cppfollowsymbolundercursor.cpp 27.8 KB
Newer Older
1 2
/****************************************************************************
**
3
** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
4 5 6 7 8 9 10 11 12
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia.  For licensing terms and
Eike Ziller's avatar
Eike Ziller committed
13 14
** conditions see http://www.qt.io/licensing.  For further information
** use the contact form at http://www.qt.io/contact-us.
15 16 17
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
Eike Ziller's avatar
Eike Ziller committed
18 19 20 21 22 23
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file.  Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
24 25 26 27 28 29 30 31 32 33
**
** In addition, as a special exception, Digia gives you certain additional
** rights.  These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/


#include "cppfollowsymbolundercursor.h"
#include "cppeditor.h"
34
#include "cppvirtualfunctionassistprovider.h"
35 36 37 38

#include <cplusplus/ASTPath.h>
#include <cplusplus/BackwardsScanner.h>
#include <cplusplus/ExpressionUnderCursor.h>
39
#include <cplusplus/ResolveExpression.h>
40 41
#include <cplusplus/SimpleLexer.h>
#include <cplusplus/TypeOfExpression.h>
42
#include <cpptools/cppmodelmanager.h>
43
#include <cpptools/functionutils.h>
44
#include <cpptools/cpptoolsreuse.h>
45
#include <cpptools/symbolfinder.h>
46
#include <texteditor/textdocumentlayout.h>
47 48 49 50 51 52 53 54 55 56 57
#include <utils/qtcassert.h>

#include <QList>
#include <QSet>

using namespace CPlusPlus;
using namespace CppTools;
using namespace CppEditor;
using namespace CppEditor::Internal;
using namespace TextEditor;

58
typedef TextEditorWidget::Link Link;
59 60 61

namespace {

62 63 64 65 66
class VirtualFunctionHelper {
public:
    VirtualFunctionHelper(const TypeOfExpression &typeOfExpression,
                          Scope *scope,
                          const Document::Ptr &document,
67 68
                          const Snapshot &snapshot,
                          SymbolFinder *symbolFinder);
69

70 71 72 73 74
    bool canLookupVirtualFunctionOverrides(Function *function);

    /// Returns != 0 if canLookupVirtualFunctionOverrides() succeeded.
    Class *staticClassOfFunctionCallExpression() const
    { return m_staticClassOfFunctionCallExpression; }
75 76 77 78 79

private:
    VirtualFunctionHelper();
    Q_DISABLE_COPY(VirtualFunctionHelper)

80
    Class *staticClassOfFunctionCallExpression_internal() const;
81 82

private:
83
    // Provided
84 85 86 87
    const Document::Ptr m_expressionDocument;
    Scope *m_scope;
    const Document::Ptr &m_document;
    const Snapshot &m_snapshot;
88 89 90 91 92 93 94
    SymbolFinder *m_finder;

    // Determined
    ExpressionAST *m_baseExpressionAST;
    Function *m_function;
    int m_accessTokenKind;
    Class *m_staticClassOfFunctionCallExpression; // Output
95 96 97 98 99
};

VirtualFunctionHelper::VirtualFunctionHelper(const TypeOfExpression &typeOfExpression,
                                             Scope *scope,
                                             const Document::Ptr &document,
100 101 102
                                             const Snapshot &snapshot,
                                             SymbolFinder *finder)
    : m_expressionDocument(typeOfExpression.context().expressionDocument())
103 104 105
    , m_scope(scope)
    , m_document(document)
    , m_snapshot(snapshot)
106 107 108 109 110
    , m_finder(finder)
    , m_baseExpressionAST(0)
    , m_function(0)
    , m_accessTokenKind(0)
    , m_staticClassOfFunctionCallExpression(0)
111
{
112 113 114 115 116 117
    if (ExpressionAST *expressionAST = typeOfExpression.expressionAST()) {
        if (CallAST *callAST = expressionAST->asCall()) {
            if (ExpressionAST *baseExpressionAST = callAST->base_expression)
                m_baseExpressionAST = baseExpressionAST;
        }
    }
118
}
119

120
bool VirtualFunctionHelper::canLookupVirtualFunctionOverrides(Function *function)
121
{
122 123
    m_function = function;
    if (!m_function || !m_baseExpressionAST || !m_expressionDocument || !m_document || !m_scope
124
            || m_scope->isClass() || m_scope->isFunction() || m_snapshot.isEmpty()) {
125
        return false;
126 127
    }

128 129
    bool result = false;

130
    if (IdExpressionAST *idExpressionAST = m_baseExpressionAST->asIdExpression()) {
131 132
        NameAST *name = idExpressionAST->name;
        const bool nameIsQualified = name && name->asQualifiedName();
133
        result = !nameIsQualified && FunctionUtils::isVirtualFunction(
134
                    function, LookupContext(m_document, m_snapshot));
135
    } else if (MemberAccessAST *memberAccessAST = m_baseExpressionAST->asMemberAccess()) {
136 137
        NameAST *name = memberAccessAST->member_name;
        const bool nameIsQualified = name && name->asQualifiedName();
138
        if (!nameIsQualified && FunctionUtils::isVirtualFunction(
139
                    function, LookupContext(m_document, m_snapshot))) {
140
            TranslationUnit *unit = m_expressionDocument->translationUnit();
141
            QTC_ASSERT(unit, return false);
142
            m_accessTokenKind = unit->tokenKind(memberAccessAST->access_token);
143

144
            if (m_accessTokenKind == T_ARROW) {
145
                result = true;
146
            } else if (m_accessTokenKind == T_DOT) {
147 148 149
                TypeOfExpression typeOfExpression;
                typeOfExpression.init(m_document, m_snapshot);
                typeOfExpression.setExpandTemplates(true);
150
                const QList<LookupItem> items = typeOfExpression.reference(
151
                            memberAccessAST->base_expression, m_document, m_scope);
152 153 154 155
                if (!items.isEmpty()) {
                    const LookupItem item = items.first();
                    if (Symbol *declaration = item.declaration())
                        result = declaration->type()->isReferenceType();
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
    if (!result)
        return false;
    return (m_staticClassOfFunctionCallExpression = staticClassOfFunctionCallExpression_internal());
}

/// For "f()" in "class C { void g() { f(); };" return class C.
/// For "c->f()" in "{ C *c; c->f(); }" return class C.
Class *VirtualFunctionHelper::staticClassOfFunctionCallExpression_internal() const
{
    if (!m_finder)
        return 0;

    Class *result = 0;

    if (m_baseExpressionAST->asIdExpression()) {
        for (Scope *s = m_scope; s ; s = s->enclosingScope()) {
            if (Function *function = s->asFunction()) {
                result = m_finder->findMatchingClassDeclaration(function, m_snapshot);
                break;
            }
        }
    } else if (MemberAccessAST *memberAccessAST = m_baseExpressionAST->asMemberAccess()) {
        QTC_ASSERT(m_accessTokenKind == T_ARROW || m_accessTokenKind == T_DOT, return result);
        TypeOfExpression typeOfExpression;
        typeOfExpression.init(m_document, m_snapshot);
        typeOfExpression.setExpandTemplates(true);
        const QList<LookupItem> items = typeOfExpression(memberAccessAST->base_expression,
188
                                                         m_expressionDocument, m_scope);
189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204
        ResolveExpression resolveExpression(typeOfExpression.context());
        ClassOrNamespace *binding = resolveExpression.baseExpression(items, m_accessTokenKind);
        if (binding) {
            if (Class *klass = binding->rootClass()) {
                result = klass;
            } else {
                const QList<Symbol *> symbols = binding->symbols();
                if (!symbols.isEmpty()) {
                    Symbol * const first = symbols.first();
                    if (first->isForwardClassDeclaration())
                        result = m_finder->findMatchingClassDeclaration(first, m_snapshot);
                }
            }
        }
    }

205
    return result;
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
Link findMacroLink_helper(const QByteArray &name, Document::Ptr doc, const Snapshot &snapshot,
                          QSet<QString> *processed)
{
    if (doc && !name.startsWith('<') && !processed->contains(doc->fileName())) {
        processed->insert(doc->fileName());

        foreach (const Macro &macro, doc->definedMacros()) {
            if (macro.name() == name) {
                Link link;
                link.targetFileName = macro.fileName();
                link.targetLine = macro.line();
                return link;
            }
        }

        const QList<Document::Include> includes = doc->resolvedIncludes();
        for (int index = includes.size() - 1; index != -1; --index) {
            const Document::Include &i = includes.at(index);
            Link link = findMacroLink_helper(name, snapshot.document(i.resolvedFileName()),
                                             snapshot, processed);
            if (link.hasValidTarget())
                return link;
        }
    }

    return Link();
}

Link findMacroLink(const QByteArray &name, const Document::Ptr &doc)
{
    if (!name.isEmpty()) {
        if (doc) {
240
            const Snapshot snapshot = CppModelManager::instance()->snapshot();
241 242 243 244 245 246 247 248
            QSet<QString> processed;
            return findMacroLink_helper(name, doc, snapshot, &processed);
        }
    }

    return Link();
}

249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266
/// Considers also forward declared templates.
static bool isForwardClassDeclaration(Type *type)
{
    if (!type)
        return false;

    if (type->isForwardClassDeclarationType()) {
        return true;
    } else if (Template *templ = type->asTemplateType()) {
        if (Symbol *declaration = templ->declaration()) {
            if (declaration->isForwardClassDeclaration())
                return true;
        }
    }

    return false;
}

267 268 269 270 271 272 273
inline LookupItem skipForwardDeclarations(const QList<LookupItem> &resolvedSymbols)
{
    QList<LookupItem> candidates = resolvedSymbols;

    LookupItem result = candidates.first();
    const FullySpecifiedType ty = result.type().simplified();

274
    if (isForwardClassDeclaration(ty.type())) {
275 276 277
        while (!candidates.isEmpty()) {
            LookupItem r = candidates.takeFirst();

278
            if (!isForwardClassDeclaration(r.type().type())) {
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
                result = r;
                break;
            }
        }
    }

    if (ty->isObjCForwardClassDeclarationType()) {
        while (!candidates.isEmpty()) {
            LookupItem r = candidates.takeFirst();

            if (!r.type()->isObjCForwardClassDeclarationType()) {
                result = r;
                break;
            }
        }
    }

    if (ty->isObjCForwardProtocolDeclarationType()) {
        while (!candidates.isEmpty()) {
            LookupItem r = candidates.takeFirst();

            if (!r.type()->isObjCForwardProtocolDeclarationType()) {
                result = r;
                break;
            }
        }
    }

    return result;
}

310
CppEditorWidget::Link attemptFuncDeclDef(const QTextCursor &cursor,
311
    CppEditorWidget *, Snapshot snapshot, const Document::Ptr &document,
312 313 314
    SymbolFinder *symbolFinder)
{
    Link result;
315 316 317
    QTC_ASSERT(document, return result);

    snapshot.insert(document);
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

    QList<AST *> path = ASTPath(document)(cursor);

    if (path.size() < 5)
        return result;

    NameAST *name = path.last()->asName();
    if (!name)
        return result;

    if (QualifiedNameAST *qName = path.at(path.size() - 2)->asQualifiedName()) {
        // TODO: check which part of the qualified name we're on
        if (qName->unqualified_name != name)
            return result;
    }

    for (int i = path.size() - 1; i != -1; --i) {
        AST *node = path.at(i);

        if (node->asParameterDeclaration() != 0)
            return result;
    }

    AST *declParent = 0;
    DeclaratorAST *decl = 0;
    for (int i = path.size() - 2; i > 0; --i) {
        if ((decl = path.at(i)->asDeclarator()) != 0) {
            declParent = path.at(i - 1);
            break;
        }
    }
    if (!decl || !declParent)
        return result;
    if (!decl->postfix_declarator_list || !decl->postfix_declarator_list->value)
        return result;
    FunctionDeclaratorAST *funcDecl = decl->postfix_declarator_list->value->asFunctionDeclarator();
    if (!funcDecl)
        return result;

    Symbol *target = 0;
    if (FunctionDefinitionAST *funDef = declParent->asFunctionDefinition()) {
        QList<Declaration *> candidates =
                symbolFinder->findMatchingDeclaration(LookupContext(document, snapshot),
                                                        funDef->symbol);
        if (!candidates.isEmpty()) // TODO: improve disambiguation
            target = candidates.first();
    } else if (declParent->asSimpleDeclaration()) {
        target = symbolFinder->findMatchingDefinition(funcDecl->symbol, snapshot);
    }

    if (target) {
369
        result = CppTools::linkToSymbol(target);
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

        unsigned startLine, startColumn, endLine, endColumn;
        document->translationUnit()->getTokenStartPosition(name->firstToken(), &startLine,
                                                           &startColumn);
        document->translationUnit()->getTokenEndPosition(name->lastToken() - 1, &endLine,
                                                         &endColumn);

        QTextDocument *textDocument = cursor.document();
        result.linkTextStart =
                textDocument->findBlockByNumber(startLine - 1).position() + startColumn - 1;
        result.linkTextEnd =
                textDocument->findBlockByNumber(endLine - 1).position() + endColumn - 1;
    }

    return result;
}

Symbol *findDefinition(Symbol *symbol, const Snapshot &snapshot, SymbolFinder *symbolFinder)
{
    if (symbol->isFunction())
        return 0; // symbol is a function definition.

    else if (!symbol->type()->isFunctionType())
        return 0; // not a function declaration

    return symbolFinder->findMatchingDefinition(symbol, snapshot);
}

398 399
} // anonymous namespace

400
FollowSymbolUnderCursor::FollowSymbolUnderCursor(CppEditorWidget *widget)
401
    : m_widget(widget)
402 403 404 405 406
    , m_virtualFunctionAssistProvider(new VirtualFunctionAssistProvider)
{
}

FollowSymbolUnderCursor::~FollowSymbolUnderCursor()
407
{
408
    delete m_virtualFunctionAssistProvider;
409 410
}

411
static int skipMatchingParentheses(const Tokens &tokens, int idx, int initialDepth)
412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427
{
    int j = idx;
    int depth = initialDepth;

    for (; j < tokens.size(); ++j) {
        if (tokens.at(j).is(T_LPAREN)) {
            ++depth;
        } else if (tokens.at(j).is(T_RPAREN)) {
            if (!--depth)
                break;
        }
    }

    return j;
}

428
TextEditorWidget::Link FollowSymbolUnderCursor::findLink(const QTextCursor &cursor,
429 430
    bool resolveTarget, const Snapshot &theSnapshot, const Document::Ptr &documentFromSemanticInfo,
    SymbolFinder *symbolFinder, bool inNextSplit)
431 432 433
{
    Link link;

434 435
    Snapshot snapshot = theSnapshot;

436
    // Move to end of identifier
437
    QTextCursor tc = cursor;
438 439
    QTextDocument *document = m_widget->document();
    QChar ch = document->characterAt(tc.position());
440
    while (CppTools::isValidIdentifierChar(ch)) {
441
        tc.movePosition(QTextCursor::NextCharacter);
442
        ch = document->characterAt(tc.position());
443 444
    }

445 446 447 448
    // Try to macth decl/def. For this we need the semantic doc with the AST.
    if (documentFromSemanticInfo
            && documentFromSemanticInfo->translationUnit()
            && documentFromSemanticInfo->translationUnit()->ast()) {
449
        int pos = tc.position();
450
        while (document->characterAt(pos).isSpace())
451
            ++pos;
452
        if (document->characterAt(pos) == QLatin1Char('(')) {
453 454
            link = attemptFuncDeclDef(cursor, m_widget, snapshot, documentFromSemanticInfo,
                                      symbolFinder);
455 456 457 458 459 460
            if (link.hasValidLinkText())
                return link;
        }
    }

    int lineNumber = 0, positionInBlock = 0;
461
    m_widget->convertPosition(cursor.position(), &lineNumber, &positionInBlock);
462 463 464 465 466 467 468
    const unsigned line = lineNumber;
    const unsigned column = positionInBlock + 1;

    // Try to find a signal or slot inside SIGNAL() or SLOT()
    int beginOfToken = 0;
    int endOfToken = 0;

469 470 471 472
    LanguageFeatures features;
    features.qtEnabled = true;
    features.qtKeywordsEnabled = true;
    features.qtMocRunEnabled = true;
473 474
    features.objCEnabled = true;
    features.cxx11Enabled = true;
475

476
    SimpleLexer tokenize;
477
    tokenize.setLanguageFeatures(features);
478
    const QString blockText = cursor.block().text();
479
    const Tokens tokens = tokenize(blockText, BackwardsScanner::previousBlockState(cursor.block()));
480 481 482 483 484 485

    bool recognizedQtMethod = false;

    for (int i = 0; i < tokens.size(); ++i) {
        const Token &tk = tokens.at(i);

486 487
        if (((unsigned) positionInBlock) >= tk.utf16charsBegin()
                && ((unsigned) positionInBlock) < tk.utf16charsEnd()) {
488
            int closingParenthesisPos = tokens.size();
489 490 491 492 493 494 495 496
            if (i >= 2 && tokens.at(i).is(T_IDENTIFIER) && tokens.at(i - 1).is(T_LPAREN)
                && (tokens.at(i - 2).is(T_SIGNAL) || tokens.at(i - 2).is(T_SLOT))) {

                // token[i] == T_IDENTIFIER
                // token[i + 1] == T_LPAREN
                // token[.....] == ....
                // token[i + n] == T_RPAREN

Orgad Shaneh's avatar
Orgad Shaneh committed
497
                if (i + 1 < tokens.size() && tokens.at(i + 1).is(T_LPAREN))
498 499 500 501 502 503 504 505 506 507 508 509 510
                    closingParenthesisPos = skipMatchingParentheses(tokens, i - 1, 0);
            } else if ((i > 3 && tk.is(T_LPAREN) && tokens.at(i - 1).is(T_IDENTIFIER)
                        && tokens.at(i - 2).is(T_LPAREN)
                    && (tokens.at(i - 3).is(T_SIGNAL) || tokens.at(i - 3).is(T_SLOT)))) {

                // skip until the closing parentheses of the SIGNAL/SLOT macro
                closingParenthesisPos = skipMatchingParentheses(tokens, i, 1);
                --i; // point to the token before the opening parenthesis
            }

            if (closingParenthesisPos < tokens.size()) {
                QTextBlock block = cursor.block();

511 512
                beginOfToken = block.position() + tokens.at(i).utf16charsBegin();
                endOfToken = block.position() + tokens.at(i).utf16charsEnd();
513

514
                tc.setPosition(block.position() + tokens.at(closingParenthesisPos).utf16charsEnd());
515
                recognizedQtMethod = true;
516 517 518 519 520
            }
            break;
        }
    }

521
    // Check if we're on an operator declaration or definition.
522
    if (!recognizedQtMethod && documentFromSemanticInfo) {
523 524 525 526 527 528
        bool cursorRegionReached = false;
        for (int i = 0; i < tokens.size(); ++i) {
            const Token &tk = tokens.at(i);

            // In this case we want to look at one token before the current position to recognize
            // an operator if the cursor is inside the actual operator: operator[$]
529 530
            if (unsigned(positionInBlock) >= tk.utf16charsBegin()
                    && unsigned(positionInBlock) <= tk.utf16charsEnd()) {
531 532 533 534 535 536 537 538 539
                cursorRegionReached = true;
                if (tk.is(T_OPERATOR)) {
                    link = attemptFuncDeclDef(cursor, m_widget, theSnapshot,
                                              documentFromSemanticInfo, symbolFinder);
                    if (link.hasValidLinkText())
                        return link;
                } else if (tk.isOperator() && i > 0 && tokens.at(i - 1).is(T_OPERATOR)) {
                    QTextCursor c = cursor;
                    c.movePosition(QTextCursor::Left, QTextCursor::MoveAnchor,
540
                                   positionInBlock - tokens.at(i - 1).utf16charsBegin());
541 542 543 544 545 546 547 548 549 550 551
                    link = attemptFuncDeclDef(c, m_widget, theSnapshot, documentFromSemanticInfo,
                                              symbolFinder);
                    if (link.hasValidLinkText())
                        return link;
                }
            } else if (cursorRegionReached) {
                break;
            }
        }
    }

552
    // Now we prefer the doc from the snapshot with macros expanded.
553
    Document::Ptr doc = snapshot.document(m_widget->textDocument()->filePath());
554
    if (!doc) {
555
        doc = documentFromSemanticInfo;
556 557 558 559 560 561
        if (!doc)
            return link;
    }

    if (!recognizedQtMethod) {
        const QTextBlock block = tc.block();
562
        int pos = cursor.positionInBlock();
563
        QChar ch = document->characterAt(cursor.position());
564
        if (pos > 0 && !isValidIdentifierChar(ch))
565 566 567 568
            --pos; // positionInBlock points to a delimiter character.
        const Token tk = SimpleLexer::tokenAt(block.text(), pos,
                                              BackwardsScanner::previousBlockState(block), true);

569 570
        beginOfToken = block.position() + tk.utf16charsBegin();
        endOfToken = block.position() + tk.utf16charsEnd();
571 572 573

        // Handle include directives
        if (tk.is(T_STRING_LITERAL) || tk.is(T_ANGLE_STRING_LITERAL)) {
574
            const unsigned lineno = cursor.blockNumber() + 1;
575 576 577 578 579 580 581 582 583 584
            foreach (const Document::Include &incl, doc->resolvedIncludes()) {
                if (incl.line() == lineno) {
                    link.targetFileName = incl.resolvedFileName();
                    link.linkTextStart = beginOfToken + 1;
                    link.linkTextEnd = endOfToken - 1;
                    return link;
                }
            }
        }

585
        if (tk.isNot(T_IDENTIFIER) && !tk.isQtKeyword())
586 587 588 589 590 591 592 593
            return link;

        tc.setPosition(endOfToken);
    }

    // Handle macro uses
    const Macro *macro = doc->findMacroDefinitionAt(line);
    if (macro) {
594
        QTextCursor macroCursor = cursor;
595
        const QByteArray name = CppTools::identifierUnderCursor(&macroCursor).toUtf8();
596 597
        if (macro->name() == name)
            return link;    //already on definition!
598 599
    } else if (const Document::MacroUse *use = doc->findMacroUseAt(endOfToken - 1)) {
        const QString fileName = use->macro().fileName();
600
        if (fileName == CppModelManager::editorConfigurationFileName()) {
601
            m_widget->showPreProcessorWidget();
602
        } else if (fileName != CppModelManager::configurationFileName()) {
603
            const Macro &macro = use->macro();
604 605
            link.targetFileName = macro.fileName();
            link.targetLine = macro.line();
606 607
            link.linkTextStart = use->utf16charsBegin();
            link.linkTextEnd = use->utf16charsEnd();
608
        }
609
        return link;
610 611 612 613 614 615 616 617 618 619 620 621
    }

    // Find the last symbol up to the cursor position
    Scope *scope = doc->scopeAt(line, column);
    if (!scope)
        return link;

    // Evaluate the type of the expression under the cursor
    ExpressionUnderCursor expressionUnderCursor;
    QString expression = expressionUnderCursor(tc);

    for (int pos = tc.position();; ++pos) {
622
        const QChar ch = document->characterAt(pos);
623 624 625 626
        if (ch.isSpace())
            continue;
        if (ch == QLatin1Char('(') && !expression.isEmpty()) {
            tc.setPosition(pos);
627
            if (TextBlockUserData::findNextClosingParenthesis(&tc, true))
628 629 630 631 632 633
                expression.append(tc.selectedText());
        }

        break;
    }

634 635
    const QSharedPointer<TypeOfExpression> typeOfExpression(new TypeOfExpression);
    typeOfExpression->init(doc, snapshot);
636
    // make possible to instantiate templates
637
    typeOfExpression->setExpandTemplates(true);
638
    const QList<LookupItem> resolvedSymbols =
639
            typeOfExpression->reference(expression.toUtf8(), scope, TypeOfExpression::Preprocess);
640 641 642 643 644 645 646 647

    if (!resolvedSymbols.isEmpty()) {
        LookupItem result = skipForwardDeclarations(resolvedSymbols);

        foreach (const LookupItem &r, resolvedSymbols) {
            if (Symbol *d = r.declaration()) {
                if (d->isDeclaration() || d->isFunction()) {
                    const QString fileName = QString::fromUtf8(d->fileName(), d->fileNameLength());
648
                    if (m_widget->textDocument()->filePath().toString() == fileName) {
649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671
                        if (unsigned(lineNumber) == d->line()
                            && unsigned(positionInBlock) >= d->column()) { // TODO: check the end
                            result = r; // take the symbol under cursor.
                            break;
                        }
                    }
                } else if (d->isUsingDeclaration()) {
                    int tokenBeginLineNumber = 0, tokenBeginColumnNumber = 0;
                    m_widget->convertPosition(beginOfToken, &tokenBeginLineNumber,
                                              &tokenBeginColumnNumber);
                    if (unsigned(tokenBeginLineNumber) > d->line()
                            || (unsigned(tokenBeginLineNumber) == d->line()
                                && unsigned(tokenBeginColumnNumber) > d->column())) {
                        result = r; // take the symbol under cursor.
                        break;
                    }
                }
            }
        }

        if (Symbol *symbol = result.declaration()) {
            Symbol *def = 0;

672 673 674 675 676 677 678 679 680 681 682 683 684 685 686
            if (resolveTarget) {
                // Consider to show a pop-up displaying overrides for the function
                Function *function = symbol->type()->asFunctionType();
                VirtualFunctionHelper helper(*typeOfExpression, scope, doc, snapshot, symbolFinder);

                if (helper.canLookupVirtualFunctionOverrides(function)) {
                    VirtualFunctionAssistProvider::Parameters params;
                    params.function = function;
                    params.staticClass = helper.staticClassOfFunctionCallExpression();
                    params.typeOfExpression = typeOfExpression;
                    params.snapshot = snapshot;
                    params.cursorPosition = cursor.position();
                    params.openInNextSplit = inNextSplit;

                    if (m_virtualFunctionAssistProvider->configure(params)) {
687
                        m_widget->invokeAssist(FollowSymbol, m_virtualFunctionAssistProvider);
688 689
                        m_virtualFunctionAssistProvider->clearParams();
                    }
690

691 692 693 694 695 696
                    // Ensure a valid link text, so the symbol name will be underlined on Ctrl+Hover.
                    Link link;
                    link.linkTextStart = beginOfToken;
                    link.linkTextEnd = endOfToken;
                    return link;
                }
697

698 699
                Symbol *lastVisibleSymbol = doc->lastVisibleSymbolAt(line, column);

700
                def = findDefinition(symbol, snapshot, symbolFinder);
701 702 703 704

                if (def == lastVisibleSymbol)
                    def = 0; // jump to declaration then.

705
                if (symbol->isForwardClassDeclaration()) {
706
                    def = symbolFinder->findMatchingClassDeclaration(symbol, snapshot);
707 708 709 710 711 712 713
                } else if (Template *templ = symbol->asTemplate()) {
                    if (Symbol *declaration = templ->declaration()) {
                        if (declaration->isForwardClassDeclaration())
                            def = symbolFinder->findMatchingClassDeclaration(declaration, snapshot);
                    }
                }

714 715
            }

716
            link = CppTools::linkToSymbol(def ? def : symbol);
717 718 719 720 721 722 723
            link.linkTextStart = beginOfToken;
            link.linkTextEnd = endOfToken;
            return link;
        }
    }

    // Handle macro uses
724
    QTextCursor macroCursor = cursor;
725
    const QByteArray name = CppTools::identifierUnderCursor(&macroCursor).toUtf8();
726
    link = findMacroLink(name, documentFromSemanticInfo);
727 728 729 730 731 732 733 734 735
    if (link.hasValidTarget()) {
        link.linkTextStart = macroCursor.selectionStart();
        link.linkTextEnd = macroCursor.selectionEnd();
        return link;
    }

    return Link();
}

736
VirtualFunctionAssistProvider *FollowSymbolUnderCursor::virtualFunctionAssistProvider()
737
{
738
    return m_virtualFunctionAssistProvider;
739 740
}

741
void FollowSymbolUnderCursor::setVirtualFunctionAssistProvider(VirtualFunctionAssistProvider *provider)
742
{
743
    m_virtualFunctionAssistProvider = provider;
744
}