summaryrefslogtreecommitdiff
path: root/src/plugins/cppeditor/builtincursorinfo.cpp
blob: a0190a3b13c22c258f2cbe38798755115fca20b6 (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
// Copyright (C) 2017 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0+ OR GPL-3.0 WITH Qt-GPL-exception-1.0

#include "builtincursorinfo.h"

#include "cppcanonicalsymbol.h"
#include "cppcursorinfo.h"
#include "cpplocalsymbols.h"
#include "cppmodelmanager.h"
#include "cppsemanticinfo.h"
#include "cpptoolsreuse.h"

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

#include <utils/textutils.h>
#include <utils/qtcassert.h>
#include <utils/runextensions.h>

#include <QTextBlock>

using namespace CPlusPlus;

namespace CppEditor {
using SemanticUses = QList<SemanticInfo::Use>;
namespace {

CursorInfo::Range toRange(const SemanticInfo::Use &use)
{
    return {use.line, use.column, use.length};
}

CursorInfo::Range toRange(int tokenIndex, TranslationUnit *translationUnit)
{
    int line, column;
    translationUnit->getTokenPosition(tokenIndex, &line, &column);
    if (column)
        --column;  // adjust the column position.

    return {line,
            column + 1,
            translationUnit->tokenAt(tokenIndex).utf16chars()};
}

CursorInfo::Range toRange(const QTextCursor &textCursor, int utf16offset, int length)
{
    QTextCursor cursor(textCursor.document());
    cursor.setPosition(utf16offset);
    const QTextBlock textBlock = cursor.block();

    return {textBlock.blockNumber() + 1,
            cursor.position() - textBlock.position() + 1,
            length};
}

CursorInfo::Ranges toRanges(const SemanticUses &uses)
{
    CursorInfo::Ranges ranges;
    ranges.reserve(uses.size());

    for (const SemanticInfo::Use &use : uses)
        ranges.append(toRange(use));

    return ranges;
}

CursorInfo::Ranges toRanges(const QList<int> &tokenIndices, TranslationUnit *translationUnit)
{
    CursorInfo::Ranges ranges;
    ranges.reserve(tokenIndices.size());

    for (int reference : tokenIndices)
        ranges.append(toRange(reference, translationUnit));

    return ranges;
}

class FunctionDefinitionUnderCursor: protected ASTVisitor
{
    int m_line = 0;
    int m_column = 0;
    DeclarationAST *m_functionDefinition = nullptr;

public:
    explicit FunctionDefinitionUnderCursor(TranslationUnit *translationUnit)
        : ASTVisitor(translationUnit)
    { }

    DeclarationAST *operator()(AST *ast, int line, int column)
    {
        m_functionDefinition = nullptr;
        m_line = line;
        m_column = column;
        accept(ast);
        return m_functionDefinition;
    }

protected:
    bool preVisit(AST *ast) override
    {
        if (m_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)
    {
        int startLine, startColumn;
        int endLine, endColumn;
        getTokenStartPosition(ast->firstToken(), &startLine, &startColumn);
        getTokenEndPosition(ast->lastToken() - 1, &endLine, &endColumn);

        if (m_line > startLine || (m_line == startLine && m_column >= startColumn)) {
            if (m_line < endLine || (m_line == endLine && m_column < endColumn)) {
                m_functionDefinition = ast;
                return false;
            }
        }

        return true;
    }
};

class FindUses
{
public:
    static CursorInfo find(const Document::Ptr document, const Snapshot &snapshot,
                           int line, int column, Scope *scope, const QString &expression)
    {
        FindUses findUses(document, snapshot, line, column, scope, expression);
        return findUses.doFind();
    }

private:
    FindUses(const Document::Ptr document, const Snapshot &snapshot, int line, int column,
             Scope *scope, const QString &expression)
        : m_document(document)
        , m_line(line)
        , m_column(column)
        , m_scope(scope)
        , m_expression(expression)
        , m_snapshot(snapshot)
    {
    }

    CursorInfo doFind() const
    {
        CursorInfo result;

        // findLocalUses operates with 1-based line and 0-based column
        const SemanticInfo::LocalUseMap localUses
                = BuiltinCursorInfo::findLocalUses(m_document, m_line, m_column - 1);
        result.localUses = localUses;
        splitLocalUses(localUses, &result.useRanges, &result.unusedVariablesRanges);

        if (!result.useRanges.isEmpty()) {
            result.areUseRangesForLocalVariable = true;
            return result;
        }

        result.useRanges = findReferences();
        result.areUseRangesForLocalVariable = false;
        return result; // OK, result.unusedVariablesRanges will be passed on
    }

    void splitLocalUses(const SemanticInfo::LocalUseMap &uses,
                        CursorInfo::Ranges *rangesForLocalVariableUnderCursor,
                        CursorInfo::Ranges *rangesForLocalUnusedVariables) const
    {
        QTC_ASSERT(rangesForLocalVariableUnderCursor, return);
        QTC_ASSERT(rangesForLocalUnusedVariables, return);

        LookupContext context(m_document, m_snapshot);

        for (auto it = uses.cbegin(), end = uses.cend(); it != end; ++it) {
            const SemanticUses &uses = it.value();

            bool good = false;
            for (const SemanticInfo::Use &use : uses) {
                if (m_line == use.line && m_column >= use.column
                        && m_column <= static_cast<int>(use.column + use.length)) {
                    good = true;
                    break;
                }
            }

            if (uses.size() == 1) {
                if (!isOwnershipRAIIType(it.key(), context))
                    rangesForLocalUnusedVariables->append(toRanges(uses)); // unused declaration
            } else if (good && rangesForLocalVariableUnderCursor->isEmpty()) {
                rangesForLocalVariableUnderCursor->append(toRanges(uses));
            }
        }
    }

    CursorInfo::Ranges findReferences() const
    {
        CursorInfo::Ranges result;
        if (!m_scope || m_expression.isEmpty())
            return result;

        TypeOfExpression typeOfExpression;
        Snapshot theSnapshot = m_snapshot;
        theSnapshot.insert(m_document);
        typeOfExpression.init(m_document, theSnapshot);
        typeOfExpression.setExpandTemplates(true);

        if (Symbol *s = Internal::CanonicalSymbol::canonicalSymbol(
                    m_scope, m_expression, typeOfExpression)) {
            const QList<int> tokenIndices = CppModelManager::instance()
                    ->references(s, typeOfExpression.context());
            result = toRanges(tokenIndices, m_document->translationUnit());
        }

        return result;
    }

private:
    // Shared
    Document::Ptr m_document;

    // For local use calculation
    int m_line;
    int m_column;

    // For references calculation
    Scope *m_scope;
    QString m_expression;
    Snapshot m_snapshot;
};

bool isSemanticInfoValidExceptLocalUses(const SemanticInfo &semanticInfo, int revision)
{
    return semanticInfo.doc
        && semanticInfo.revision == static_cast<unsigned>(revision)
        && !semanticInfo.snapshot.isEmpty();
}

bool isMacroUseOf(const Document::MacroUse &marcoUse, const Macro &macro)
{
    const Macro &candidate = marcoUse.macro();

    return candidate.line() == macro.line()
        && candidate.utf16CharOffset() == macro.utf16CharOffset()
        && candidate.length() == macro.length()
        && candidate.fileName() == macro.fileName();
}

bool handleMacroCase(const Document::Ptr document,
                     const QTextCursor &textCursor,
                     CursorInfo::Ranges *ranges)
{
    QTC_ASSERT(ranges, return false);

    const Macro *macro = findCanonicalMacro(textCursor, document);
    if (!macro)
        return false;

    const int length = macro->nameToQString().size();

    // Macro definition
    if (macro->fileName() == document->fileName())
        ranges->append(toRange(textCursor, macro->utf16CharOffset(), length));

    // Other macro uses
    for (const Document::MacroUse &use : document->macroUses()) {
        if (isMacroUseOf(use, *macro))
            ranges->append(toRange(textCursor, use.utf16charsBegin(), length));
    }

    return true;
}

} // anonymous namespace

QFuture<CursorInfo> BuiltinCursorInfo::run(const CursorInfoParams &cursorInfoParams)
{
    QFuture<CursorInfo> nothing;

    const SemanticInfo semanticInfo = cursorInfoParams.semanticInfo;
    const int currentDocumentRevision = cursorInfoParams.textCursor.document()->revision();
    if (!isSemanticInfoValidExceptLocalUses(semanticInfo, currentDocumentRevision))
        return nothing;

    const Document::Ptr document = semanticInfo.doc;
    const Snapshot snapshot = semanticInfo.snapshot;
    if (!document)
        return nothing;

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

    CursorInfo::Ranges ranges;
    if (handleMacroCase(document, cursorInfoParams.textCursor, &ranges)) {
        CursorInfo result;
        result.useRanges = ranges;
        result.areUseRangesForLocalVariable = false;

        QFutureInterface<CursorInfo> fi;
        fi.reportResult(result);
        fi.reportFinished();

        return fi.future();
    }

    const QTextCursor &textCursor = cursorInfoParams.textCursor;
    int line, column;
    Utils::Text::convertPosition(textCursor.document(), textCursor.position(), &line, &column);
    Internal::CanonicalSymbol canonicalSymbol(document, snapshot);
    QString expression;
    Scope *scope = canonicalSymbol.getScopeAndExpression(textCursor, &expression);

    return Utils::runAsync(&FindUses::find, document, snapshot, line, column, scope, expression);
}

SemanticInfo::LocalUseMap
BuiltinCursorInfo::findLocalUses(const Document::Ptr &document, int line, int column)
{
    if (!document || !document->translationUnit() || !document->translationUnit()->ast())
        return SemanticInfo::LocalUseMap();

    AST *ast = document->translationUnit()->ast();
    FunctionDefinitionUnderCursor functionDefinitionUnderCursor(document->translationUnit());
    DeclarationAST *declaration = functionDefinitionUnderCursor(ast, line, column);
    return Internal::LocalSymbols(document, declaration).uses;
}

} // namespace CppEditor