cppcompletionassist.cpp 68.1 KB
Newer Older
hjk's avatar
hjk committed
1
/****************************************************************************
con's avatar
con committed
2
**
hjk's avatar
hjk committed
3 4
** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
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 12 13 14
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia.  For licensing terms and
** conditions see http://qt.digia.com/licensing.  For further information
** use the contact form at http://qt.digia.com/contact-us.
15
**
16
** GNU Lesser General Public License Usage
hjk's avatar
hjk committed
17 18 19 20 21 22 23 24 25
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights.  These rights are described in the Digia Qt LGPL Exception
con's avatar
con committed
26 27
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
hjk's avatar
hjk committed
28
****************************************************************************/
hjk's avatar
hjk committed
29

con's avatar
con committed
30
#include "cppmodelmanager.h"
Leandro Melo's avatar
Leandro Melo committed
31
#include "cppcompletionassist.h"
32
#include "cppdoxygen.h"
Leandro Melo's avatar
Leandro Melo committed
33
#include "cppmodelmanager.h"
34
#include "cpptoolsconstants.h"
con's avatar
con committed
35 36 37 38 39 40 41 42 43 44 45 46

#include <Control.h>
#include <AST.h>
#include <ASTVisitor.h>
#include <CoreTypes.h>
#include <Literals.h>
#include <Names.h>
#include <NameVisitor.h>
#include <Symbols.h>
#include <SymbolVisitor.h>
#include <Scope.h>
#include <TranslationUnit.h>
47
#include <CppRewriter.h>
hjk's avatar
hjk committed
48

con's avatar
con committed
49
#include <cplusplus/ResolveExpression.h>
50
#include <cplusplus/MatchingText.h>
con's avatar
con committed
51 52
#include <cplusplus/Overview.h>
#include <cplusplus/ExpressionUnderCursor.h>
53
#include <cplusplus/BackwardsScanner.h>
54
#include <cplusplus/LookupContext.h>
con's avatar
con committed
55

56
#include <coreplugin/idocument.h>
con's avatar
con committed
57
#include <coreplugin/icore.h>
58
#include <coreplugin/mimedatabase.h>
Leandro Melo's avatar
Leandro Melo committed
59 60 61 62 63 64 65
#include <cppeditor/cppeditorconstants.h>
#include <texteditor/codeassist/basicproposalitem.h>
#include <texteditor/codeassist/basicproposalitemlistmodel.h>
#include <texteditor/codeassist/genericproposal.h>
#include <texteditor/codeassist/ifunctionhintproposalmodel.h>
#include <texteditor/codeassist/functionhintproposal.h>
#include <texteditor/convenience.h>
66
#include <texteditor/snippets/snippet.h>
Leandro Melo's avatar
Leandro Melo committed
67 68
#include <texteditor/texteditorsettings.h>
#include <texteditor/completionsettings.h>
69
#include <utils/qtcassert.h>
con's avatar
con committed
70

71 72 73 74
#include <QLatin1String>
#include <QTextCursor>
#include <QTextDocument>
#include <QIcon>
75

con's avatar
con committed
76
using namespace CPlusPlus;
Leandro Melo's avatar
Leandro Melo committed
77 78
using namespace CppEditor;
using namespace CppTools;
79
using namespace CppTools::Internal;
Leandro Melo's avatar
Leandro Melo committed
80
using namespace TextEditor;
con's avatar
con committed
81

Leandro Melo's avatar
Leandro Melo committed
82 83
namespace CppTools {
namespace Internal {
84

Leandro Melo's avatar
Leandro Melo committed
85 86 87 88 89
struct CompleteFunctionDeclaration
{
    explicit CompleteFunctionDeclaration(Function *f = 0)
        : function(f)
    {}
90

Leandro Melo's avatar
Leandro Melo committed
91 92
    Function *function;
};
93

Leandro Melo's avatar
Leandro Melo committed
94 95 96 97 98 99 100 101 102 103
// ----------------------
// CppAssistProposalModel
// ----------------------
class CppAssistProposalModel : public TextEditor::BasicProposalItemListModel
{
public:
    CppAssistProposalModel()
        : TextEditor::BasicProposalItemListModel()
        , m_completionOperator(T_EOF_SYMBOL)
        , m_replaceDotForArrow(false)
104
        , m_typeOfExpression(new TypeOfExpression)
105 106 107
    {
        m_typeOfExpression->setExpandTemplates(true);
    }
108

109
    virtual bool isSortable(const QString &prefix) const;
Leandro Melo's avatar
Leandro Melo committed
110
    virtual IAssistProposalItem *proposalItem(int index) const;
con's avatar
con committed
111

Leandro Melo's avatar
Leandro Melo committed
112 113
    unsigned m_completionOperator;
    bool m_replaceDotForArrow;
114
    QSharedPointer<TypeOfExpression> m_typeOfExpression;
Leandro Melo's avatar
Leandro Melo committed
115
};
116

Leandro Melo's avatar
Leandro Melo committed
117 118 119 120
// ---------------------
// CppAssistProposalItem
// ---------------------
class CppAssistProposalItem : public TextEditor::BasicProposalItem
121
{
Leandro Melo's avatar
Leandro Melo committed
122
public:
123
    CppAssistProposalItem() :
124
        m_isOverloaded(false) {}
125

Leandro Melo's avatar
Leandro Melo committed
126 127 128
    virtual bool prematurelyApplies(const QChar &c) const;
    virtual void applyContextualContent(TextEditor::BaseTextEditor *editor,
                                        int basePosition) const;
129

Leandro Melo's avatar
Leandro Melo committed
130 131 132
    bool isOverloaded() const { return m_isOverloaded; }
    void markAsOverloaded() { m_isOverloaded = true; }
    void keepCompletionOperator(unsigned compOp) { m_completionOperator = compOp; }
133 134
    void keepTypeOfExpression(const QSharedPointer<TypeOfExpression> &typeOfExp)
    { m_typeOfExpression = typeOfExp; }
135

Leandro Melo's avatar
Leandro Melo committed
136 137 138 139
private:
    bool m_isOverloaded;
    unsigned m_completionOperator;
    mutable QChar m_typedChar;
140
    QSharedPointer<TypeOfExpression> m_typeOfExpression;
Leandro Melo's avatar
Leandro Melo committed
141
};
142

Leandro Melo's avatar
Leandro Melo committed
143 144
} // Internal
} // CppTools
145

Leandro Melo's avatar
Leandro Melo committed
146
Q_DECLARE_METATYPE(CppTools::Internal::CompleteFunctionDeclaration)
147

148 149 150 151 152 153 154 155
bool CppAssistProposalModel::isSortable(const QString &prefix) const
{
    if (m_completionOperator != T_EOF_SYMBOL)
        return true;

    return !prefix.isEmpty();
}

Leandro Melo's avatar
Leandro Melo committed
156 157 158 159 160 161 162
IAssistProposalItem *CppAssistProposalModel::proposalItem(int index) const
{
    BasicProposalItem *item =
        static_cast<BasicProposalItem *>(BasicProposalItemListModel::proposalItem(index));
    if (!item->data().canConvert<QString>()) {
        CppAssistProposalItem *cppItem = static_cast<CppAssistProposalItem *>(item);
        cppItem->keepCompletionOperator(m_completionOperator);
163
        cppItem->keepTypeOfExpression(m_typeOfExpression);
Leandro Melo's avatar
Leandro Melo committed
164 165 166
    }
    return item;
}
167

Leandro Melo's avatar
Leandro Melo committed
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
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;
}

200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219
static bool isDereferenced(TextEditor::BaseTextEditor *editor, int basePosition)
{
    QTextCursor cursor = editor->editorWidget()->textCursor();
    cursor.setPosition(basePosition);

    BackwardsScanner scanner(cursor);
    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;
}

Leandro Melo's avatar
Leandro Melo committed
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
void CppAssistProposalItem::applyContextualContent(TextEditor::BaseTextEditor *editor,
                                                    int basePosition) const
{
    Symbol *symbol = 0;

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

    QString toInsert;
    QString extraChars;
    int extraLength = 0;
    int cursorOffset = 0;

    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();

        const CompletionSettings &completionSettings =
                TextEditorSettings::instance()->completionSettings();
        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.
                if (! function->hasReturnType() && (function->unqualifiedName() && !function->unqualifiedName()->isDestructorNameId())) {
                    // 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
                    if (function->argumentCount() == 0) {
                        extraChars += QLatin1Char('<');
                    }
#endif
271
                } else if (!isDereferenced(editor, basePosition) && ! function->isAmbiguous()) {
Leandro Melo's avatar
Leandro Melo committed
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
                    // 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).
                    const QChar characterAtCursor = editor->characterAt(editor->position());
                    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
                    if (!isOverloaded() && ! function->hasArguments() && skipClosingParenthesis) {
                        extraChars += QLatin1Char(')');
                        if (endWithSemicolon) {
                            extraChars += semicolon;
                            m_typedChar = QChar();
                        }
                    } else if (autoParenthesesEnabled) {
                        const QChar lookAhead = editor->characterAt(editor->position() + 1);
                        if (MatchingText::shouldInsertMatchingText(lookAhead)) {
                            extraChars += QLatin1Char(')');
                            --cursorOffset;
                            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;
    }

339 340 341 342
    // 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).
    const int lineEnd = editor->position(TextEditor::ITextEditor::EndOfLine);
    const QString inEditor = editor->textAt(editor->position(), lineEnd - editor->position());
343
    int preserveLength = 0;
344
    if (!inEditor.isEmpty()) {
345
        preserveLength = toInsert.length() - (editor->position() - basePosition);
346
        const int inEditorLength = inEditor.length();
347 348 349 350 351
        while (preserveLength) {
            if (inEditor.startsWith(toInsert.right(preserveLength))
                    && (inEditorLength == preserveLength
                        || (!inEditor.at(preserveLength).isLetterOrNumber()
                            && inEditor.at(preserveLength) != QLatin1Char('_')))) {
Yuchen Deng's avatar
Yuchen Deng committed
352
                break;
353 354
            }
            --preserveLength;
Yuchen Deng's avatar
Yuchen Deng committed
355 356
        }
    }
357

Leandro Melo's avatar
Leandro Melo committed
358 359
    for (int i = 0; i < extraChars.length(); ++i) {
        const QChar a = extraChars.at(i);
360
        const QChar b = editor->characterAt(editor->position() + i + preserveLength);
Leandro Melo's avatar
Leandro Melo committed
361 362 363 364 365 366 367 368 369
        if (a == b)
            ++extraLength;
        else
            break;
    }

    toInsert += extraChars;

    // Insert the remainder of the name
370
    const int length = editor->position() - basePosition + preserveLength + extraLength;
Leandro Melo's avatar
Leandro Melo committed
371 372 373 374 375 376 377 378 379 380 381 382
    editor->setCursorPosition(basePosition);
    editor->replace(length, toInsert);
    if (cursorOffset)
        editor->setCursorPosition(editor->position() + cursorOffset);
}

// --------------------
// CppFunctionHintModel
// --------------------
class CppFunctionHintModel : public TextEditor::IFunctionHintProposalModel
{
public:
383 384
    CppFunctionHintModel(QList<Function *> functionSymbols,
                         const QSharedPointer<TypeOfExpression> &typeOfExp)
Leandro Melo's avatar
Leandro Melo committed
385 386
        : m_functionSymbols(functionSymbols)
        , m_currentArg(-1)
387
        , m_typeOfExpression(typeOfExp)
Leandro Melo's avatar
Leandro Melo committed
388 389 390 391 392 393 394 395 396 397
    {}

    virtual void reset() {}
    virtual int size() const { return m_functionSymbols.size(); }
    virtual QString text(int index) const;
    virtual int activeArgument(const QString &prefix) const;

private:
    QList<Function *> m_functionSymbols;
    mutable int m_currentArg;
398
    QSharedPointer<TypeOfExpression> m_typeOfExpression;
Leandro Melo's avatar
Leandro Melo committed
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 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447
};

QString CppFunctionHintModel::text(int index) const
{
    Overview overview;
    overview.setShowReturnTypes(true);
    overview.setShowArgumentNames(true);
    overview.setMarkedArgument(m_currentArg + 1);
    Function *f = m_functionSymbols.at(index);

    const QString prettyMethod = overview(f->type(), f->name());
    const int begin = overview.markedArgumentBegin();
    const int end = overview.markedArgumentEnd();

    QString hintText;
    hintText += Qt::escape(prettyMethod.left(begin));
    hintText += "<b>";
    hintText += Qt::escape(prettyMethod.mid(begin, end - begin));
    hintText += "</b>";
    hintText += Qt::escape(prettyMethod.mid(end));
    return hintText;
}

int CppFunctionHintModel::activeArgument(const QString &prefix) const
{
    int argnr = 0;
    int parcount = 0;
    SimpleLexer tokenize;
    QList<Token> tokens = tokenize(prefix);
    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;
        else if (! parcount && tk.is(T_COMMA))
            ++argnr;
    }

    if (parcount < 0)
        return -1;

    if (argnr != m_currentArg)
        m_currentArg = argnr;

    return argnr;
}

// ---------------------------
448
// InternalCompletionAssistProvider
Leandro Melo's avatar
Leandro Melo committed
449 450
// ---------------------------

451
IAssistProcessor *InternalCompletionAssistProvider::createProcessor() const
Leandro Melo's avatar
Leandro Melo committed
452
{
453
    return new CppCompletionAssistProcessor;
Leandro Melo's avatar
Leandro Melo committed
454 455
}

456 457
namespace {
class CppCompletionSupportInternal: public CppCompletionSupport
Leandro Melo's avatar
Leandro Melo committed
458
{
459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488
public:
    CppCompletionSupportInternal(TextEditor::ITextEditor *editor)
        : CppCompletionSupport(editor)
    {}

    virtual ~CppCompletionSupportInternal()
    {}

    virtual TextEditor::IAssistInterface *createAssistInterface(ProjectExplorer::Project *project,
                                                                QTextDocument *document,
                                                                int position,
                                                                TextEditor::AssistReason reason) const
    {
        CppModelManagerInterface *modelManager = CppModelManagerInterface::instance();
        QStringList includePaths;
        QStringList frameworkPaths;
        if (project) {
            includePaths = modelManager->projectInfo(project).includePaths();
            frameworkPaths = modelManager->projectInfo(project).frameworkPaths();
        }
        return new CppTools::Internal::CppCompletionAssistInterface(
                    document,
                    position,
                    editor()->document(),
                    reason,
                    modelManager->snapshot(),
                    includePaths,
                    frameworkPaths);
    }
};
Leandro Melo's avatar
Leandro Melo committed
489 490
}

491
CppCompletionSupport *InternalCompletionAssistProvider::completionSupport(ITextEditor *editor)
Leandro Melo's avatar
Leandro Melo committed
492
{
493
    return new CppCompletionSupportInternal(editor);
Leandro Melo's avatar
Leandro Melo committed
494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537
}

// -----------------
// CppAssistProposal
// -----------------
class CppAssistProposal : public TextEditor::GenericProposal
{
public:
    CppAssistProposal(int cursorPos, TextEditor::IGenericProposalModel *model)
        : TextEditor::GenericProposal(cursorPos, model)
        , m_replaceDotForArrow(static_cast<CppAssistProposalModel *>(model)->m_replaceDotForArrow)
    {}

    virtual bool isCorrective() const { return m_replaceDotForArrow; }
    virtual void makeCorrection(BaseTextEditor *editor);

private:
    bool m_replaceDotForArrow;
};

void CppAssistProposal::makeCorrection(BaseTextEditor *editor)
{
    editor->setCursorPosition(basePosition() - 1);
    editor->replace(1, QLatin1String("->"));
    moveBasePosition(1);
}

namespace {

class ConvertToCompletionItem: protected NameVisitor
{
    // The completion item.
    BasicProposalItem *_item;

    // The current symbol.
    Symbol *_symbol;

    // The pretty printer.
    Overview overview;

public:
    ConvertToCompletionItem()
        : _item(0)
        , _symbol(0)
538 539 540 541
    {
        overview.setShowReturnTypes(true);
        overview.setShowArgumentNames(true);
    }
Leandro Melo's avatar
Leandro Melo committed
542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579

    BasicProposalItem *operator()(Symbol *symbol)
    {
        if (! symbol || ! symbol->name() || symbol->name()->isQualifiedNameId())
            return 0;

        BasicProposalItem *previousItem = switchCompletionItem(0);
        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;
    }

    BasicProposalItem *switchCompletionItem(BasicProposalItem *item)
    {
        BasicProposalItem *previousItem = _item;
        _item = item;
        return previousItem;
    }

    BasicProposalItem *newCompletionItem(const Name *name)
    {
        BasicProposalItem *item = new CppAssistProposalItem;
        item->setText(overview.prettyName(name));
        return item;
    }

    virtual void visit(const Identifier *name)
580 581 582 583 584 585
    {
        _item = newCompletionItem(name);
        if (!_symbol->isScope() || _symbol->isFunction()) {
            _item->setDetail(overview.prettyType(_symbol->type(), name));
        }
    }
Leandro Melo's avatar
Leandro Melo committed
586 587 588 589 590 591 592 593 594 595 596

    virtual void visit(const TemplateNameId *name)
    {
        _item = newCompletionItem(name);
        _item->setText(QLatin1String(name->identifier()->chars()));
    }

    virtual void visit(const DestructorNameId *name)
    { _item = newCompletionItem(name); }

    virtual void visit(const OperatorNameId *name)
597 598 599 600
    {
        _item = newCompletionItem(name);
        _item->setDetail(overview.prettyType(_symbol->type(), name));
    }
Leandro Melo's avatar
Leandro Melo committed
601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 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 693 694 695 696 697 698

    virtual void visit(const ConversionNameId *name)
    { _item = newCompletionItem(name); }

    virtual void visit(const QualifiedNameId *name)
    { _item = newCompletionItem(name->name()); }
};

Class *asClassOrTemplateClassType(FullySpecifiedType ty)
{
    if (Class *classTy = ty->asClassType())
        return classTy;
    else if (Template *templ = ty->asTemplateType()) {
        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;
    else if (Template *templ = ty->asTemplateType()) {
        if (Symbol *decl = templ->declaration())
            return decl->asFunction();
    }
    return 0;
}

} // Anonymous

// ----------------------------
// CppCompletionAssistProcessor
// ----------------------------
CppCompletionAssistProcessor::CppCompletionAssistProcessor()
    : m_startPosition(-1)
    , m_objcEnabled(true)
    , m_snippetCollector(CppEditor::Constants::CPP_SNIPPETS_GROUP_ID,
                         QIcon(QLatin1String(":/texteditor/images/snippet.png")))
    , preprocessorCompletions(QStringList()
          << QLatin1String("define")
          << QLatin1String("error")
          << QLatin1String("include")
          << QLatin1String("line")
          << QLatin1String("pragma")
          << QLatin1String("undef")
          << QLatin1String("if")
          << QLatin1String("ifdef")
          << QLatin1String("ifndef")
          << QLatin1String("elif")
          << QLatin1String("else")
          << QLatin1String("endif"))
    , m_model(new CppAssistProposalModel)
    , m_hintProposal(0)
{}

CppCompletionAssistProcessor::~CppCompletionAssistProcessor()
{}

IAssistProposal * CppCompletionAssistProcessor::perform(const IAssistInterface *interface)
{
    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;
}

bool CppCompletionAssistProcessor::accepts() const
{
    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) {
699
            const int column = pos - m_interface->textDocument()->findBlock(start).position();
Leandro Melo's avatar
Leandro Melo committed
700 701 702 703 704 705 706 707
            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);
708
        if (!characterUnderCursor.isLetterOrNumber() && characterUnderCursor != QLatin1Char('_')) {
709
            const int startOfName = findStartOfName(pos);
710
            if (pos - startOfName >= 3) {
Leandro Melo's avatar
Leandro Melo committed
711
                const QChar firstCharacter = m_interface->characterAt(startOfName);
712 713
                if (firstCharacter.isLetter() || firstCharacter == QLatin1Char('_')) {
                    // Finally check that we're not inside a comment or string (code copied from startOfOperator)
714
                    QTextCursor tc(m_interface->textDocument());
715 716 717 718 719 720 721 722 723 724
                    tc.setPosition(pos);

                    SimpleLexer tokenize;
                    tokenize.setQtMocRunEnabled(true);
                    tokenize.setObjCEnabled(true);
                    tokenize.setSkipComments(false);
                    const QList<Token> &tokens = tokenize(tc.block().text(), BackwardsScanner::previousBlockState(tc.block()));
                    const int tokenIdx = SimpleLexer::tokenBefore(tokens, qMax(0, tc.positionInBlock() - 1));
                    const Token tk = (tokenIdx == -1) ? Token() : tokens.at(tokenIdx);

725
                    if (!tk.isComment() && !tk.isLiteral()) {
726
                        return true;
727 728 729 730 731 732 733 734 735 736 737 738 739 740
                    } 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 =
                                line.midRef(idToken.begin(), idToken.end() - idToken.begin());
                        if (identifier == QLatin1String("include")
                                || identifier == QLatin1String("include_next")
                                || (m_objcEnabled && identifier == QLatin1String("import"))) {
                            return true;
                        }
                    }
741 742
                }
            }
743
        }
744
    }
con's avatar
con committed
745 746 747 748

    return false;
}

Leandro Melo's avatar
Leandro Melo committed
749
IAssistProposal *CppCompletionAssistProcessor::createContentProposal()
con's avatar
con committed
750
{
Leandro Melo's avatar
Leandro Melo committed
751 752 753 754 755 756 757 758 759 760 761 762 763 764
    // Duplicates are kept only if they are snippets.
    QSet<QString> processed;
    QList<BasicProposalItem *>::iterator it = m_completions.begin();
    while (it != m_completions.end()) {
        CppAssistProposalItem *item = static_cast<CppAssistProposalItem *>(*it);
        if (!processed.contains(item->text()) || item->data().canConvert<QString>()) {
            ++it;
            if (!item->data().canConvert<QString>()) {
                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();
765
                        }
Leandro Melo's avatar
Leandro Melo committed
766
                    }
767 768
                }
            }
Leandro Melo's avatar
Leandro Melo committed
769
        } else {
770
            delete *it;
Leandro Melo's avatar
Leandro Melo committed
771
            it = m_completions.erase(it);
772
        }
Roberto Raggi's avatar
Roberto Raggi committed
773
    }
774

Leandro Melo's avatar
Leandro Melo committed
775 776 777
    m_model->loadContent(m_completions);
    return new CppAssistProposal(m_startPosition, m_model.take());
}
778

Leandro Melo's avatar
Leandro Melo committed
779 780 781
IAssistProposal *CppCompletionAssistProcessor::createHintProposal(
    QList<CPlusPlus::Function *> functionSymbols) const
{
782 783
    IFunctionHintProposalModel *model =
            new CppFunctionHintModel(functionSymbols, m_model->m_typeOfExpression);
Leandro Melo's avatar
Leandro Melo committed
784 785
    IAssistProposal *proposal = new FunctionHintProposal(m_startPosition, model);
    return proposal;
786 787
}

Leandro Melo's avatar
Leandro Melo committed
788 789 790
int CppCompletionAssistProcessor::startOfOperator(int pos,
                                                  unsigned *kind,
                                                  bool wantFunctionCall) const
791
{
Leandro Melo's avatar
Leandro Melo committed
792 793 794 795
    const QChar ch  = pos > -1 ? m_interface->characterAt(pos - 1) : QChar();
    const QChar ch2 = pos >  0 ? m_interface->characterAt(pos - 2) : QChar();
    const QChar ch3 = pos >  1 ? m_interface->characterAt(pos - 3) : QChar();

796
    int start = pos - CppCompletionAssistProvider::activationSequenceChar(ch, ch2, ch3, kind, wantFunctionCall);
Leandro Melo's avatar
Leandro Melo committed
797
    if (start != pos) {
798
        QTextCursor tc(m_interface->textDocument());
Leandro Melo's avatar
Leandro Melo committed
799 800 801 802 803 804 805 806 807 808 809 810
        tc.setPosition(pos);

        // 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 = pos;
            }
        }
811

Leandro Melo's avatar
Leandro Melo committed
812 813 814 815 816 817 818
        if (*kind == T_COMMA) {
            ExpressionUnderCursor expressionUnderCursor;
            if (expressionUnderCursor.startOfFunctionCall(tc) == -1) {
                *kind = T_EOF_SYMBOL;
                start = pos;
            }
        }
819

Leandro Melo's avatar
Leandro Melo committed
820 821 822 823 824 825 826
        SimpleLexer tokenize;
        tokenize.setQtMocRunEnabled(true);
        tokenize.setObjCEnabled(true);
        tokenize.setSkipComments(false);
        const QList<Token> &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);
827

Leandro Melo's avatar
Leandro Melo committed
828 829 830 831 832 833 834 835
        if (*kind == T_DOXY_COMMENT && !(tk.is(T_DOXY_COMMENT) || tk.is(T_CPP_DOXY_COMMENT))) {
            *kind = T_EOF_SYMBOL;
            start = pos;
        }
        // Don't complete in comments or strings, but still check for include completion
        else if (tk.is(T_COMMENT) || tk.is(T_CPP_COMMENT) ||
                 (tk.isLiteral() && (*kind != T_STRING_LITERAL
                                     && *kind != T_ANGLE_STRING_LITERAL
836 837
                                     && *kind != T_SLASH
                                     && *kind != T_DOT))) {
Leandro Melo's avatar
Leandro Melo committed
838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863
            *kind = T_EOF_SYMBOL;
            start = pos;
        }
        // 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 = pos;
        }
        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 = pos;
                }
            }
        }
        // Check for include preprocessor directive
864 865
        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)))) {
Leandro Melo's avatar
Leandro Melo committed
866 867 868 869 870 871 872 873 874 875 876
            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.begin(),
                                                              directiveToken.length());
                    if (directive == QLatin1String("include") ||
                            directive == QLatin1String("include_next") ||
                            directive == QLatin1String("import")) {
                        include = true;
877 878 879
                    }
                }
            }
Leandro Melo's avatar
Leandro Melo committed
880 881 882 883

            if (!include) {
                *kind = T_EOF_SYMBOL;
                start = pos;
884 885 886 887 888 889 890 891
            } else {
                if (*kind == T_DOT) {
                    start = findStartOfName(start);
                    const QChar ch4  = start > -1 ? m_interface->characterAt(start - 1) : QChar();
                    const QChar ch5 = start >  0 ? m_interface->characterAt(start - 2) : QChar();
                    const QChar ch6 = start >  1 ? m_interface->characterAt(start - 3) : QChar();
                    start = start - CppCompletionAssistProvider::activationSequenceChar(ch4, ch5, ch6, kind, wantFunctionCall);
                }
Leandro Melo's avatar
Leandro Melo committed
892
            }
893 894
        }
    }
Leandro Melo's avatar
Leandro Melo committed
895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910

    return start;
}

int CppCompletionAssistProcessor::findStartOfName(int pos) const
{
    if (pos == -1)
        pos = m_interface->position();
    QChar chr;

    // Skip to the start of a name
    do {
        chr = m_interface->characterAt(--pos);
    } while (chr.isLetterOrNumber() || chr == QLatin1Char('_'));

    return pos + 1;
911 912
}

Leandro Melo's avatar
Leandro Melo committed
913
int CppCompletionAssistProcessor::startCompletionHelper()
914
{
Leandro Melo's avatar
Leandro Melo committed
915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933
    if (m_objcEnabled) {
        if (tryObjCCompletion())
            return m_startPosition;
    }

    const int startOfName = findStartOfName();
    m_startPosition = startOfName;
    m_model->m_completionOperator = T_EOF_SYMBOL;

    int endOfOperator = m_startPosition;

    // 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);

934 935
    const Core::IDocument *document = m_interface->document();
    QString fileName = document->fileName();
Leandro Melo's avatar
Leandro Melo committed
936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954

    if (m_model->m_completionOperator == T_DOXY_COMMENT) {
        for (int i = 1; i < T_DOXY_LAST_TAG; ++i)
            addCompletionItem(QString::fromLatin1(doxygenTagSpell(i)), m_icons.keywordIcon());
        return m_startPosition;
    }

    // Pre-processor completion
    if (m_model->m_completionOperator == T_POUND) {
        completePreprocessor();
        m_startPosition = startOfName;
        return m_startPosition;
    }

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

955
        QTextCursor c(m_interface->textDocument());
Leandro Melo's avatar
Leandro Melo committed
956 957
        c.setPosition(endOfExpression);
        if (completeInclude(c))
958
            m_startPosition = endOfExpression + 1;
Leandro Melo's avatar
Leandro Melo committed
959 960 961 962
        return m_startPosition;
    }

    ExpressionUnderCursor expressionUnderCursor;
963
    QTextCursor tc(m_interface->textDocument());
Leandro Melo's avatar
Leandro Melo committed
964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006

    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;
        m_startPosition = start + 1;
        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();

        if (m_model->m_completionOperator == T_LPAREN) {
            if (expression.endsWith(QLatin1String("SIGNAL")))
                m_model->m_completionOperator = T_SIGNAL;

            else if (expression.endsWith(QLatin1String("SLOT")))
                m_model->m_completionOperator = T_SLOT;

            else if (m_interface->position() != endOfOperator) {
                // 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;
                m_startPosition = startOfName;
                startOfExpression = m_interface->position();
            }
        }
    } else if (expression.isEmpty()) {
        while (startOfExpression > 0 && m_interface->characterAt(startOfExpression).isSpace())
            --startOfExpression;
    }

    int line = 0, column = 0;
1007
    Convenience::convertPosition(m_interface->textDocument(), startOfExpression, &line, &column);
Leandro Melo's avatar
Leandro Melo committed
1008 1009
    return startCompletionInternal(fileName, line, column, expression, endOfExpression);
}
1010

Leandro Melo's avatar
Leandro Melo committed
1011 1012 1013 1014
bool CppCompletionAssistProcessor::tryObjCCompletion()
{
    int end = m_interface->position();
    while (m_interface->characterAt(end).isSpace())
1015
        ++end;
Leandro Melo's avatar
Leandro Melo committed
1016
    if (m_interface->characterAt(end) != QLatin1Char(']'))
1017 1018
        return false;

1019
    QTextCursor tc(m_interface->textDocument());
1020 1021 1022 1023 1024 1025 1026 1027 1028 1029
    tc.setPosition(end);
    BackwardsScanner tokens(tc);
    if (tokens[tokens.startToken() - 1].isNot(T_RBRACKET))
        return false;

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

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

1032
    Document::Ptr thisDocument = m_interface->snapshot().document(m_interface->document()->fileName());
1033 1034 1035
    if (! thisDocument)
        return false;

1036 1037
    m_model->m_typeOfExpression->init(thisDocument, m_interface->snapshot());

1038
    int line = 0, column = 0;
1039
    Convenience::convertPosition(m_interface->textDocument(), m_interface->position(), &line, &column);
1040 1041 1042 1043
    Scope *scope = thisDocument->scopeAt(line, column);
    if (!scope)
        return false;

1044
    const QList<LookupItem> items = (*m_model->m_typeOfExpression)(expr.toUtf8(), scope);
1045
    LookupContext lookupContext(thisDocument, m_interface->snapshot());
1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066

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

            if (NamedType *namedTy = ty->asNamedType()) {
                ClassOrNamespace *binding = lookupContext.lookupType(namedTy->name(), item.scope());
                completeObjCMsgSend(binding, false);
            }
        } else {
            if (ObjCClass *clazz = ty->asObjCClassType()) {
                ClassOrNamespace *binding = lookupContext.lookupType(clazz->name(), item.scope());
                completeObjCMsgSend(binding, true);
            }
        }
    }

    if (m_completions.isEmpty())
        return false;

Leandro Melo's avatar
Leandro Melo committed
1067
    m_startPosition = m_interface->position();
1068 1069 1070
    return true;
}

Leandro Melo's avatar
Leandro Melo committed
1071 1072 1073 1074
void CppCompletionAssistProcessor::addCompletionItem(const QString &text,
                                                     const QIcon &icon,
                                                     int order,
                                                     const QVariant &data)
1075
{
Leandro Melo's avatar
Leandro Melo committed
1076 1077 1078 1079 1080 1081 1082
    BasicProposalItem *item = new CppAssistProposalItem;
    item->setText(text);
    item->setIcon(icon);
    item->setOrder(order);
    item->setData(data);
    m_completions.append(item);
}
1083

Leandro Melo's avatar
Leandro Melo committed
1084 1085 1086 1087 1088 1089 1090
void CppCompletionAssistProcessor::addCompletionItem(CPlusPlus::Symbol *symbol)
{
    ConvertToCompletionItem toCompletionItem;
    BasicProposalItem *item = toCompletionItem(symbol);
    if (item) {
        item->setIcon(m_icons.iconForSymbol(symbol));
        m_completions.append(item);
1091
    }
Leandro Melo's avatar
Leandro Melo committed
1092
}
1093

Leandro Melo's avatar
Leandro Melo committed
1094 1095 1096 1097 1098 1099 1100 1101
void CppCompletionAssistProcessor::completeObjCMsgSend(CPlusPlus::ClassOrNamespace *binding,
                                                       bool staticClassAccess)
{
    QList<Scope*> memberScopes;
    foreach (Symbol *s, binding->symbols()) {
        if (ObjCClass *c = s->asObjCClass())
            memberScopes.append(c);
    }
con's avatar
con committed
1102

Leandro Melo's avatar
Leandro Melo committed
1103 1104 1105
    foreach (Scope *scope, memberScopes) {
        for (unsigned i = 0; i < scope->memberCount(); ++i) {
            Symbol *symbol = scope->memberAt(i);
con's avatar
con committed
1106

Leandro Melo's avatar
Leandro Melo committed
1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131
            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);
                            text += selectorName->nameAt(i)->identifier()->chars();
                            text += QLatin1Char(':');
                            text += TextEditor::Snippet::kVariableDelimiter;
                            text += QLatin1Char('(');
                            text += oo(arg->type());
                            text += QLatin1Char(')');
                            text += oo(arg->name());
                            text += TextEditor::Snippet::kVariableDelimiter;
                        }
                    } else {
                        text = selectorName->identifier()->chars();
                    }
                    data = text;
con's avatar
con committed
1132

Leandro Melo's avatar
Leandro Melo committed
1133 1134 1135 1136
                    if (!text.isEmpty())
                        addCompletionItem(text, QIcon(), 0, QVariant::fromValue(data));
                }
            }
1137 1138
        }
    }
Leandro Melo's avatar
Leandro Melo committed
1139
}
1140

Leandro Melo's avatar
Leandro Melo committed
1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156
bool CppCompletionAssistProcessor::completeInclude(const QTextCursor &cursor)
{
    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);
1157 1158
    }

Leandro Melo's avatar
Leandro Melo committed
1159 1160
    // Make completion for all relevant includes
    QStringList includePaths = m_interface->includePaths();
1161
    const QString &currentFilePath = QFileInfo(m_interface->document()->fileName()).path();
Leandro Melo's avatar
Leandro Melo committed
1162 1163 1164
    if (!includePaths.contains(currentFilePath))
        includePaths.append(currentFilePath);

1165
    const Core::MimeType mimeType =
hjk's avatar
hjk committed
1166
            Core::ICore::mimeDatabase()->findByType(QLatin1String("text/x-c++hdr"));
1167 1168
    const QStringList suffixes = mimeType.suffixes();

Leandro Melo's avatar
Leandro Melo committed
1169 1170 1171 1172 1173 1174
    foreach (const QString &includePath, includePaths) {
        QString realPath = includePath;
        if (!directoryPrefix.isEmpty()) {
            realPath += QLatin1Char('/');
            realPath += directoryPrefix;
        }
1175
        completeInclude(realPath, suffixes);
1176 1177
    }

Leandro Melo's avatar
Leandro Melo committed
1178 1179 1180 1181 1182 1183
    foreach (const QString &frameworkPath, m_interface->frameworkPaths()) {
        QString realPath = frameworkPath;
        if (!directoryPrefix.isEmpty()) {
            realPath += QLatin1Char('/');
            realPath += directoryPrefix;
            realPath += QLatin1String(".framework/Headers");
1184
        }
1185
        completeInclude(realPath, suffixes);
1186 1187
    }

Leandro Melo's avatar
Leandro Melo committed
1188 1189
    return !m_completions.isEmpty();
}
1190

1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207
void CppCompletionAssistProcessor::completeInclude(const QString &realPath,
                                                   const QStringList &suffixes)
{
    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('/');
            addCompletionItem(text, m_icons.keywordIcon());
        }
    }
}

Leandro Melo's avatar
Leandro Melo committed
1208 1209 1210 1211
void CppCompletionAssistProcessor::completePreprocessor()
{
    foreach (const QString &preprocessorCompletion, preprocessorCompletions)
        addCompletionItem(preprocessorCompletion);
1212

Leandro Melo's avatar
Leandro Melo committed
1213 1214 1215
    if (objcKeywordsWanted())
        addCompletionItem(QLatin1String("import"));
}
1216

Leandro Melo's avatar
Leandro Melo committed
1217 1218 1219 1220
bool CppCompletionAssistProcessor::objcKeywordsWanted() const
{
    if (!m_objcEnabled)
        return false;
1221

1222 1223
    const Core::IDocument *document = m_interface->document();
    QString fileName = document->fileName();
con's avatar
con committed
1224

hjk's avatar
hjk committed
1225
    const Core::MimeDatabase *mdb = Core::ICore::mimeDatabase();
Leandro Melo's avatar
Leandro Melo committed
1226
    return mdb->findByFile(fileName).type() == CppTools::Constants::OBJECTIVE_CPP_SOURCE_MIMETYPE;
1227
}
con's avatar
con committed
1228

Leandro Melo's avatar
Leandro Melo committed
1229 1230 1231 1232
int CppCompletionAssistProcessor::startCompletionInternal(const QString fileName,
                                                          unsigned line, unsigned column,
                                                          const QString &expr,
                                                          int endOfExpression)
1233 1234
{
    QString expression = expr.trimmed();
1235

1236
    Document::Ptr thisDocument = m_interface->snapshot().document(fileName);
1237 1238
    if (! thisDocument)
        return -1;
con's avatar
con committed
1239

1240
    m_model->m_typeOfExpression->init(thisDocument, m_interface->snapshot());
1241 1242

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

1245
    if (expression.isEmpty()) {
Leandro Melo's avatar
Leandro Melo committed
1246
        if (m_model->m_completionOperator == T_EOF_SYMBOL || m_model->m_completionOperator == T_COLON_COLON) {
1247
            (void) (*m_model->m_typeOfExpression)(expression.toUtf8(), scope);
1248 1249 1250 1251 1252
            globalCompletion(scope);
            if (m_completions.isEmpty())
                return -1;
            return m_startPosition;
        }
con's avatar
con committed
1253

Leandro Melo's avatar
Leandro Melo committed
1254
        else if (m_model->m_completionOperator == T_SIGNAL || m_model->m_completionOperator == T_SLOT) {
con's avatar
con committed
1255 1256 1257
            // Apply signal/slot completion on 'this'
            expression = QLatin1String("this");
        }
1258
    }
con's avatar
con committed
1259

1260
    QByteArray utf8Exp = expression.toUtf8();
1261
    QList<LookupItem> results =
1262
            (*m_model->m_typeOfExpression)(utf8Exp, scope, TypeOfExpression::Preprocess);
1263

1264
    if (results.isEmpty()) {
Leandro Melo's avatar
Leandro Melo committed
1265
        if (m_model->m_completionOperator == T_SIGNAL || m_model->m_completionOperator == T_SLOT) {
1266 1267
            if (! (expression.isEmpty() || expression == QLatin1String("this"))) {
                expression = QLatin1String("this");
1268
                results = (*m_model->m_typeOfExpression)(utf8Exp, scope);
1269
            }
Roberto Raggi's avatar
Cleanup  
Roberto Raggi committed
1270

1271 1272
            if (results.isEmpty())
                return -1;
Roberto Raggi's avatar
Cleanup  
Roberto Raggi committed
1273

Leandro Melo's avatar
Leandro Melo committed
1274
        } else if (m_model->m_completionOperator == T_LPAREN) {
1275 1276
            // Find the expression that precedes the current name
            int index = endOfExpression;
Leandro Melo's avatar
Leandro Melo committed
1277
            while (m_interface->characterAt(index - 1).isSpa