aboutsummaryrefslogtreecommitdiffstats
path: root/src/plugins/cpptools/cppcompletionassistprocessor.cpp
blob: cf945301ce0d57e6d4f2dd97b9d289a066a03d69 (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
/****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** 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 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.
**
** 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.
**
****************************************************************************/

#include "cppcompletionassistprocessor.h"

#include <cppeditor/cppeditorconstants.h>

#include <cplusplus/BackwardsScanner.h>
#include <cplusplus/ExpressionUnderCursor.h>
#include <cplusplus/SimpleLexer.h>
#include <cplusplus/Token.h>

#include <QTextBlock>
#include <QTextCursor>
#include <QTextDocument>

using namespace CPlusPlus;

namespace CppTools {

CppCompletionAssistProcessor::CppCompletionAssistProcessor(int snippetItemOrder)
    : m_preprocessorCompletions(
          QStringList({"define", "error", "include", "line", "pragma", "pragma once",
                       "pragma omp atomic", "pragma omp parallel", "pragma omp for",
                       "pragma omp ordered", "pragma omp parallel for", "pragma omp section",
                       "pragma omp sections", "pragma omp parallel sections", "pragma omp single",
                       "pragma omp master", "pragma omp critical", "pragma omp barrier",
                       "pragma omp flush", "pragma omp threadprivate", "undef", "if", "ifdef",
                       "ifndef", "elif", "else", "endif"}))
    , m_snippetCollector(QLatin1String(CppEditor::Constants::CPP_SNIPPETS_GROUP_ID),
                         QIcon(QLatin1String(":/texteditor/images/snippet.png")),
                         snippetItemOrder)
{
}

void CppCompletionAssistProcessor::addSnippets()
{
    m_completions.append(m_snippetCollector.collect());
}

static bool isDoxygenTagCompletionCharacter(const QChar &character)
{
    return character == QLatin1Char('\\')
        || character == QLatin1Char('@') ;
}

static bool twoIndentifiersBeforeLBrace(const Tokens &tokens, int tokenIdx)
{
    const Token &previousToken = tokens.at(tokenIdx - 1);
    if (previousToken.kind() != T_IDENTIFIER)
        return false;
    for (int index = tokenIdx - 2; index >= 0; index -= 2) {
        const Token &token = tokens.at(index);
        if (token.kind() == T_IDENTIFIER)
            return true;

        if (token.kind() != T_COLON_COLON)
            return false;
    }
    return false;
}

void CppCompletionAssistProcessor::startOfOperator(QTextDocument *textDocument,
        int positionInDocument,
        unsigned *kind,
        int &start,
        const CPlusPlus::LanguageFeatures &languageFeatures,
        bool adjustForQt5SignalSlotCompletion,
        DotAtIncludeCompletionHandler dotAtIncludeCompletionHandler)
{
    if (start != positionInDocument) {
        QTextCursor tc(textDocument);
        tc.setPosition(positionInDocument);

        // Include completion: make sure the quote character is the first one on the line
        if (*kind == T_STRING_LITERAL) {
            QTextCursor s = tc;
            s.movePosition(QTextCursor::StartOfLine, QTextCursor::KeepAnchor);
            QString sel = s.selectedText();
            if (sel.indexOf(QLatin1Char('"')) < sel.length() - 1) {
                *kind = T_EOF_SYMBOL;
                start = positionInDocument;
            }
        }

        if (*kind == T_COMMA) {
            ExpressionUnderCursor expressionUnderCursor(languageFeatures);
            if (expressionUnderCursor.startOfFunctionCall(tc) == -1) {
                *kind = T_EOF_SYMBOL;
                start = positionInDocument;
            }
        }

        SimpleLexer tokenize;
        tokenize.setLanguageFeatures(languageFeatures);
        tokenize.setSkipComments(false);
        const Tokens &tokens = tokenize(tc.block().text(), BackwardsScanner::previousBlockState(tc.block()));
        const int tokenIdx = SimpleLexer::tokenBefore(tokens, qMax(0, tc.positionInBlock() - 1)); // get the token at the left of the cursor
        const Token tk = (tokenIdx == -1) ? Token() : tokens.at(tokenIdx);
        const QChar characterBeforePositionInDocument
                = textDocument->characterAt(positionInDocument - 1);

        if (adjustForQt5SignalSlotCompletion && *kind == T_AMPER && tokenIdx > 0) {
            const Token &previousToken = tokens.at(tokenIdx - 1);
            if (previousToken.kind() == T_COMMA)
                start = positionInDocument - (tk.utf16charOffset - previousToken.utf16charOffset) - 1;
        } else if (*kind == T_DOXY_COMMENT && !(tk.is(T_DOXY_COMMENT) || tk.is(T_CPP_DOXY_COMMENT))) {
            *kind = T_EOF_SYMBOL;
            start = positionInDocument;
        // Do not complete in comments, except in doxygen comments for doxygen commands.
        // Do not complete in strings, except it is for include completion.
        } else if (tk.is(T_COMMENT) || tk.is(T_CPP_COMMENT)
                 || ((tk.is(T_CPP_DOXY_COMMENT) || tk.is(T_DOXY_COMMENT))
                        && !isDoxygenTagCompletionCharacter(characterBeforePositionInDocument))
                 || (tk.isLiteral() && (*kind != T_STRING_LITERAL
                                     && *kind != T_ANGLE_STRING_LITERAL
                                     && *kind != T_SLASH
                                     && *kind != T_DOT))) {
            *kind = T_EOF_SYMBOL;
            start = positionInDocument;
        // Include completion: can be triggered by slash, but only in a string
        } else if (*kind == T_SLASH && (tk.isNot(T_STRING_LITERAL) && tk.isNot(T_ANGLE_STRING_LITERAL))) {
            *kind = T_EOF_SYMBOL;
            start = positionInDocument;
        } else if (*kind == T_LPAREN) {
            if (tokenIdx > 0) {
                const Token &previousToken = tokens.at(tokenIdx - 1); // look at the token at the left of T_LPAREN
                switch (previousToken.kind()) {
                case T_IDENTIFIER:
                case T_GREATER:
                case T_SIGNAL:
                case T_SLOT:
                    break; // good

                default:
                    // that's a bad token :)
                    *kind = T_EOF_SYMBOL;
                    start = positionInDocument;
                }
            } else {
                *kind = T_EOF_SYMBOL;
                start = positionInDocument;
            }
        } else if (*kind == T_LBRACE) {
            if (tokenIdx <= 0 || !twoIndentifiersBeforeLBrace(tokens, tokenIdx)) {
                *kind = T_EOF_SYMBOL;
                start = positionInDocument;
            }
        }
        // Check for include preprocessor directive
        else if (*kind == T_STRING_LITERAL || *kind == T_ANGLE_STRING_LITERAL || *kind == T_SLASH
                 || (*kind == T_DOT
                        && (tk.is(T_STRING_LITERAL) || tk.is(T_ANGLE_STRING_LITERAL)))) {
            bool include = false;
            if (tokens.size() >= 3) {
                if (tokens.at(0).is(T_POUND) && tokens.at(1).is(T_IDENTIFIER) && (tokens.at(2).is(T_STRING_LITERAL) ||
                                                                                  tokens.at(2).is(T_ANGLE_STRING_LITERAL))) {
                    const Token &directiveToken = tokens.at(1);
                    QString directive = tc.block().text().mid(directiveToken.utf16charsBegin(),
                                                              directiveToken.utf16chars());
                    if (directive == QLatin1String("include") ||
                            directive == QLatin1String("include_next") ||
                            directive == QLatin1String("import")) {
                        include = true;
                    }
                }
            }

            if (!include) {
                *kind = T_EOF_SYMBOL;
                start = positionInDocument;
            } else if (*kind == T_DOT && dotAtIncludeCompletionHandler){
                dotAtIncludeCompletionHandler(start, kind);
            }
        }
    }
}

} // namespace CppTools