cppcompletionassist.cpp 76.5 KB
Newer Older
hjk's avatar
hjk committed
1
/****************************************************************************
con's avatar
con committed
2
**
3 4
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
con's avatar
con committed
5
**
hjk's avatar
hjk committed
6
** This file is part of Qt Creator.
con's avatar
con committed
7
**
hjk's avatar
hjk committed
8 9 10 11
** 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.
con's avatar
con committed
23
**
hjk's avatar
hjk committed
24
****************************************************************************/
hjk's avatar
hjk committed
25

Leandro Melo's avatar
Leandro Melo committed
26
#include "cppcompletionassist.h"
27

28
#include "builtineditordocumentparser.h"
29
#include "cppdoxygen.h"
Leandro Melo's avatar
Leandro Melo committed
30
#include "cppmodelmanager.h"
31
#include "cpptoolsconstants.h"
32
#include "cpptoolsreuse.h"
33
#include "editordocumenthandle.h"
con's avatar
con committed
34 35

#include <coreplugin/icore.h>
Leandro Melo's avatar
Leandro Melo committed
36
#include <cppeditor/cppeditorconstants.h>
37
#include <texteditor/codeassist/assistproposalitem.h>
Leandro Melo's avatar
Leandro Melo committed
38 39 40 41
#include <texteditor/codeassist/genericproposal.h>
#include <texteditor/codeassist/ifunctionhintproposalmodel.h>
#include <texteditor/codeassist/functionhintproposal.h>
#include <texteditor/convenience.h>
42
#include <texteditor/snippets/snippet.h>
Leandro Melo's avatar
Leandro Melo committed
43 44
#include <texteditor/texteditorsettings.h>
#include <texteditor/completionsettings.h>
45

Eike Ziller's avatar
Eike Ziller committed
46
#include <utils/mimetypes/mimedatabase.h>
47
#include <utils/qtcassert.h>
con's avatar
con committed
48

49 50 51 52 53 54 55
#include <cplusplus/BackwardsScanner.h>
#include <cplusplus/CppRewriter.h>
#include <cplusplus/ExpressionUnderCursor.h>
#include <cplusplus/MatchingText.h>
#include <cplusplus/Overview.h>
#include <cplusplus/ResolveExpression.h>

56
#include <QDirIterator>
57 58 59 60
#include <QLatin1String>
#include <QTextCursor>
#include <QTextDocument>
#include <QIcon>
61

con's avatar
con committed
62
using namespace CPlusPlus;
Leandro Melo's avatar
Leandro Melo committed
63 64
using namespace CppEditor;
using namespace CppTools;
65
using namespace CppTools::Internal;
Leandro Melo's avatar
Leandro Melo committed
66
using namespace TextEditor;
con's avatar
con committed
67

Leandro Melo's avatar
Leandro Melo committed
68 69
namespace CppTools {
namespace Internal {
70

Leandro Melo's avatar
Leandro Melo committed
71 72 73 74 75
struct CompleteFunctionDeclaration
{
    explicit CompleteFunctionDeclaration(Function *f = 0)
        : function(f)
    {}
76

Leandro Melo's avatar
Leandro Melo committed
77 78
    Function *function;
};
79

Leandro Melo's avatar
Leandro Melo committed
80 81 82
// ---------------------
// CppAssistProposalItem
// ---------------------
83
class CppAssistProposalItem final : public AssistProposalItem
84
{
Leandro Melo's avatar
Leandro Melo committed
85
public:
86
    CppAssistProposalItem() :
87
        m_isOverloaded(false) {}
88

89
    ~CppAssistProposalItem() Q_DECL_NOEXCEPT {}
90
    bool prematurelyApplies(const QChar &c) const override;
91
    void applyContextualContent(TextDocumentManipulatorInterface &manipulator, int basePosition) const override;
92

Leandro Melo's avatar
Leandro Melo committed
93 94 95
    bool isOverloaded() const { return m_isOverloaded; }
    void markAsOverloaded() { m_isOverloaded = true; }
    void keepCompletionOperator(unsigned compOp) { m_completionOperator = compOp; }
96 97
    void keepTypeOfExpression(const QSharedPointer<TypeOfExpression> &typeOfExp)
    { m_typeOfExpression = typeOfExp; }
98

99 100 101

    quint64 hash() const override;

Leandro Melo's avatar
Leandro Melo committed
102
private:
103
    QSharedPointer<TypeOfExpression> m_typeOfExpression;
104 105 106
    unsigned m_completionOperator;
    mutable QChar m_typedChar;
    bool m_isOverloaded;
Leandro Melo's avatar
Leandro Melo committed
107
};
108

Leandro Melo's avatar
Leandro Melo committed
109 110
} // Internal
} // CppTools
111

Leandro Melo's avatar
Leandro Melo committed
112
Q_DECLARE_METATYPE(CppTools::Internal::CompleteFunctionDeclaration)
113

114 115 116 117 118 119 120 121
bool CppAssistProposalModel::isSortable(const QString &prefix) const
{
    if (m_completionOperator != T_EOF_SYMBOL)
        return true;

    return !prefix.isEmpty();
}

122
AssistProposalItemInterface *CppAssistProposalModel::proposalItem(int index) const
Leandro Melo's avatar
Leandro Melo committed
123
{
124 125
    AssistProposalItemInterface *item = GenericProposalModel::proposalItem(index);
    if (!item->isSnippet()) {
Leandro Melo's avatar
Leandro Melo committed
126 127
        CppAssistProposalItem *cppItem = static_cast<CppAssistProposalItem *>(item);
        cppItem->keepCompletionOperator(m_completionOperator);
128
        cppItem->keepTypeOfExpression(m_typeOfExpression);
Leandro Melo's avatar
Leandro Melo committed
129 130 131
    }
    return item;
}
132

Leandro Melo's avatar
Leandro Melo committed
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
bool CppAssistProposalItem::prematurelyApplies(const QChar &typedChar) const
{
    if (m_completionOperator == T_SIGNAL || m_completionOperator == T_SLOT) {
        if (typedChar == QLatin1Char('(') || typedChar == QLatin1Char(',')) {
            m_typedChar = typedChar;
            return true;
        }
    } else if (m_completionOperator == T_STRING_LITERAL
               || m_completionOperator == T_ANGLE_STRING_LITERAL) {
        if (typedChar == QLatin1Char('/') && text().endsWith(QLatin1Char('/'))) {
            m_typedChar = typedChar;
            return true;
        }
    } else if (data().value<Symbol *>()) {
        if (typedChar == QLatin1Char(':')
                || typedChar == QLatin1Char(';')
                || typedChar == QLatin1Char('.')
                || typedChar == QLatin1Char(',')
                || typedChar == QLatin1Char('(')) {
            m_typedChar = typedChar;
            return true;
        }
    } else if (data().canConvert<CompleteFunctionDeclaration>()) {
        if (typedChar == QLatin1Char('(')) {
            m_typedChar = typedChar;
            return true;
        }
    }

    return false;
}

165
static bool isDereferenced(TextDocumentManipulatorInterface &manipulator, int basePosition)
166
{
167
    QTextCursor cursor = manipulator.textCursorAt(basePosition);
168 169
    cursor.setPosition(basePosition);

170
    BackwardsScanner scanner(cursor, LanguageFeatures());
171 172 173 174 175 176 177 178 179 180 181 182 183 184
    for (int pos = scanner.startToken()-1; pos >= 0; pos--) {
        switch (scanner[pos].kind()) {
        case T_COLON_COLON:
        case T_IDENTIFIER:
            //Ignore scope specifiers
            break;

        case T_AMPER: return true;
        default:      return false;
        }
    }
    return false;
}

185 186 187 188 189 190 191 192 193 194
quint64 CppAssistProposalItem::hash() const
{
    if (data().canConvert<Symbol *>())
        return quint64(data().value<Symbol *>()->index());
    else if (data().canConvert<CompleteFunctionDeclaration>())
        return quint64(data().value<CompleteFunctionDeclaration>().function->index());

    return 0;
}

195
void CppAssistProposalItem::applyContextualContent(TextDocumentManipulatorInterface &manipulator, int basePosition) const
Leandro Melo's avatar
Leandro Melo committed
196 197 198 199 200 201 202 203 204 205
{
    Symbol *symbol = 0;

    if (data().isValid())
        symbol = data().value<Symbol *>();

    QString toInsert;
    QString extraChars;
    int extraLength = 0;
    int cursorOffset = 0;
206
    bool setAutoCompleteSkipPos = false;
Leandro Melo's avatar
Leandro Melo committed
207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226

    bool autoParenthesesEnabled = true;

    if (m_completionOperator == T_SIGNAL || m_completionOperator == T_SLOT) {
        toInsert = text();
        extraChars += QLatin1Char(')');

        if (m_typedChar == QLatin1Char('(')) // Eat the opening parenthesis
            m_typedChar = QChar();
    } else if (m_completionOperator == T_STRING_LITERAL || m_completionOperator == T_ANGLE_STRING_LITERAL) {
        toInsert = text();
        if (!toInsert.endsWith(QLatin1Char('/'))) {
            extraChars += QLatin1Char((m_completionOperator == T_ANGLE_STRING_LITERAL) ? '>' : '"');
        } else {
            if (m_typedChar == QLatin1Char('/')) // Eat the slash
                m_typedChar = QChar();
        }
    } else {
        toInsert = text();

227
        const CompletionSettings &completionSettings = TextEditorSettings::completionSettings();
Leandro Melo's avatar
Leandro Melo committed
228 229 230 231 232 233
        const bool autoInsertBrackets = completionSettings.m_autoInsertBrackets;

        if (autoInsertBrackets && symbol && symbol->type()) {
            if (Function *function = symbol->type()->asFunctionType()) {
                // If the member is a function, automatically place the opening parenthesis,
                // except when it might take template parameters.
234 235 236
                if (!function->hasReturnType()
                    && (function->unqualifiedName()
                    && !function->unqualifiedName()->isDestructorNameId())) {
Leandro Melo's avatar
Leandro Melo committed
237 238 239 240 241 242
                    // Don't insert any magic, since the user might have just wanted to select the class

                    /// ### port me
#if 0
                } else if (function->templateParameterCount() != 0 && typedChar != QLatin1Char('(')) {
                    // If there are no arguments, then we need the template specification
243
                    if (function->argumentCount() == 0)
Leandro Melo's avatar
Leandro Melo committed
244 245
                        extraChars += QLatin1Char('<');
#endif
246
                } else if (!isDereferenced(manipulator, basePosition) && !function->isAmbiguous()) {
Leandro Melo's avatar
Leandro Melo committed
247 248 249 250 251 252 253 254 255 256 257 258 259
                    // When the user typed the opening parenthesis, he'll likely also type the closing one,
                    // in which case it would be annoying if we put the cursor after the already automatically
                    // inserted closing parenthesis.
                    const bool skipClosingParenthesis = m_typedChar != QLatin1Char('(');

                    if (completionSettings.m_spaceAfterFunctionName)
                        extraChars += QLatin1Char(' ');
                    extraChars += QLatin1Char('(');
                    if (m_typedChar == QLatin1Char('('))
                        m_typedChar = QChar();

                    // If the function doesn't return anything, automatically place the semicolon,
                    // unless we're doing a scope completion (then it might be function definition).
260
                    const QChar characterAtCursor = manipulator.characterAt(manipulator.currentPosition());
Leandro Melo's avatar
Leandro Melo committed
261 262 263 264 265 266 267 268 269 270
                    bool endWithSemicolon = m_typedChar == QLatin1Char(';')
                            || (function->returnType()->isVoidType() && m_completionOperator != T_COLON_COLON);
                    const QChar semicolon = m_typedChar.isNull() ? QLatin1Char(';') : m_typedChar;

                    if (endWithSemicolon && characterAtCursor == semicolon) {
                        endWithSemicolon = false;
                        m_typedChar = QChar();
                    }

                    // If the function takes no arguments, automatically place the closing parenthesis
271
                    if (!isOverloaded() && !function->hasArguments() && skipClosingParenthesis) {
Leandro Melo's avatar
Leandro Melo committed
272 273 274 275 276 277
                        extraChars += QLatin1Char(')');
                        if (endWithSemicolon) {
                            extraChars += semicolon;
                            m_typedChar = QChar();
                        }
                    } else if (autoParenthesesEnabled) {
278
                        const QChar lookAhead = manipulator.characterAt(manipulator.currentPosition() + 1);
Leandro Melo's avatar
Leandro Melo committed
279 280 281
                        if (MatchingText::shouldInsertMatchingText(lookAhead)) {
                            extraChars += QLatin1Char(')');
                            --cursorOffset;
282
                            setAutoCompleteSkipPos = true;
Leandro Melo's avatar
Leandro Melo committed
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
                            if (endWithSemicolon) {
                                extraChars += semicolon;
                                --cursorOffset;
                                m_typedChar = QChar();
                            }
                        }
                        // TODO: When an opening parenthesis exists, the "semicolon" should really be
                        // inserted after the matching closing parenthesis.
                    }
                }
            }
        }

        if (autoInsertBrackets && data().canConvert<CompleteFunctionDeclaration>()) {
            if (m_typedChar == QLatin1Char('('))
                m_typedChar = QChar();

            // everything from the closing parenthesis on are extra chars, to
            // make sure an auto-inserted ")" gets replaced by ") const" if necessary
            int closingParen = toInsert.lastIndexOf(QLatin1Char(')'));
            extraChars = toInsert.mid(closingParen);
            toInsert.truncate(closingParen);
        }
    }

    // Append an unhandled typed character, adjusting cursor offset when it had been adjusted before
    if (!m_typedChar.isNull()) {
        extraChars += m_typedChar;
        if (cursorOffset != 0)
            --cursorOffset;
    }

315 316
    // Determine the length of characters that should just be kept on the editor, but do
    // not consider content that ends as an identifier (which could be undesired).
317 318 319
    const int lineEnd = manipulator.positionAt(EndOfLinePosition);
    const QString inEditor = manipulator.textAt(manipulator.currentPosition(),
                                                lineEnd - manipulator.currentPosition());
320
    int preserveLength = 0;
321
    if (!inEditor.isEmpty()) {
322
        preserveLength = toInsert.length() - (manipulator.currentPosition() - basePosition);
323
        const int inEditorLength = inEditor.length();
324
        while (preserveLength > 0) {
325 326
            if (inEditor.startsWith(toInsert.right(preserveLength))
                    && (inEditorLength == preserveLength
327
                        || !CppTools::isValidIdentifierChar(inEditor.at(preserveLength)))) {
328
                break;
329 330
            }
            --preserveLength;
331 332
        }
    }
333

Leandro Melo's avatar
Leandro Melo committed
334 335
    for (int i = 0; i < extraChars.length(); ++i) {
        const QChar a = extraChars.at(i);
336
        const QChar b = manipulator.characterAt(manipulator.currentPosition() + i + preserveLength);
Leandro Melo's avatar
Leandro Melo committed
337 338 339 340 341 342 343 344 345
        if (a == b)
            ++extraLength;
        else
            break;
    }

    toInsert += extraChars;

    // Insert the remainder of the name
346 347
    const int length = manipulator.currentPosition() - basePosition + preserveLength + extraLength;
    manipulator.replace(basePosition, length, toInsert);
Leandro Melo's avatar
Leandro Melo committed
348
    if (cursorOffset)
349
        manipulator.setCursorPosition(manipulator.currentPosition() + cursorOffset);
350 351
    if (setAutoCompleteSkipPos)
        manipulator.setAutoCompleteSkipPosition(manipulator.currentPosition());
Leandro Melo's avatar
Leandro Melo committed
352 353 354 355 356
}

// --------------------
// CppFunctionHintModel
// --------------------
357
class CppFunctionHintModel : public IFunctionHintProposalModel
Leandro Melo's avatar
Leandro Melo committed
358 359
{
public:
360 361
    CppFunctionHintModel(QList<Function *> functionSymbols,
                         const QSharedPointer<TypeOfExpression> &typeOfExp)
Leandro Melo's avatar
Leandro Melo committed
362 363
        : m_functionSymbols(functionSymbols)
        , m_currentArg(-1)
364
        , m_typeOfExpression(typeOfExp)
Leandro Melo's avatar
Leandro Melo committed
365 366
    {}

367 368 369 370
    void reset() override {}
    int size() const override { return m_functionSymbols.size(); }
    QString text(int index) const override;
    int activeArgument(const QString &prefix) const override;
Leandro Melo's avatar
Leandro Melo committed
371 372 373 374

private:
    QList<Function *> m_functionSymbols;
    mutable int m_currentArg;
375
    QSharedPointer<TypeOfExpression> m_typeOfExpression;
Leandro Melo's avatar
Leandro Melo committed
376 377 378 379 380
};

QString CppFunctionHintModel::text(int index) const
{
    Overview overview;
381 382 383
    overview.showReturnTypes = true;
    overview.showArgumentNames = true;
    overview.markedArgument = m_currentArg + 1;
Leandro Melo's avatar
Leandro Melo committed
384 385
    Function *f = m_functionSymbols.at(index);

386 387 388
    const QString prettyMethod = overview.prettyType(f->type(), f->name());
    const int begin = overview.markedArgumentBegin;
    const int end = overview.markedArgumentEnd;
Leandro Melo's avatar
Leandro Melo committed
389 390

    QString hintText;
391
    hintText += prettyMethod.left(begin).toHtmlEscaped();
392
    hintText += QLatin1String("<b>");
393
    hintText += prettyMethod.mid(begin, end - begin).toHtmlEscaped();
394
    hintText += QLatin1String("</b>");
395
    hintText += prettyMethod.mid(end).toHtmlEscaped();
Leandro Melo's avatar
Leandro Melo committed
396 397 398 399 400 401 402 403
    return hintText;
}

int CppFunctionHintModel::activeArgument(const QString &prefix) const
{
    int argnr = 0;
    int parcount = 0;
    SimpleLexer tokenize;
404
    Tokens tokens = tokenize(prefix);
Leandro Melo's avatar
Leandro Melo committed
405 406 407 408 409 410
    for (int i = 0; i < tokens.count(); ++i) {
        const Token &tk = tokens.at(i);
        if (tk.is(T_LPAREN))
            ++parcount;
        else if (tk.is(T_RPAREN))
            --parcount;
411
        else if (!parcount && tk.is(T_COMMA))
Leandro Melo's avatar
Leandro Melo committed
412 413 414 415 416 417 418 419 420 421 422 423 424
            ++argnr;
    }

    if (parcount < 0)
        return -1;

    if (argnr != m_currentArg)
        m_currentArg = argnr;

    return argnr;
}

// ---------------------------
425
// InternalCompletionAssistProvider
Leandro Melo's avatar
Leandro Melo committed
426 427
// ---------------------------

428
IAssistProcessor *InternalCompletionAssistProvider::createProcessor() const
Leandro Melo's avatar
Leandro Melo committed
429
{
430
    return new InternalCppCompletionAssistProcessor;
Leandro Melo's avatar
Leandro Melo committed
431 432
}

433
AssistInterface *InternalCompletionAssistProvider::createAssistInterface(
434 435 436 437 438
        const QString &filePath,
        const TextEditorWidget *textEditorWidget,
        const LanguageFeatures &languageFeatures,
        int position,
        AssistReason reason) const
Leandro Melo's avatar
Leandro Melo committed
439
{
440
    QTC_ASSERT(textEditorWidget, return 0);
441

442 443
    return new CppCompletionAssistInterface(filePath,
                                            textEditorWidget,
444
                                            BuiltinEditorDocumentParser::get(filePath),
445 446 447
                                            languageFeatures,
                                            position,
                                            reason,
448
                                            CppModelManager::instance()->workingCopy());
Leandro Melo's avatar
Leandro Melo committed
449 450 451 452 453
}

// -----------------
// CppAssistProposal
// -----------------
454
class CppAssistProposal : public GenericProposal
Leandro Melo's avatar
Leandro Melo committed
455 456
{
public:
457
    CppAssistProposal(int cursorPos, GenericProposalModel *model)
458
        : GenericProposal(cursorPos, model)
Leandro Melo's avatar
Leandro Melo committed
459 460 461
        , m_replaceDotForArrow(static_cast<CppAssistProposalModel *>(model)->m_replaceDotForArrow)
    {}

462 463
    bool isCorrective() const override { return m_replaceDotForArrow; }
    void makeCorrection(TextEditorWidget *editorWidget) override;
Leandro Melo's avatar
Leandro Melo committed
464 465 466 467 468

private:
    bool m_replaceDotForArrow;
};

469
void CppAssistProposal::makeCorrection(TextEditorWidget *editorWidget)
Leandro Melo's avatar
Leandro Melo committed
470
{
471 472 473 474
    const int oldPosition = editorWidget->position();
    editorWidget->setCursorPosition(basePosition() - 1);
    editorWidget->replace(1, QLatin1String("->"));
    editorWidget->setCursorPosition(oldPosition + 1);
Leandro Melo's avatar
Leandro Melo committed
475 476 477 478 479 480 481 482
    moveBasePosition(1);
}

namespace {

class ConvertToCompletionItem: protected NameVisitor
{
    // The completion item.
483
    AssistProposalItem *_item;
Leandro Melo's avatar
Leandro Melo committed
484 485 486 487 488 489 490 491 492 493 494

    // The current symbol.
    Symbol *_symbol;

    // The pretty printer.
    Overview overview;

public:
    ConvertToCompletionItem()
        : _item(0)
        , _symbol(0)
495
    {
496 497
        overview.showReturnTypes = true;
        overview.showArgumentNames = true;
498
    }
Leandro Melo's avatar
Leandro Melo committed
499

500
    AssistProposalItem *operator()(Symbol *symbol)
Leandro Melo's avatar
Leandro Melo committed
501
    {
502
        //using declaration can be qualified
503 504
        if (!symbol || !symbol->name() || (symbol->name()->isQualifiedNameId()
                                           && !symbol->asUsingDeclaration()))
Leandro Melo's avatar
Leandro Melo committed
505 506
            return 0;

507
        AssistProposalItem *previousItem = switchCompletionItem(0);
Leandro Melo's avatar
Leandro Melo committed
508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523
        Symbol *previousSymbol = switchSymbol(symbol);
        accept(symbol->unqualifiedName());
        if (_item)
            _item->setData(QVariant::fromValue(symbol));
        (void) switchSymbol(previousSymbol);
        return switchCompletionItem(previousItem);
    }

protected:
    Symbol *switchSymbol(Symbol *symbol)
    {
        Symbol *previousSymbol = _symbol;
        _symbol = symbol;
        return previousSymbol;
    }

524
    AssistProposalItem *switchCompletionItem(AssistProposalItem *item)
Leandro Melo's avatar
Leandro Melo committed
525
    {
526
        AssistProposalItem *previousItem = _item;
Leandro Melo's avatar
Leandro Melo committed
527 528 529 530
        _item = item;
        return previousItem;
    }

531
    AssistProposalItem *newCompletionItem(const Name *name)
Leandro Melo's avatar
Leandro Melo committed
532
    {
533
        AssistProposalItem *item = new CppAssistProposalItem;
Leandro Melo's avatar
Leandro Melo committed
534 535 536 537
        item->setText(overview.prettyName(name));
        return item;
    }

538
    void visit(const Identifier *name)
539 540
    {
        _item = newCompletionItem(name);
541
        if (!_symbol->isScope() || _symbol->isFunction())
542 543
            _item->setDetail(overview.prettyType(_symbol->type(), name));
    }
Leandro Melo's avatar
Leandro Melo committed
544

545
    void visit(const TemplateNameId *name)
Leandro Melo's avatar
Leandro Melo committed
546 547
    {
        _item = newCompletionItem(name);
548
        _item->setText(QString::fromUtf8(name->identifier()->chars(), name->identifier()->size()));
Leandro Melo's avatar
Leandro Melo committed
549 550
    }

551
    void visit(const DestructorNameId *name)
Leandro Melo's avatar
Leandro Melo committed
552 553
    { _item = newCompletionItem(name); }

554
    void visit(const OperatorNameId *name)
555 556 557 558
    {
        _item = newCompletionItem(name);
        _item->setDetail(overview.prettyType(_symbol->type(), name));
    }
Leandro Melo's avatar
Leandro Melo committed
559

560
    void visit(const ConversionNameId *name)
Leandro Melo's avatar
Leandro Melo committed
561 562
    { _item = newCompletionItem(name); }

563
    void visit(const QualifiedNameId *name)
Leandro Melo's avatar
Leandro Melo committed
564 565 566 567 568 569 570
    { _item = newCompletionItem(name->name()); }
};

Class *asClassOrTemplateClassType(FullySpecifiedType ty)
{
    if (Class *classTy = ty->asClassType())
        return classTy;
571
    if (Template *templ = ty->asTemplateType()) {
Leandro Melo's avatar
Leandro Melo committed
572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593
        if (Symbol *decl = templ->declaration())
            return decl->asClass();
    }
    return 0;
}

Scope *enclosingNonTemplateScope(Symbol *symbol)
{
    if (symbol) {
        if (Scope *scope = symbol->enclosingScope()) {
            if (Template *templ = scope->asTemplate())
                return templ->enclosingScope();
            return scope;
        }
    }
    return 0;
}

Function *asFunctionOrTemplateFunctionType(FullySpecifiedType ty)
{
    if (Function *funTy = ty->asFunctionType())
        return funTy;
594
    if (Template *templ = ty->asTemplateType()) {
Leandro Melo's avatar
Leandro Melo committed
595 596 597 598 599 600
        if (Symbol *decl = templ->declaration())
            return decl->asFunction();
    }
    return 0;
}

601 602 603 604 605 606 607 608 609 610
bool isQPrivateSignal(const Symbol *symbol)
{
    if (!symbol)
        return false;

    static Identifier qPrivateSignalIdentifier("QPrivateSignal", 14);

    if (FullySpecifiedType type = symbol->type()) {
        if (NamedType *namedType = type->asNamedType()) {
            if (const Name *name = namedType->name()) {
611
                if (name->match(&qPrivateSignalIdentifier))
612 613 614 615 616 617 618
                    return true;
            }
        }
    }
    return false;
}

619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637
QString createQt4SignalOrSlot(CPlusPlus::Function *function, const Overview &overview)
{
    QString signature;
    signature += Overview().prettyName(function->name());
    signature += QLatin1Char('(');
    for (unsigned i = 0, to = function->argumentCount(); i < to; ++i) {
        Symbol *arg = function->argumentAt(i);
        if (isQPrivateSignal(arg))
            continue;
        if (i != 0)
            signature += QLatin1Char(',');
        signature += overview.prettyType(arg->type());
    }
    signature += QLatin1Char(')');

    const QByteArray normalized = QMetaObject::normalizedSignature(signature.toUtf8());
    return QString::fromUtf8(normalized, normalized.size());
}

638
QString createQt5SignalOrSlot(CPlusPlus::Function *function, const Overview &overview)
639 640
{
    QString text;
641
    text += overview.prettyName(function->name());
642 643 644
    return text;
}

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
/*!
    \class BackwardsEater
    \brief Checks strings and expressions before given position.

    Similar to BackwardsScanner, but also can handle expressions. Ignores whitespace.
*/
class BackwardsEater
{
public:
    explicit BackwardsEater(const CppCompletionAssistInterface *assistInterface, int position)
        : m_position(position)
        , m_assistInterface(assistInterface)
    {
    }

    bool isPositionValid() const
    {
        return m_position >= 0;
    }

    bool eatConnectOpenParenthesis()
    {
        return eatString(QLatin1String("(")) && eatString(QLatin1String("connect"));
    }

    bool eatExpressionCommaAmpersand()
    {
        return eatString(QLatin1String("&")) && eatString(QLatin1String(",")) && eatExpression();
    }

    bool eatConnectOpenParenthesisExpressionCommaAmpersandExpressionComma()
    {
        return eatString(QLatin1String(","))
            && eatExpression()
            && eatExpressionCommaAmpersand()
            && eatConnectOpenParenthesis();
    }

private:
    bool eatExpression()
    {
        if (!isPositionValid())
            return false;

        maybeEatWhitespace();

        QTextCursor cursor(m_assistInterface->textDocument());
        cursor.setPosition(m_position + 1);
693
        ExpressionUnderCursor expressionUnderCursor(m_assistInterface->languageFeatures());
694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768
        const QString expression = expressionUnderCursor(cursor);
        if (expression.isEmpty())
            return false;
        m_position = m_position - expression.length();
        return true;
    }

    bool eatString(const QString &string)
    {
        if (!isPositionValid())
            return false;

        if (string.isEmpty())
            return true;

        maybeEatWhitespace();

        const int stringLength = string.length();
        const int stringStart = m_position - (stringLength - 1);

        if (stringStart < 0)
            return false;

        if (m_assistInterface->textAt(stringStart, stringLength) == string) {
            m_position = stringStart - 1;
            return true;
        }

        return false;
    }

    void maybeEatWhitespace()
    {
        while (isPositionValid() && m_assistInterface->characterAt(m_position).isSpace())
            --m_position;
    }

private:
    int m_position;
    const CppCompletionAssistInterface * const m_assistInterface;
};

bool canCompleteConnectSignalAt2ndArgument(const CppCompletionAssistInterface *assistInterface,
                                           int startOfExpression)
{
    BackwardsEater eater(assistInterface, startOfExpression);

    return eater.isPositionValid()
        && eater.eatExpressionCommaAmpersand()
        && eater.eatConnectOpenParenthesis();
}

bool canCompleteConnectSignalAt4thArgument(const CppCompletionAssistInterface *assistInterface,
                                           int startPosition)
{
    BackwardsEater eater(assistInterface, startPosition);

    return eater.isPositionValid()
        && eater.eatExpressionCommaAmpersand()
        && eater.eatConnectOpenParenthesisExpressionCommaAmpersandExpressionComma();
}

bool canCompleteClassNameAt2ndOr4thConnectArgument(
        const CppCompletionAssistInterface *assistInterface,
        int startPosition)
{
    BackwardsEater eater(assistInterface, startPosition);

    if (!eater.isPositionValid())
        return false;

    return eater.eatConnectOpenParenthesis()
        || eater.eatConnectOpenParenthesisExpressionCommaAmpersandExpressionComma();
}

769 770
ClassOrNamespace *classOrNamespaceFromLookupItem(const LookupItem &lookupItem,
                                                 const LookupContext &context)
771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798
{
    const Name *name = 0;

    if (Symbol *d = lookupItem.declaration()) {
        if (Class *k = d->asClass())
            name = k->name();
    }

    if (!name) {
        FullySpecifiedType type = lookupItem.type().simplified();

        if (PointerType *pointerType = type->asPointerType())
            type = pointerType->elementType().simplified();
        else
            return 0; // not a pointer or a reference to a pointer.

        NamedType *namedType = type->asNamedType();
        if (!namedType) // not a class name.
            return 0;

        name = namedType->name();
    }

    return name ? context.lookupType(name, lookupItem.scope()) : 0;
}

Class *classFromLookupItem(const LookupItem &lookupItem, const LookupContext &context)
{
799
    ClassOrNamespace *b = classOrNamespaceFromLookupItem(lookupItem, context);
800 801 802 803 804 805 806 807 808 809 810 811
    if (!b)
        return 0;

    foreach (Symbol *s, b->symbols()) {
        if (Class *klass = s->asClass())
            return klass;
    }
    return 0;
}

const Name *minimalName(Symbol *symbol, Scope *targetScope, const LookupContext &context)
{
812
    ClassOrNamespace *target = context.lookupType(targetScope);
813 814 815 816 817
    if (!target)
        target = context.globalNamespace();
    return context.minimalName(symbol, target, context.bindings()->control().data());
}

Leandro Melo's avatar
Leandro Melo committed
818 819
} // Anonymous

820 821 822 823
// ------------------------------------
// InternalCppCompletionAssistProcessor
// ------------------------------------
InternalCppCompletionAssistProcessor::InternalCppCompletionAssistProcessor()
824
    : m_model(new CppAssistProposalModel)
825 826
{
}
Leandro Melo's avatar
Leandro Melo committed
827

828
InternalCppCompletionAssistProcessor::~InternalCppCompletionAssistProcessor()
Leandro Melo's avatar
Leandro Melo committed
829 830
{}

831
IAssistProposal * InternalCppCompletionAssistProcessor::perform(const AssistInterface *interface)
Leandro Melo's avatar
Leandro Melo committed
832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848
{
    m_interface.reset(static_cast<const CppCompletionAssistInterface *>(interface));

    if (interface->reason() != ExplicitlyInvoked && !accepts())
        return 0;

    int index = startCompletionHelper();
    if (index != -1) {
        if (m_hintProposal)
            return m_hintProposal;

        return createContentProposal();
    }

    return 0;
}

849
bool InternalCppCompletionAssistProcessor::accepts() const
Leandro Melo's avatar
Leandro Melo committed
850 851 852 853 854 855 856
{
    const int pos = m_interface->position();
    unsigned token = T_EOF_SYMBOL;

    const int start = startOfOperator(pos, &token, /*want function call=*/ true);
    if (start != pos) {
        if (token == T_POUND) {
857
            const int column = pos - m_interface->textDocument()->findBlock(start).position();
Leandro Melo's avatar
Leandro Melo committed
858 859 860 861 862 863 864 865
            if (column != 1)
                return false;
        }

        return true;
    } else {
        // Trigger completion after three characters of a name have been typed, when not editing an existing name
        QChar characterUnderCursor = m_interface->characterAt(pos);
866 867

        if (!isValidIdentifierChar(characterUnderCursor)) {
868
            const int startOfName = findStartOfName(pos);
869
            if (pos - startOfName >= 3) {
Leandro Melo's avatar
Leandro Melo committed
870
                const QChar firstCharacter = m_interface->characterAt(startOfName);
871
                if (isValidFirstIdentifierChar(firstCharacter)) {
872
                    // Finally check that we're not inside a comment or string (code copied from startOfOperator)
873
                    QTextCursor tc(m_interface->textDocument());
874 875 876
                    tc.setPosition(pos);

                    SimpleLexer tokenize;
877
                    tokenize.setLanguageFeatures(m_interface->languageFeatures());
878
                    tokenize.setSkipComments(false);
879

880
                    const Tokens &tokens = tokenize(tc.block().text(), BackwardsScanner::previousBlockState(tc.block()));
881 882 883
                    const int tokenIdx = SimpleLexer::tokenBefore(tokens, qMax(0, tc.positionInBlock() - 1));
                    const Token tk = (tokenIdx == -1) ? Token() : tokens.at(tokenIdx);

884
                    if (!tk.isComment() && !tk.isLiteral()) {
885
                        return true;
886 887 888 889 890 891 892
                    } else if (tk.isLiteral()
                               && tokens.size() == 3
                               && tokens.at(0).kind() == T_POUND
                               && tokens.at(1).kind() == T_IDENTIFIER) {
                        const QString &line = tc.block().text();
                        const Token &idToken = tokens.at(1);
                        const QStringRef &identifier =
893 894
                                line.midRef(idToken.utf16charsBegin(),
                                            idToken.utf16charsEnd() - idToken.utf16charsBegin());
895 896
                        if (identifier == QLatin1String("include")
                                || identifier == QLatin1String("include_next")
897
                                || (m_interface->languageFeatures().objCEnabled && identifier == QLatin1String("import"))) {
898 899 900
                            return true;
                        }
                    }
901 902
                }
            }
903
        }
904
    }
con's avatar
con committed
905 906 907 908

    return false;
}

909
IAssistProposal *InternalCppCompletionAssistProcessor::createContentProposal()
con's avatar
con committed
910
{
Leandro Melo's avatar
Leandro Melo committed
911 912
    // Duplicates are kept only if they are snippets.
    QSet<QString> processed;
913
    auto it = m_completions.begin();
Leandro Melo's avatar
Leandro Melo committed
914 915
    while (it != m_completions.end()) {
        CppAssistProposalItem *item = static_cast<CppAssistProposalItem *>(*it);
916
        if (!processed.contains(item->text()) || item->isSnippet()) {
Leandro Melo's avatar
Leandro Melo committed
917
            ++it;
918
            if (!item->isSnippet()) {
Leandro Melo's avatar
Leandro Melo committed
919 920 921 922 923 924
                processed.insert(item->text());
                if (!item->isOverloaded()) {
                    if (Symbol *symbol = qvariant_cast<Symbol *>(item->data())) {
                        if (Function *funTy = symbol->type()->asFunctionType()) {
                            if (funTy->hasArguments())
                                item->markAsOverloaded();
925
                        }
Leandro Melo's avatar
Leandro Melo committed
926
                    }
927 928
                }
            }
Leandro Melo's avatar
Leandro Melo committed
929
        } else {
930
            delete *it;
Leandro Melo's avatar
Leandro Melo committed
931
            it = m_completions.erase(it);
932
        }
933
    }
934

Leandro Melo's avatar
Leandro Melo committed
935
    m_model->loadContent(m_completions);
936
    return new CppAssistProposal(m_positionForProposal, m_model.take());
Leandro Melo's avatar
Leandro Melo committed
937
}
938

939
IAssistProposal *InternalCppCompletionAssistProcessor::createHintProposal(
940
    QList<Function *> functionSymbols) const
Leandro Melo's avatar
Leandro Melo committed
941
{
942 943
    IFunctionHintProposalModel *model =
            new CppFunctionHintModel(functionSymbols, m_model->m_typeOfExpression);
944
    IAssistProposal *proposal = new FunctionHintProposal(m_positionForProposal, model);
Leandro Melo's avatar
Leandro Melo committed
945
    return proposal;
946 947
}

948
int InternalCppCompletionAssistProcessor::startOfOperator(int positionInDocument,
949 950
                                                          unsigned *kind,
                                                          bool wantFunctionCall) const
951
{
952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976
    const QChar ch  = m_interface->characterAt(positionInDocument - 1);
    const QChar ch2 = m_interface->characterAt(positionInDocument - 2);
    const QChar ch3 = m_interface->characterAt(positionInDocument - 3);

    int start = positionInDocument
                 - CppCompletionAssistProvider::activationSequenceChar(ch, ch2, ch3, kind,
                                                                       wantFunctionCall,
                                                                       /*wantQt5SignalSlots*/ true);

    const auto dotAtIncludeCompletionHandler = [this](int &start, unsigned *kind) {
            start = findStartOfName(start);
            const QChar ch4 = m_interface->characterAt(start - 1);
            const QChar ch5 = m_interface->characterAt(start - 2);
            const QChar ch6 = m_interface->characterAt(start - 3);
            start = start - CppCompletionAssistProvider::activationSequenceChar(
                                ch4, ch5, ch6, kind, false, false);
    };

    CppCompletionAssistProcessor::startOfOperator(m_interface->textDocument(),
                                                  positionInDocument,
                                                  kind,
                                                  start,
                                                  m_interface->languageFeatures(),
                                                  /*adjustForQt5SignalSlotCompletion=*/ true,
                                                  dotAtIncludeCompletionHandler);
Leandro Melo's avatar
Leandro Melo committed
977 978 979
    return start;
}

980
int InternalCppCompletionAssistProcessor::findStartOfName(int pos) const
Leandro Melo's avatar
Leandro Melo committed
981 982 983 984 985 986 987 988
{
    if (pos == -1)
        pos = m_interface->position();
    QChar chr;

    // Skip to the start of a name
    do {
        chr = m_interface->characterAt(--pos);
989
    } while (CppTools::isValidIdentifierChar(chr));
Leandro Melo's avatar
Leandro Melo committed
990 991

    return pos + 1;
992 993
}

994
int InternalCppCompletionAssistProcessor::startCompletionHelper()
995
{
996
    if (m_interface->languageFeatures().objCEnabled) {
Leandro Melo's avatar
Leandro Melo committed
997
        if (tryObjCCompletion())
998
            return m_positionForProposal;
Leandro Melo's avatar
Leandro Melo committed
999 1000 1001
    }

    const int startOfName = findStartOfName();
1002
    m_positionForProposal = startOfName;
Leandro Melo's avatar
Leandro Melo committed
1003 1004
    m_model->m_completionOperator = T_EOF_SYMBOL;

1005
    int endOfOperator = m_positionForProposal;
Leandro Melo's avatar
Leandro Melo committed
1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016

    // Skip whitespace preceding this position
    while (m_interface->characterAt(endOfOperator - 1).isSpace())
        --endOfOperator;

    int endOfExpression = startOfOperator(endOfOperator,
                                          &m_model->m_completionOperator,
                                          /*want function call =*/ true);

    if (m_model->m_completionOperator == T_DOXY_COMMENT) {
        for (int i = 1; i < T_DOXY_LAST_TAG; ++i)
1017
            addCompletionItem(QString::fromLatin1(doxygenTagSpell(i)), Icons::keywordIcon());
1018
        return m_positionForProposal;
Leandro Melo's avatar
Leandro Melo committed
1019 1020 1021 1022 1023
    }

    // Pre-processor completion
    if (m_model->m_completionOperator == T_POUND) {
        completePreprocessor();
1024 1025
        m_positionForProposal = startOfName;
        return m_positionForProposal;
Leandro Melo's avatar
Leandro Melo committed
1026 1027 1028 1029 1030 1031 1032
    }

    // Include completion
    if (m_model->m_completionOperator == T_STRING_LITERAL
        || m_model->m_completionOperator == T_ANGLE_STRING_LITERAL
        || m_model->m_completionOperator == T_SLASH) {

1033
        QTextCursor c(m_interface->textDocument());
Leandro Melo's avatar
Leandro Melo committed
1034 1035
        c.setPosition(endOfExpression);
        if (completeInclude(c))
1036 1037
            m_positionForProposal = endOfExpression + 1;
        return m_positionForProposal;
Leandro Melo's avatar
Leandro Melo committed
1038 1039
    }

1040
    ExpressionUnderCursor expressionUnderCursor(m_interface->languageFeatures());
1041
    QTextCursor tc(m_interface->textDocument());
Leandro Melo's avatar
Leandro Melo committed
1042 1043 1044 1045 1046 1047 1048 1049 1050 1051

    if (m_model->m_completionOperator == T_COMMA) {
        tc.setPosition(endOfExpression);
        const int start = expressionUnderCursor.startOfFunctionCall(tc);
        if (start == -1) {
            m_model->m_completionOperator = T_EOF_SYMBOL;
            return -1;
        }

        endOfExpression = start;
1052
        m_positionForProposal = start + 1;
Leandro Melo's avatar
Leandro Melo committed
1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063
        m_model->m_completionOperator = T_LPAREN;
    }

    QString expression;
    int startOfExpression = m_interface->position();
    tc.setPosition(endOfExpression);

    if (m_model->m_completionOperator) {
        expression = expressionUnderCursor(tc);
        startOfExpression = endOfExpression - expression.length();

1064
        if (m_model->m_completionOperator == T_AMPER) {
1065 1066 1067 1068
            // We expect 'expression' to be either "sender" or "receiver" in
            //  "connect(sender, &" or
            //  "connect(otherSender, &Foo::signal1, receiver, &"
            const int beforeExpression = startOfExpression - 1;
1069 1070
            if (canCompleteClassNameAt2ndOr4thConnectArgument(m_interface.data(),
                                                              beforeExpression)) {
1071
                m_model->m_completionOperator = CompleteQt5SignalOrSlotClassNameTrigger;
1072
            } else { // Ensure global completion
1073
                startOfExpression = endOfExpression = m_positionForProposal;
1074 1075 1076
                expression.clear();
                m_model->m_completionOperator = T_EOF_SYMBOL;
            }
1077 1078 1079 1080 1081 1082 1083 1084 1085
        } else if (m_model->m_completionOperator == T_COLON_COLON) {
            // We expect 'expression' to be "Foo" in
            //  "connect(sender, &Foo::" or
            //  "connect(sender, &Bar::signal1, receiver, &Foo::"
            const int beforeExpression = startOfExpression - 1;
            if (canCompleteConnectSignalAt2ndArgument(m_interface.data(), beforeExpression))
                m_model->m_completionOperator = CompleteQt5SignalTrigger;
            else if (canCompleteConnectSignalAt4thArgument(m_interface.data(), beforeExpression))
                m_model->m_completionOperator = CompleteQt5SlotTrigger;
1086
        } else if (m_model->m_completionOperator == T_LPAREN) {
1087
            if (expression.endsWith(QLatin1String("SIGNAL"))) {
Leandro Melo's avatar
Leandro Melo committed
1088
                m_model->m_completionOperator = T_SIGNAL;
1089
            } else if (expression.endsWith(QLatin1String("SLOT"))) {
Leandro Melo's avatar
Leandro Melo committed
1090
                m_model->m_completionOperator = T_SLOT;
1091
            } else if (m_interface->position() != endOfOperator) {
Leandro Melo's avatar
Leandro Melo committed
1092 1093 1094
                // We don't want a function completion when the cursor isn't at the opening brace
                expression.clear();
                m_model->m_completionOperator = T_EOF_SYMBOL;
1095
                m_positionForProposal = startOfName;
Leandro Melo's avatar
Leandro Melo committed
1096 1097 1098 1099 1100 1101 1102 1103 1104
                startOfExpression = m_interface->position();
            }
        }
    } else if (expression.isEmpty()) {
        while (startOfExpression > 0 && m_interface->characterAt(startOfExpression).isSpace())
            --startOfExpression;
    }

    int line = 0, column = 0;
1105
    Convenience::convertPosition(m_interface->textDocument(), startOfExpression, &line, &column);
1106
    const QString fileName = m_interface->fileName();
Leandro Melo's avatar
Leandro Melo committed
1107 1108
    return startCompletionInternal(fileName, line, column, expression, endOfExpression);
}
1109

1110
bool InternalCppCompletionAssistProcessor::tryObjCCompletion()
Leandro Melo's avatar
Leandro Melo committed
1111 1112 1113
{
    int end = m_interface->position();
    while (m_interface->characterAt(end).isSpace())
1114
        ++end;
Leandro Melo's avatar
Leandro Melo committed
1115
    if (m_interface->characterAt(end) != QLatin1Char(']'))
1116 1117
        return false;

1118
    QTextCursor tc(m_interface->textDocument());
1119
    tc.setPosition(end);
1120
    BackwardsScanner tokens(tc, m_interface->languageFeatures());
1121 1122 1123 1124 1125 1126 1127
    if (tokens[tokens.startToken() - 1].isNot(T_RBRACKET))
        return false;

    const int start = tokens.startOfMatchingBrace(tokens.startToken());
    if (start == tokens.startToken())
        return false;

1128
    const int startPos = tokens[start].bytesBegin() + tokens.startPosition();
Leandro Melo's avatar
Leandro Melo committed
1129
    const QString expr = m_interface->textAt(startPos, m_interface->position() - startPos);
1130

1131
    Document::Ptr thisDocument = m_interface->snapshot().document(m_interface->fileName());
1132
    if (!thisDocument)
1133 1134
        return false;

1135 1136
    m_model->m_typeOfExpression->init(thisDocument, m_interface->snapshot());

1137
    int line = 0, column = 0;
1138
    Convenience::convertPosition(m_interface->textDocument(), m_interface->position(), &line, &column);
1139 1140 1141 1142
    Scope *scope = thisDocument->scopeAt(line, column);
    if (!scope)
        return false;

1143
    const QList<LookupItem> items = (*m_model->m_typeOfExpression)(expr.toUtf8(), scope);
1144
    LookupContext lookupContext(thisDocument, m_interface->snapshot());
1145 1146 1147 1148 1149 1150 1151

    foreach (const LookupItem &item, items) {
        FullySpecifiedType ty = item.type().simplified();
        if (ty->isPointerType()) {
            ty = ty->asPointerType()->elementType().simplified();

            if (NamedType *namedTy = ty->asNamedType()) {
1152
                ClassOrNamespace *binding = lookupContext.lookupType(namedTy->name(), item.scope());
1153 1154 1155 1156
                completeObjCMsgSend(binding, false);
            }
        } else {
            if (ObjCClass *clazz = ty->asObjCClassType()) {
1157
                ClassOrNamespace *binding = lookupContext.lookupType(clazz->name(), item.scope());
1158 1159 1160 1161 1162 1163 1164 1165
                completeObjCMsgSend(binding, true);
            }
        }
    }

    if (m_completions.isEmpty())
        return false;

1166
    m_positionForProposal = m_interface->position();
1167 1168 1169
    return true;
}

1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181
namespace {
enum CompletionOrder {
    // default order is 0
    FunctionArgumentsOrder = 2,
    FunctionLocalsOrder = 2, // includes local types
    PublicClassMemberOrder = 1,
    InjectedClassNameOrder = -1,
    MacrosOrder = -2,
    KeywordsOrder = -2
};
}

1182 1183 1184 1185
void InternalCppCompletionAssistProcessor::addCompletionItem(const QString &text,
                                                             const QIcon &icon,
                                                             int order,
                                                             const QVariant &data)
1186
{
1187
    AssistProposalItem *item = new CppAssistProposalItem;
Leandro Melo's avatar
Leandro Melo committed
1188 1189 1190 1191 1192 1193
    item->setText(text);
    item->setIcon(icon);
    item->setOrder(order);
    item->setData(data);
    m_completions.append(item);
}
1194

1195
void InternalCppCompletionAssistProcessor::addCompletionItem(Symbol *symbol, int order)
Leandro Melo's avatar
Leandro Melo committed
1196 1197
{
    ConvertToCompletionItem toCompletionItem;
1198
    AssistProposalItem *item = toCompletionItem(symbol);
Leandro Melo's avatar
Leandro Melo committed
1199
    if (item) {
1200
        item->setIcon(Icons::iconForSymbol(symbol));
1201
        item->setOrder(order);
Leandro Melo's avatar
Leandro Melo committed
1202
        m_completions.append(item);
1203
    }
Leandro Melo's avatar
Leandro Melo committed
1204
}
1205

1206
void InternalCppCompletionAssistProcessor::completeObjCMsgSend(ClassOrNamespace *binding,
1207
                                                               bool staticClassAccess)
Leandro Melo's avatar
Leandro Melo committed
1208 1209 1210 1211 1212 1213
{
    QList<Scope*> memberScopes;
    foreach (Symbol *s, binding->symbols()) {
        if (ObjCClass *c = s->asObjCClass())
            memberScopes.append(c);
    }
con's avatar
con committed
1214

Leandro Melo's avatar
Leandro Melo committed
1215 1216 1217
    foreach (Scope *scope, memberScopes) {
        for (unsigned i = 0; i < scope->memberCount(); ++i) {
            Symbol *symbol = scope->memberAt(i);
con's avatar
con committed
1218

Leandro Melo's avatar
Leandro Melo committed
1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230
            if (ObjCMethod *method = symbol->type()->asObjCMethodType()) {
                if (method->isStatic() == staticClassAccess) {
                    Overview oo;
                    const SelectorNameId *selectorName =
                            method->name()->asSelectorNameId();
                    QString text;
                    QString data;
                    if (selectorName->hasArguments()) {
                        for (unsigned i = 0; i < selectorName->nameCount(); ++i) {
                            if (i > 0)
                                text += QLatin1Char(' ');
                            Symbol *arg = method->argumentAt(i);
1231
                            text += QString::fromUtf8(selectorName->nameAt(i)->identifier()->chars());
Leandro Melo's avatar
Leandro Melo committed
1232
                            text += QLatin1Char(':');
1233
                            text += Snippet::kVariableDelimiter;
Leandro Melo's avatar
Leandro Melo committed
1234
                            text += QLatin1Char('(');
1235
                            text += oo.prettyType(arg->type());
Leandro Melo's avatar
Leandro Melo committed
1236
                            text += QLatin1Char(')');
1237
                            text += oo.prettyName(arg->name());
1238
                            text += Snippet::kVariableDelimiter;
Leandro Melo's avatar
Leandro Melo committed
1239 1240
                        }
                    } else {
1241
                        text = QString::fromUtf8(selectorName->identifier()->chars());
Leandro Melo's avatar
Leandro Melo committed
1242 1243
                    }
                    data = text;
con's avatar
con committed
1244

Leandro Melo's avatar
Leandro Melo committed
1245 1246 1247 1248
                    if (!text.isEmpty())
                        addCompletionItem(text, QIcon(), 0, QVariant::fromValue(data));
                }
            }
1249 1250
        }
    }
Leandro Melo's avatar
Leandro Melo committed
1251
}
1252

1253
bool InternalCppCompletionAssistProcessor::completeInclude(const QTextCursor &cursor)
Leandro Melo's avatar
Leandro Melo committed
1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268
{
    QString directoryPrefix;
    if (m_model->m_completionOperator == T_SLASH) {
        QTextCursor c = cursor;
        c.movePosition(QTextCursor::StartOfLine, QTextCursor::KeepAnchor);
        QString sel = c.selectedText();
        int startCharPos = sel.indexOf(QLatin1Char('"'));
        if (startCharPos == -1) {
            startCharPos = sel.indexOf(QLatin1Char('<'));
            m_model->m_completionOperator = T_ANGLE_STRING_LITERAL;
        } else {
            m_model->m_completionOperator = T_STRING_LITERAL;
        }
        if (startCharPos != -1)
            directoryPrefix = sel.mid(startCharPos + 1, sel.length() - 1);
1269 1270
    }

Leandro Melo's avatar
Leandro Melo committed
1271
    // Make completion for all relevant includes
1272 1273 1274
    ProjectPartHeaderPaths headerPaths = m_interface->headerPaths();
    const ProjectPartHeaderPath currentFilePath(QFileInfo(m_interface->fileName()).path(),
                                                ProjectPartHeaderPath::IncludePath);
1275 1276
    if (!headerPaths.contains(currentFilePath))
        headerPaths.append(currentFilePath);
Leandro Melo's avatar
Leandro Melo committed
1277

Eike Ziller's avatar
Eike Ziller committed
1278 1279
    Utils::MimeDatabase mdb;
    const QStringList suffixes = mdb.mimeTypeForName(QLatin1String("text/x-c++hdr")).suffixes();
1280

1281
    foreach (const ProjectPartHeaderPath &headerPath, headerPaths) {
1282
        QString realPath = headerPath.path;
Leandro Melo's avatar
Leandro Melo committed
1283 1284 1285
        if (!directoryPrefix.isEmpty()) {
            realPath += QLatin1Char('/');
            realPath += directoryPrefix;
1286 1287
            if (headerPath.isFrameworkPath())
                realPath += QLatin1String(".framework/Headers");
1288
        }
1289
        completeInclude(realPath, suffixes);
1290 1291
    }

Leandro Melo's avatar
Leandro Melo committed
1292 1293
    return !m_completions.isEmpty();
}
1294

1295 1296
void InternalCppCompletionAssistProcessor::completeInclude(const QString &realPath,
                                                           const QStringList &suffixes)
1297 1298 1299 1300 1301 1302 1303 1304 1305 1306
{
    QDirIterator i(realPath, QDir::Files | QDir::Dirs | QDir::NoDotAndDotDot);
    while (i.hasNext()) {
        const QString fileName = i.next();
        const QFileInfo fileInfo = i.fileInfo();
        const QString suffix = fileInfo.suffix();
        if (suffix.isEmpty() || suffixes.contains(suffix)) {
            QString text = fileName.mid(realPath.length() + 1);
            if (fileInfo.isDir())
                text += QLatin1Char('/');
1307
            addCompletionItem(text, Icons::keywordIcon());
1308 1309 1310 1311
        }
    }
}

1312
void InternalCppCompletionAssistProcessor::completePreprocessor()
Leandro Melo's avatar
Leandro Melo committed
1313
{
1314
    foreach (const QString &preprocessorCompletion, m_preprocessorCompletions)
Leandro Melo's avatar
Leandro Melo committed
1315
        addCompletionItem(preprocessorCompletion);
1316

Leandro Melo's avatar
Leandro Melo committed
1317 1318 1319
    if (objcKeywordsWanted())
        addCompletionItem(QLatin1String("import"));
}
1320

1321
bool InternalCppCompletionAssistProcessor::objcKeywordsWanted() const
Leandro Melo's avatar
Leandro Melo committed
1322
{
1323
    if (!m_interface->languageFeatures().objCEnabled)
Leandro Melo's avatar
Leandro Melo committed
1324
        return false;
1325

1326
    const QString fileName = m_interface->fileName();
con's avatar
con committed
1327

Eike Ziller's avatar
Eike Ziller committed
1328 1329 1330 1331
    Utils::MimeDatabase mdb;
    const Utils::MimeType mt = mdb.mimeTypeForFile(fileName);
    return mt.matchesName(QLatin1String(CppTools::Constants::OBJECTIVE_C_SOURCE_MIMETYPE))
            || mt.matchesName(QLatin1String(CppTools::Constants::OBJECTIVE_CPP_SOURCE_MIMETYPE));
1332
}
con's avatar
con committed
1333

1334 1335 1336 1337
int InternalCppCompletionAssistProcessor::startCompletionInternal(const QString &fileName,
                                                                  unsigned line, unsigned column,
                                                                  const QString &expr,
                                                                  int endOfExpression)
1338 1339
{
    QString expression = expr.trimmed();
1340

1341
    Document::Ptr thisDocument = m_interface->snapshot().document(fileName);
1342
    if (!thisDocument)
1343
        return -1;
con's avatar
con committed
1344

1345
    m_model->m_typeOfExpression->init(thisDocument, m_interface->snapshot());
1346 1347

    Scope *scope = thisDocument->scopeAt(line, column);
1348
    QTC_ASSERT(scope != 0, return -1);
con's avatar