cppuseselectionsupdater.cpp 15.6 KB
Newer Older
1 2
/****************************************************************************
**
3 4
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
5 6 7 8 9 10 11
**
** 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
12 13 14
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
15
**
16 17 18 19 20 21 22
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3 as published by the Free Software
** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-3.0.html.
23 24 25 26 27 28 29 30 31
**
****************************************************************************/

#include "cppuseselectionsupdater.h"

#include "cppcanonicalsymbol.h"
#include "cppeditor.h"

#include <cpptools/cpplocalsymbols.h>
32
#include <cpptools/cppmodelmanager.h>
33
#include <cpptools/cpptoolsreuse.h>
34
#include <texteditor/texteditor.h>
35
#include <texteditor/textdocument.h>
36
#include <texteditor/convenience.h>
37 38 39 40 41 42
#include <texteditor/fontsettings.h>

#include <cplusplus/Macro.h>
#include <cplusplus/TranslationUnit.h>

#include <utils/qtcassert.h>
43
#include <utils/runextensions.h>
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

#include <QTextBlock>
#include <QTextCursor>
#include <QTextEdit>

using namespace CPlusPlus;

enum { updateUseSelectionsInternalInMs = 500 };

namespace {

class FunctionDefinitionUnderCursor: protected ASTVisitor
{
    unsigned _line;
    unsigned _column;
    DeclarationAST *_functionDefinition;

public:
    FunctionDefinitionUnderCursor(TranslationUnit *translationUnit)
        : ASTVisitor(translationUnit),
          _line(0), _column(0)
    { }

    DeclarationAST *operator()(AST *ast, unsigned line, unsigned column)
    {
        _functionDefinition = 0;
        _line = line;
        _column = column;
        accept(ast);
        return _functionDefinition;
    }

protected:
    virtual bool preVisit(AST *ast)
    {
        if (_functionDefinition)
            return false;

        if (FunctionDefinitionAST *def = ast->asFunctionDefinition())
            return checkDeclaration(def);

        if (ObjCMethodDeclarationAST *method = ast->asObjCMethodDeclaration()) {
            if (method->function_body)
                return checkDeclaration(method);
        }

        return true;
    }

private:
    bool checkDeclaration(DeclarationAST *ast)
    {
        unsigned startLine, startColumn;
        unsigned endLine, endColumn;
        getTokenStartPosition(ast->firstToken(), &startLine, &startColumn);
        getTokenEndPosition(ast->lastToken() - 1, &endLine, &endColumn);

        if (_line > startLine || (_line == startLine && _column >= startColumn)) {
            if (_line < endLine || (_line == endLine && _column < endColumn)) {
                _functionDefinition = ast;
                return false;
            }
        }

        return true;
    }
};

QTextEdit::ExtraSelection extraSelection(const QTextCharFormat &format, const QTextCursor &cursor)
{
    QTextEdit::ExtraSelection selection;
    selection.format = format;
    selection.cursor = cursor;
    return selection;
}

120
class Params
121
{
122 123 124 125 126 127 128 129 130 131 132
public:
    Params(const QTextCursor &textCursor, const Document::Ptr document, const Snapshot &snapshot)
        : document(document), snapshot(snapshot)
    {
        TextEditor::Convenience::convertPosition(textCursor.document(), textCursor.position(),
                                                 &line, &column);
        CppEditor::Internal::CanonicalSymbol canonicalSymbol(document, snapshot);
        scope = canonicalSymbol.getScopeAndExpression(textCursor, &expression);
    }

public:
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
    // Shared
    Document::Ptr document;

    // For local use calculation
    int line;
    int column;

    // For references calculation
    Scope *scope;
    QString expression;
    Snapshot snapshot;
};

using CppEditor::Internal::SemanticUses;

void splitLocalUses(const CppTools::SemanticInfo::LocalUseMap &uses,
                    const Params &p,
                    SemanticUses *selectionsForLocalVariableUnderCursor,
                    SemanticUses *selectionsForLocalUnusedVariables)
{
    QTC_ASSERT(selectionsForLocalVariableUnderCursor, return);
    QTC_ASSERT(selectionsForLocalUnusedVariables, return);

    LookupContext context(p.document, p.snapshot);

    CppTools::SemanticInfo::LocalUseIterator it(uses);
    while (it.hasNext()) {
        it.next();
        const SemanticUses &uses = it.value();

        bool good = false;
        foreach (const CppTools::SemanticInfo::Use &use, uses) {
            unsigned l = p.line;
            unsigned c = p.column + 1; // convertCursorPosition() returns a 0-based column number.
            if (l == use.line && c >= use.column && c <= (use.column + use.length)) {
                good = true;
                break;
            }
        }

        if (uses.size() == 1) {
            if (!CppTools::isOwnershipRAIIType(it.key(), context))
                selectionsForLocalUnusedVariables->append(uses); // unused declaration
        } else if (good && selectionsForLocalVariableUnderCursor->isEmpty()) {
            selectionsForLocalVariableUnderCursor->append(uses);
        }
    }
}

CppTools::SemanticInfo::LocalUseMap findLocalUses(const Params &p)
{
    AST *ast = p.document->translationUnit()->ast();
    FunctionDefinitionUnderCursor functionDefinitionUnderCursor(p.document->translationUnit());
    DeclarationAST *declaration = functionDefinitionUnderCursor(ast, p.line, p.column);
    return CppTools::LocalSymbols(p.document, declaration).uses;
}

QList<int> findReferences(const Params &p)
{
    QList<int> result;
    if (!p.scope || p.expression.isEmpty())
        return result;

    TypeOfExpression typeOfExpression;
    Snapshot snapshot = p.snapshot;
    snapshot.insert(p.document);
    typeOfExpression.init(p.document, snapshot);
    typeOfExpression.setExpandTemplates(true);

    using CppEditor::Internal::CanonicalSymbol;
    if (Symbol *s = CanonicalSymbol::canonicalSymbol(p.scope, p.expression, typeOfExpression)) {
204
        CppTools::CppModelManager *mmi = CppTools::CppModelManager::instance();
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
        result = mmi->references(s, typeOfExpression.context());
    }

    return result;
}

CppEditor::Internal::UseSelectionsResult findUses(const Params p)
{
    CppEditor::Internal::UseSelectionsResult result;

    const CppTools::SemanticInfo::LocalUseMap localUses = findLocalUses(p);
    result.localUses = localUses;
    splitLocalUses(localUses, p, &result.selectionsForLocalVariableUnderCursor,
                                 &result.selectionsForLocalUnusedVariables);

    if (!result.selectionsForLocalVariableUnderCursor.isEmpty())
        return result;

    result.references = findReferences(p);
    return result; // OK, result.selectionsForLocalUnusedVariables will be passed on
}

} // anonymous namespace

namespace CppEditor {
namespace Internal {

232
CppUseSelectionsUpdater::CppUseSelectionsUpdater(TextEditor::TextEditorWidget *editorWidget)
233 234 235 236 237
    : m_editorWidget(editorWidget)
    , m_findUsesRevision(-1)
{
    m_timer.setSingleShot(true);
    m_timer.setInterval(updateUseSelectionsInternalInMs);
238
    connect(&m_timer, &QTimer::timeout, this, [this]() { update(); });
239 240 241 242 243 244 245 246 247 248 249 250
}

void CppUseSelectionsUpdater::scheduleUpdate()
{
    m_timer.start();
}

void CppUseSelectionsUpdater::abortSchedule()
{
    m_timer.stop();
}

251
void CppUseSelectionsUpdater::update(CallType callType)
252 253 254
{
    CppEditorWidget *cppEditorWidget = qobject_cast<CppEditorWidget *>(m_editorWidget);
    QTC_ASSERT(cppEditorWidget, return);
255 256 257
    if (!cppEditorWidget->isSemanticInfoValidExceptLocalUses())
        return;

258 259 260 261
    const CppTools::SemanticInfo semanticInfo = cppEditorWidget->semanticInfo();
    const Document::Ptr document = semanticInfo.doc;
    const Snapshot snapshot = semanticInfo.snapshot;

262 263 264 265
    if (!document)
        return;

    if (semanticInfo.revision != static_cast<unsigned>(textDocument()->revision()))
266 267 268 269 270 271
        return;

    QTC_ASSERT(document->translationUnit(), return);
    QTC_ASSERT(document->translationUnit()->ast(), return);
    QTC_ASSERT(!snapshot.isEmpty(), return);

272
    if (handleMacroCase(document)) {
273 274 275 276
        emit finished(CppTools::SemanticInfo::LocalUseMap());
        return;
    }

277 278 279 280
    if (callType == Asynchronous)
        handleSymbolCaseAsynchronously(document, snapshot);
    else
        handleSymbolCaseSynchronously(document, snapshot);
281 282 283 284 285 286 287 288 289 290 291 292 293
}

void CppUseSelectionsUpdater::onFindUsesFinished()
{
    QTC_ASSERT(m_findUsesWatcher, return);
    if (m_findUsesWatcher->isCanceled())
        return;
    if (m_findUsesRevision != textDocument()->revision())
        return;
    // Optimizable: If the cursor is still on the same identifier the results are valid.
    if (m_findUsesCursorPosition != m_editorWidget->position())
        return;

294
    processSymbolCaseResults(m_findUsesWatcher->result());
295 296 297 298 299

    m_findUsesWatcher.reset();
    m_document.reset();
}

300
bool CppUseSelectionsUpdater::handleMacroCase(const Document::Ptr document)
301
{
302
    const Macro *macro = CppTools::findCanonicalMacro(m_editorWidget->textCursor(), document);
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
    if (!macro)
        return false;

    const QTextCharFormat &occurrencesFormat = textCharFormat(TextEditor::C_OCCURRENCES);
    ExtraSelections selections;

    // Macro definition
    if (macro->fileName() == document->fileName()) {
        QTextCursor cursor(textDocument());
        cursor.setPosition(macro->utf16CharOffset());
        cursor.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor,
                            macro->nameToQString().size());

        selections.append(extraSelection(occurrencesFormat, cursor));
    }

    // Other macro uses
    foreach (const Document::MacroUse &use, document->macroUses()) {
        const Macro &useMacro = use.macro();
        if (useMacro.line() != macro->line()
                || useMacro.utf16CharOffset() != macro->utf16CharOffset()
                || useMacro.length() != macro->length()
                || useMacro.fileName() != macro->fileName())
            continue;

        QTextCursor cursor(textDocument());
        cursor.setPosition(use.utf16charsBegin());
        cursor.setPosition(use.utf16charsEnd(), QTextCursor::KeepAnchor);

        selections.append(extraSelection(occurrencesFormat, cursor));
    }

    updateUseSelections(selections);
    return true;
}

339 340
void CppUseSelectionsUpdater::handleSymbolCaseAsynchronously(const Document::Ptr document,
                                                             const Snapshot &snapshot)
341 342 343 344 345 346
{
    m_document = document;

    if (m_findUsesWatcher)
        m_findUsesWatcher->cancel();
    m_findUsesWatcher.reset(new QFutureWatcher<UseSelectionsResult>);
347
    connect(m_findUsesWatcher.data(), &QFutureWatcherBase::finished, this, &CppUseSelectionsUpdater::onFindUsesFinished);
348 349 350 351

    m_findUsesRevision = textDocument()->revision();
    m_findUsesCursorPosition = m_editorWidget->position();

352
    const Params params = Params(m_editorWidget->textCursor(), document, snapshot);
353
    m_findUsesWatcher->setFuture(Utils::runAsync(findUses, params));
354 355
}

356 357 358
void CppUseSelectionsUpdater::handleSymbolCaseSynchronously(const Document::Ptr document,
                                                            const Snapshot &snapshot)
{
359
    const Document::Ptr previousDocument = m_document;
360 361
    m_document = document;

362 363 364
    const Params params = Params(m_editorWidget->textCursor(), document, snapshot);
    const UseSelectionsResult result = findUses(params);
    processSymbolCaseResults(result);
365 366

    m_document = previousDocument;
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
}

void CppUseSelectionsUpdater::processSymbolCaseResults(const UseSelectionsResult &result)
{
    const bool hasUsesForLocalVariable = !result.selectionsForLocalVariableUnderCursor.isEmpty();
    const bool hasReferences = !result.references.isEmpty();

    ExtraSelections localVariableSelections;
    if (hasUsesForLocalVariable) {
        localVariableSelections = toExtraSelections(result.selectionsForLocalVariableUnderCursor,
                                                    TextEditor::C_OCCURRENCES);
        updateUseSelections(localVariableSelections);
    } else if (hasReferences) {
        const ExtraSelections selections = toExtraSelections(result.references,
                                                             TextEditor::C_OCCURRENCES);
        updateUseSelections(selections);
    } else {
        if (!currentUseSelections().isEmpty())
            updateUseSelections(ExtraSelections());
    }

    updateUnusedSelections(toExtraSelections(result.selectionsForLocalUnusedVariables,
                                             TextEditor::C_OCCURRENCES_UNUSED));

    emit selectionsForVariableUnderCursorUpdated(localVariableSelections);
    emit finished(result.localUses);
}

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
ExtraSelections CppUseSelectionsUpdater::toExtraSelections(const SemanticUses &uses,
                                                           TextEditor::TextStyle style) const
{
    ExtraSelections result;

    foreach (const CppTools::SemanticInfo::Use &use, uses) {
        if (use.isInvalid())
            continue;

        QTextDocument *document = textDocument();
        const int position = document->findBlockByNumber(use.line - 1).position() + use.column - 1;
        const int anchor = position + use.length;

        QTextEdit::ExtraSelection sel;
        sel.format = textCharFormat(style);
        sel.cursor = QTextCursor(document);
        sel.cursor.setPosition(anchor);
        sel.cursor.setPosition(position, QTextCursor::KeepAnchor);

        result.append(sel);
    }

    return result;
}

ExtraSelections CppUseSelectionsUpdater::toExtraSelections(const QList<int> &references,
                                                           TextEditor::TextStyle style) const
{
    ExtraSelections selections;
424 425 426

    QTC_ASSERT(m_document, return selections);

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
    foreach (int index, references) {
        unsigned line, column;
        TranslationUnit *unit = m_document->translationUnit();
        unit->getTokenPosition(index, &line, &column);

        if (column)
            --column;  // adjust the column position.

        const int len = unit->tokenAt(index).utf16chars();

        QTextCursor cursor(textDocument()->findBlockByNumber(line - 1));
        cursor.setPosition(cursor.position() + column);
        cursor.setPosition(cursor.position() + len, QTextCursor::KeepAnchor);

        selections.append(extraSelection(textCharFormat(style), cursor));
    }

    return selections;
}

QTextCharFormat CppUseSelectionsUpdater::textCharFormat(TextEditor::TextStyle category) const
{
    return m_editorWidget->textDocument()->fontSettings().toTextCharFormat(category);
}

QTextDocument *CppUseSelectionsUpdater::textDocument() const
{
    return m_editorWidget->document();
}

ExtraSelections CppUseSelectionsUpdater::currentUseSelections() const
{
    return m_editorWidget->extraSelections(
460
        TextEditor::TextEditorWidget::CodeSemanticsSelection);
461 462 463 464
}

void CppUseSelectionsUpdater::updateUseSelections(const ExtraSelections &selections)
{
465
    m_editorWidget->setExtraSelections(TextEditor::TextEditorWidget::CodeSemanticsSelection,
466 467 468 469 470
                                       selections);
}

void CppUseSelectionsUpdater::updateUnusedSelections(const ExtraSelections &selections)
{
471
    m_editorWidget->setExtraSelections(TextEditor::TextEditorWidget::UnusedSymbolSelection,
472 473 474 475 476
                                       selections);
}

} // namespace Internal
} // namespace CppEditor