aboutsummaryrefslogtreecommitdiffstats
path: root/src/plugins/cppeditor/cppelementevaluator.cpp
blob: df2ee98c2acccda7919d93891c66702d0375cf07 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
// Copyright (C) 2016 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0

#include "cppelementevaluator.h"

#include "cppmodelmanager.h"
#include "cpptoolsreuse.h"
#include "symbolfinder.h"
#include "typehierarchybuilder.h"

#include <texteditor/textdocument.h>

#include <cplusplus/ExpressionUnderCursor.h>
#include <cplusplus/Icons.h>
#include <cplusplus/TypeOfExpression.h>

#include <utils/async.h>

#include <QDir>
#include <QQueue>
#include <QSet>

using namespace CPlusPlus;
using namespace Utils;

namespace CppEditor::Internal {

static QStringList stripName(const QString &name)
{
    QStringList all;
    all << name;
    int colonColon = 0;
    const int size = name.size();
    while ((colonColon = name.indexOf(QLatin1String("::"), colonColon)) != -1) {
        all << name.right(size - colonColon - 2);
        colonColon += 2;
    }
    return all;
}

CppElement::CppElement() = default;

CppElement::~CppElement() = default;

CppClass *CppElement::toCppClass()
{
    return nullptr;
}

class Unknown : public CppElement
{
public:
    explicit Unknown(const QString &type) : type(type)
    {
        tooltip = type;
    }

public:
    QString type;
};

class CppInclude : public CppElement
{
public:
    explicit CppInclude(const Document::Include &includeFile)
        : path(includeFile.resolvedFileName())
        , fileName(path.fileName())
    {
        helpCategory = Core::HelpItem::Brief;
        helpIdCandidates = QStringList(fileName);
        helpMark = fileName;
        link = Utils::Link(path);
        tooltip = path.toUserOutput();
    }

public:
    FilePath path;
    QString fileName;
};

class CppMacro : public CppElement
{
public:
    explicit CppMacro(const Macro &macro)
    {
        helpCategory = Core::HelpItem::Macro;
        const QString macroName = QString::fromUtf8(macro.name(), macro.name().size());
        helpIdCandidates = QStringList(macroName);
        helpMark = macroName;
        link = Link(macro.filePath(), macro.line());
        tooltip = macro.toStringWithLineBreaks();
    }
};

// CppDeclarableElement
CppDeclarableElement::CppDeclarableElement(Symbol *declaration)
    : CppElement()
    , iconType(CPlusPlus::Icons::iconTypeForSymbol(declaration))
{
    Overview overview;
    overview.showArgumentNames = true;
    overview.showReturnTypes = true;
    overview.showTemplateParameters = true;
    name = overview.prettyName(declaration->name());
    if (declaration->enclosingScope()->asClass() ||
        declaration->enclosingScope()->asNamespace() ||
        declaration->enclosingScope()->asEnum() ||
        declaration->enclosingScope()->asTemplate()) {
        qualifiedName = overview.prettyName(LookupContext::fullyQualifiedName(declaration));
        helpIdCandidates = stripName(qualifiedName);
    } else {
        qualifiedName = name;
        helpIdCandidates.append(name);
    }

    tooltip = overview.prettyType(declaration->type(), qualifiedName);
    link = declaration->toLink();
    helpMark = name;
}

class CppNamespace : public CppDeclarableElement
{
public:
    explicit CppNamespace(Symbol *declaration)
        : CppDeclarableElement(declaration)
    {
        helpCategory = Core::HelpItem::ClassOrNamespace;
        tooltip = qualifiedName;
    }
};

CppClass::CppClass(Symbol *declaration) : CppDeclarableElement(declaration)
{
    helpCategory = Core::HelpItem::ClassOrNamespace;
    tooltip = qualifiedName;
}

CppClass *CppClass::toCppClass()
{
    return this;
}

void CppClass::lookupBases(const QFuture<void> &future, Symbol *declaration,
                           const LookupContext &context)
{
    ClassOrNamespace *hierarchy = context.lookupType(declaration);
    if (!hierarchy)
        return;
    QSet<ClassOrNamespace *> visited;
    addBaseHierarchy(future, context, hierarchy, &visited);
}

void CppClass::addBaseHierarchy(const QFuture<void> &future, const LookupContext &context,
                                ClassOrNamespace *hierarchy, QSet<ClassOrNamespace *> *visited)
{
    if (future.isCanceled())
        return;
    visited->insert(hierarchy);
    const QList<ClassOrNamespace *> &baseClasses = hierarchy->usings();
    for (ClassOrNamespace *baseClass : baseClasses) {
        const QList<Symbol *> &symbols = baseClass->symbols();
        for (Symbol *symbol : symbols) {
            if (!symbol->asClass())
                continue;
            ClassOrNamespace *baseHierarchy = context.lookupType(symbol);
            if (baseHierarchy && !visited->contains(baseHierarchy)) {
                CppClass classSymbol(symbol);
                classSymbol.addBaseHierarchy(future, context, baseHierarchy, visited);
                bases.append(classSymbol);
            }
        }
    }
}

void CppClass::lookupDerived(const QFuture<void> &future, Symbol *declaration,
                             const Snapshot &snapshot)
{
    snapshot.updateDependencyTable(future);
    if (future.isCanceled())
        return;
    addDerivedHierarchy(TypeHierarchyBuilder::buildDerivedTypeHierarchy(
                        declaration, snapshot, future));
}

void CppClass::addDerivedHierarchy(const TypeHierarchy &hierarchy)
{
    const QList<TypeHierarchy> derivedHierarchies = hierarchy.hierarchy();
    for (const TypeHierarchy &derivedHierarchy : derivedHierarchies) {
        CppClass classSymbol(derivedHierarchy.symbol());
        classSymbol.addDerivedHierarchy(derivedHierarchy);
        derived.append(classSymbol);
    }
}

class CppFunction : public CppDeclarableElement
{
public:
    explicit CppFunction(Symbol *declaration)
        : CppDeclarableElement(declaration)
    {
        helpCategory = Core::HelpItem::Function;

        const FullySpecifiedType &type = declaration->type();

        // Functions marks can be found either by the main overload or signature based
        // (with no argument names and no return). Help ids have no signature at all.
        Overview overview;
        overview.showDefaultArguments = false;
        helpMark = overview.prettyType(type, name);

        overview.showFunctionSignatures = false;
        helpIdCandidates.append(overview.prettyName(declaration->name()));
    }
};

class CppEnum : public CppDeclarableElement
{
public:
    explicit CppEnum(Enum *declaration)
        : CppDeclarableElement(declaration)
    {
        helpCategory = Core::HelpItem::Enum;
        tooltip = qualifiedName;
    }
};

class CppTypedef : public CppDeclarableElement
{
public:
    explicit CppTypedef(Symbol *declaration)
        : CppDeclarableElement(declaration)
    {
        helpCategory = Core::HelpItem::Typedef;
        Overview overview;
        overview.showTemplateParameters = true;
        tooltip = overview.prettyType(declaration->type(), qualifiedName);
    }
};

class CppVariable : public CppDeclarableElement
{
public:
    explicit CppVariable(Symbol *declaration, const LookupContext &context, Scope *scope)
        : CppDeclarableElement(declaration)
    {
        const FullySpecifiedType &type = declaration->type();

        const Name *typeName = nullptr;
        if (type->asNamedType()) {
            typeName = type->asNamedType()->name();
        } else if (type->asPointerType() || type->asReferenceType()) {
            FullySpecifiedType associatedType;
            if (type->asPointerType())
                associatedType = type->asPointerType()->elementType();
            else
                associatedType = type->asReferenceType()->elementType();
            if (associatedType->asNamedType())
                typeName = associatedType->asNamedType()->name();
        }

        if (typeName) {
            if (ClassOrNamespace *clazz = context.lookupType(typeName, scope)) {
                if (!clazz->symbols().isEmpty()) {
                    Overview overview;
                    Symbol *symbol = clazz->symbols().at(0);
                    const QString &name = overview.prettyName(
                        LookupContext::fullyQualifiedName(symbol));
                    if (!name.isEmpty()) {
                        tooltip = name;
                        helpCategory = Core::HelpItem::ClassOrNamespace;
                        const QStringList &allNames = stripName(name);
                        if (!allNames.isEmpty()) {
                            helpMark = allNames.last();
                            helpIdCandidates = allNames;
                        }
                    }
                }
            }
        }
    }
};

class CppEnumerator : public CppDeclarableElement
{
public:
    explicit CppEnumerator(EnumeratorDeclaration *declaration)
        : CppDeclarableElement(declaration)
    {
        helpCategory = Core::HelpItem::Enum;

        Overview overview;

        Symbol *enumSymbol = declaration->enclosingScope();
        const QString enumName = overview.prettyName(LookupContext::fullyQualifiedName(enumSymbol));
        const QString enumeratorName = overview.prettyName(declaration->name());
        QString enumeratorValue;
        if (const StringLiteral *value = declaration->constantValue())
            enumeratorValue = QString::fromUtf8(value->chars(), value->size());

        helpMark = overview.prettyName(enumSymbol->name());

        tooltip = enumeratorName;
        if (!enumName.isEmpty())
            tooltip.prepend(enumName + QLatin1Char(' '));
        if (!enumeratorValue.isEmpty())
            tooltip.append(QLatin1String(" = ") + enumeratorValue);
    }
};

static bool isCppClass(Symbol *symbol)
{
    return symbol->asClass() || symbol->asForwardClassDeclaration()
            || (symbol->asTemplate() && symbol->asTemplate()->declaration()
                && (symbol->asTemplate()->declaration()->asClass()
                    || symbol->asTemplate()->declaration()->asForwardClassDeclaration()));
}

static Symbol *followClassDeclaration(Symbol *symbol, const Snapshot &snapshot, SymbolFinder symbolFinder,
                               LookupContext *context = nullptr)
{
    if (!symbol->asForwardClassDeclaration())
        return symbol;

    Symbol *classDeclaration = symbolFinder.findMatchingClassDeclaration(symbol, snapshot);
    if (!classDeclaration)
        return symbol;

    if (context) {
        const Document::Ptr declarationDocument = snapshot.document(classDeclaration->filePath());
        if (declarationDocument != context->thisDocument())
            (*context) = LookupContext(declarationDocument, snapshot);
    }
    return classDeclaration;
}

static Symbol *followTemplateAsClass(Symbol *symbol)
{
    if (Template *t = symbol->asTemplate(); t && t->declaration() && t->declaration()->asClass())
        return t->declaration()->asClass();
    return symbol;
}

static void createTypeHierarchy(QPromise<std::shared_ptr<CppElement>> &promise,
                                const Snapshot &snapshot,
                                const LookupItem &lookupItem,
                                const LookupContext &context,
                                SymbolFinder symbolFinder)
{
    if (promise.isCanceled())
        return;

    Symbol *declaration = lookupItem.declaration();
    if (!declaration)
        return;

    if (!isCppClass(declaration))
        return;

    LookupContext contextToUse = context;
    declaration = followClassDeclaration(declaration, snapshot, symbolFinder, &contextToUse);
    declaration = followTemplateAsClass(declaration);

    if (promise.isCanceled())
        return;
    std::shared_ptr<CppClass> cppClass(new CppClass(declaration));
    const QFuture<void> future = QFuture<void>(promise.future());
    cppClass->lookupBases(future, declaration, contextToUse);
    if (promise.isCanceled())
        return;
    cppClass->lookupDerived(future, declaration, snapshot);
    if (promise.isCanceled())
        return;
    promise.addResult(cppClass);
}

static std::shared_ptr<CppElement> handleLookupItemMatch(const Snapshot &snapshot,
                                                        const LookupItem &lookupItem,
                                                        const LookupContext &context,
                                                        SymbolFinder symbolFinder)
{
    std::shared_ptr<CppElement> element;
    Symbol *declaration = lookupItem.declaration();
    if (!declaration) {
        const QString &type = Overview().prettyType(lookupItem.type(), QString());
        element = std::shared_ptr<CppElement>(new Unknown(type));
    } else {
        const FullySpecifiedType &type = declaration->type();
        if (declaration->asNamespace()) {
            element = std::shared_ptr<CppElement>(new CppNamespace(declaration));
        } else if (isCppClass(declaration)) {
            LookupContext contextToUse = context;
            declaration = followClassDeclaration(declaration, snapshot, symbolFinder, &contextToUse);
            element = std::shared_ptr<CppElement>(new CppClass(declaration));
        } else if (Enum *enumDecl = declaration->asEnum()) {
            element = std::shared_ptr<CppElement>(new CppEnum(enumDecl));
        } else if (auto enumerator = dynamic_cast<EnumeratorDeclaration *>(declaration)) {
            element = std::shared_ptr<CppElement>(new CppEnumerator(enumerator));
        } else if (declaration->isTypedef()) {
            element = std::shared_ptr<CppElement>(new CppTypedef(declaration));
        } else if (declaration->asFunction()
                   || (type.isValid() && type->asFunctionType())
                   || declaration->asTemplate()) {
            element = std::shared_ptr<CppElement>(new CppFunction(declaration));
        } else if (declaration->asDeclaration() && type.isValid()) {
            element = std::shared_ptr<CppElement>(
                new CppVariable(declaration, context, lookupItem.scope()));
        } else {
            element = std::shared_ptr<CppElement>(new CppDeclarableElement(declaration));
        }
    }
    return element;
}

//  special case for bug QTCREATORBUG-4780
static bool shouldOmitElement(const LookupItem &lookupItem, const Scope *scope)
{
    return !lookupItem.declaration() && scope && scope->asFunction()
            && lookupItem.type().match(scope->asFunction()->returnType());
}

using namespace std::placeholders;
using ExecFunction = std::function<QFuture<std::shared_ptr<CppElement>>
            (const CPlusPlus::Snapshot &, const CPlusPlus::LookupItem &,
             const CPlusPlus::LookupContext &)>;
using SourceFunction = std::function<bool(const CPlusPlus::Snapshot &,
                                          CPlusPlus::Document::Ptr &,
                                          CPlusPlus::Scope **, QString &)>;

static QFuture<std::shared_ptr<CppElement>> createFinishedFuture()
{
    QFutureInterface<std::shared_ptr<CppElement>> futureInterface;
    futureInterface.reportStarted();
    futureInterface.reportFinished();
    return futureInterface.future();
}

static LookupItem findLookupItem(const CPlusPlus::Snapshot &snapshot, CPlusPlus::Document::Ptr &doc,
       Scope *scope, const QString &expression, LookupContext *lookupContext, bool followTypedef)
{
    TypeOfExpression typeOfExpression;
    typeOfExpression.init(doc, snapshot);
    // make possible to instantiate templates
    typeOfExpression.setExpandTemplates(true);
    const QList<LookupItem> &lookupItems = typeOfExpression(expression.toUtf8(), scope);
    *lookupContext = typeOfExpression.context();
    if (lookupItems.isEmpty())
        return LookupItem();

    auto isInteresting = [followTypedef](Symbol *symbol) {
        return symbol && (!followTypedef || (symbol->asClass() || symbol->asTemplate()
               || symbol->asForwardClassDeclaration() || symbol->isTypedef()));
    };

    for (const LookupItem &item : lookupItems) {
        if (shouldOmitElement(item, scope))
            continue;
        Symbol *symbol = item.declaration();
        if (!isInteresting(symbol))
            continue;
        if (followTypedef && symbol->isTypedef()) {
            CPlusPlus::NamedType *namedType = symbol->type()->asNamedType();
            if (!namedType) {
                // Anonymous aggregate such as: typedef struct {} Empty;
                continue;
            }
            return TypeHierarchyBuilder::followTypedef(*lookupContext,
                         namedType->name(), symbol->enclosingScope());
        }
        return item;
    }
    return LookupItem();
}

static QFuture<std::shared_ptr<CppElement>> exec(SourceFunction &&sourceFunction,
                                                 ExecFunction &&execFunction,
                                                 bool followTypedef = true)
{
    const Snapshot &snapshot = CppModelManager::snapshot();

    Document::Ptr doc;
    QString expression;
    Scope *scope = nullptr;
    if (!std::invoke(std::forward<SourceFunction>(sourceFunction), snapshot, doc, &scope, expression))
        return createFinishedFuture();

    LookupContext lookupContext;
    const LookupItem &lookupItem = findLookupItem(snapshot, doc, scope, expression, &lookupContext,
                                                  followTypedef);
    if (!lookupItem.declaration())
        return createFinishedFuture();

    return std::invoke(std::forward<ExecFunction>(execFunction), snapshot, lookupItem, lookupContext);
}

static QFuture<std::shared_ptr<CppElement>> asyncExec(
        const CPlusPlus::Snapshot &snapshot, const CPlusPlus::LookupItem &lookupItem,
        const CPlusPlus::LookupContext &lookupContext)
{
    return Utils::asyncRun(&createTypeHierarchy, snapshot, lookupItem, lookupContext,
                           *CppModelManager::symbolFinder());
}

class FromExpressionFunctor
{
public:
    FromExpressionFunctor(const QString &expression, const FilePath &filePath)
        : m_expression(expression)
        , m_filePath(filePath)
    {}

    bool operator()(const CPlusPlus::Snapshot &snapshot, Document::Ptr &doc, Scope **scope,
                    QString &expression)
    {
        doc = snapshot.document(m_filePath);
        if (doc.isNull())
            return false;

        expression = m_expression;

        // Fetch the expression's code
        *scope = doc->globalNamespace();
        return true;
    }
private:
    const QString m_expression;
    const FilePath m_filePath;
};

QFuture<std::shared_ptr<CppElement>> CppElementEvaluator::asyncExecute(const QString &expression,
                                                                       const FilePath &filePath)
{
    return exec(FromExpressionFunctor(expression, filePath), asyncExec);
}

class FromGuiFunctor
{
public:
    FromGuiFunctor(TextEditor::TextEditorWidget *editor)
        : m_editor(editor)
        , m_tc(editor->textCursor())
    {}

    bool operator()(const CPlusPlus::Snapshot &snapshot, Document::Ptr &doc, Scope **scope,
                    QString &expression)
    {
        doc = snapshot.document(m_editor->textDocument()->filePath());
        if (!doc)
            return false;

        int line = 0;
        int column = 0;
        const int pos = m_tc.position();
        m_editor->convertPosition(pos, &line, &column);

        checkDiagnosticMessage(pos);

        if (matchIncludeFile(doc, line) || matchMacroInUse(doc, pos))
            return false;

        moveCursorToEndOfIdentifier(&m_tc);
        ExpressionUnderCursor expressionUnderCursor(doc->languageFeatures());
        expression = expressionUnderCursor(m_tc);

        // Fetch the expression's code
        *scope = doc->scopeAt(line, column);
        return true;
    }
    QFuture<std::shared_ptr<CppElement>> syncExec(const CPlusPlus::Snapshot &,
                     const CPlusPlus::LookupItem &, const CPlusPlus::LookupContext &);

private:
    void checkDiagnosticMessage(int pos);
    bool matchIncludeFile(const CPlusPlus::Document::Ptr &document, int line);
    bool matchMacroInUse(const CPlusPlus::Document::Ptr &document, int pos);

public:
    void clear();

    TextEditor::TextEditorWidget *m_editor;
    QTextCursor m_tc;
    std::shared_ptr<CppElement> m_element;
    QString m_diagnosis;
};

QFuture<std::shared_ptr<CppElement>> FromGuiFunctor::syncExec(
        const CPlusPlus::Snapshot &snapshot, const CPlusPlus::LookupItem &lookupItem,
        const CPlusPlus::LookupContext &lookupContext)
{
    QFutureInterface<std::shared_ptr<CppElement>> futureInterface;
    futureInterface.reportStarted();
    m_element = handleLookupItemMatch(snapshot, lookupItem, lookupContext,
                                      *CppModelManager::symbolFinder());
    futureInterface.reportResult(m_element);
    futureInterface.reportFinished();
    return futureInterface.future();
}

void FromGuiFunctor::checkDiagnosticMessage(int pos)
{
    const QList<QTextEdit::ExtraSelection> &selections = m_editor->extraSelections(
        TextEditor::TextEditorWidget::CodeWarningsSelection);
    for (const QTextEdit::ExtraSelection &sel : selections) {
        if (pos >= sel.cursor.selectionStart() && pos <= sel.cursor.selectionEnd()) {
            m_diagnosis = sel.format.toolTip();
            break;
        }
    }
}

bool FromGuiFunctor::matchIncludeFile(const Document::Ptr &document, int line)
{
    const QList<Document::Include> &includes = document->resolvedIncludes();
    for (const Document::Include &includeFile : includes) {
        if (includeFile.line() == line) {
            m_element = std::shared_ptr<CppElement>(new CppInclude(includeFile));
            return true;
        }
    }
    return false;
}

bool FromGuiFunctor::matchMacroInUse(const Document::Ptr &document, int pos)
{
    for (const Document::MacroUse &use : document->macroUses()) {
        if (use.containsUtf16charOffset(pos)) {
            const int begin = use.utf16charsBegin();
            if (pos < begin + use.macro().nameToQString().size()) {
                m_element = std::shared_ptr<CppElement>(new CppMacro(use.macro()));
                return true;
            }
        }
    }
    return false;
}

void FromGuiFunctor::clear()
{
    m_element.reset();
    m_diagnosis.clear();
}

class CppElementEvaluatorPrivate
{
public:
    CppElementEvaluatorPrivate(TextEditor::TextEditorWidget *editor) : m_functor(editor) {}
    FromGuiFunctor m_functor;
};

CppElementEvaluator::CppElementEvaluator(TextEditor::TextEditorWidget *editor)
    : d(new CppElementEvaluatorPrivate(editor))
{}

CppElementEvaluator::~CppElementEvaluator()
{
    delete d;
}

void CppElementEvaluator::setTextCursor(const QTextCursor &tc)
{
    d->m_functor.m_tc = tc;
}

QFuture<std::shared_ptr<CppElement>> CppElementEvaluator::asyncExecute(
        TextEditor::TextEditorWidget *editor)
{
    return exec(FromGuiFunctor(editor), asyncExec);
}

void CppElementEvaluator::execute()
{
    d->m_functor.clear();
    exec(std::ref(d->m_functor), std::bind(&FromGuiFunctor::syncExec, &d->m_functor, _1, _2, _3), false);
}

const std::shared_ptr<CppElement> &CppElementEvaluator::cppElement() const
{
    return d->m_functor.m_element;
}

bool CppElementEvaluator::hasDiagnosis() const
{
    return !d->m_functor.m_diagnosis.isEmpty();
}

const QString &CppElementEvaluator::diagnosis() const
{
    return d->m_functor.m_diagnosis;
}

Utils::Link CppElementEvaluator::linkFromExpression(const QString &expression, const FilePath &filePath)
{
    const Snapshot &snapshot = CppModelManager::snapshot();
    Document::Ptr doc = snapshot.document(filePath);
    if (doc.isNull())
        return Utils::Link();
    Scope *scope = doc->globalNamespace();

    TypeOfExpression typeOfExpression;
    typeOfExpression.init(doc, snapshot);
    typeOfExpression.setExpandTemplates(true);
    const QList<LookupItem> &lookupItems = typeOfExpression(expression.toUtf8(), scope);
    if (lookupItems.isEmpty())
        return Utils::Link();

    for (const LookupItem &item : lookupItems) {
        Symbol *symbol = item.declaration();
        if (!symbol)
            continue;
        if (!symbol->asClass() && !symbol->asTemplate())
            continue;
        return symbol->toLink();
    }
    return Utils::Link();
}

} // namespace CppEditor::Internal