cppcompletionassist.cpp 69.8 KB
Newer Older
hjk's avatar
hjk committed
1
/****************************************************************************
con's avatar
con committed
2
**
3
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
hjk's avatar
hjk committed
4
** 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

Leandro Melo's avatar
Leandro Melo committed
30 31
#include "cppcompletionassist.h"
#include "cppmodelmanager.h"
32
#include "cpptoolsconstants.h"
33
#include "cpptoolseditorsupport.h"
34
#include "cppdoxygen.h"
con's avatar
con committed
35 36

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

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 57 58 59
#include <QLatin1String>
#include <QTextCursor>
#include <QTextDocument>
#include <QIcon>
60

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

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

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

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

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

Leandro Melo's avatar
Leandro Melo committed
88 89 90
    virtual bool prematurelyApplies(const QChar &c) const;
    virtual void applyContextualContent(TextEditor::BaseTextEditor *editor,
                                        int basePosition) const;
91

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

Leandro Melo's avatar
Leandro Melo committed
98 99 100
private:
    bool m_isOverloaded;
    mutable QChar m_typedChar;
101
    unsigned m_completionOperator;
102
    QSharedPointer<TypeOfExpression> m_typeOfExpression;
Leandro Melo's avatar
Leandro Melo committed
103
};
104

Leandro Melo's avatar
Leandro Melo committed
105 106
} // Internal
} // CppTools
107

Leandro Melo's avatar
Leandro Melo committed
108
Q_DECLARE_METATYPE(CppTools::Internal::CompleteFunctionDeclaration)
109

110 111 112 113 114 115 116 117
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
118 119 120 121 122 123 124
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);
125
        cppItem->keepTypeOfExpression(m_typeOfExpression);
Leandro Melo's avatar
Leandro Melo committed
126 127 128
    }
    return item;
}
129

Leandro Melo's avatar
Leandro Melo committed
130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161
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;
}

162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181
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
182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213
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();

214
        const CompletionSettings &completionSettings = TextEditorSettings::completionSettings();
Leandro Melo's avatar
Leandro Melo committed
215 216 217 218 219 220
        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.
221 222 223
                if (!function->hasReturnType()
                    && (function->unqualifiedName()
                    && !function->unqualifiedName()->isDestructorNameId())) {
Leandro Melo's avatar
Leandro Melo committed
224 225 226 227 228 229
                    // 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
230
                    if (function->argumentCount() == 0)
Leandro Melo's avatar
Leandro Melo committed
231 232
                        extraChars += QLatin1Char('<');
#endif
233
                } else if (!isDereferenced(editor, basePosition) && !function->isAmbiguous()) {
Leandro Melo's avatar
Leandro Melo committed
234 235 236 237 238 239 240 241 242 243 244 245 246
                    // 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).
247
                    const QChar characterAtCursor = editor->textDocument()->characterAt(editor->position());
Leandro Melo's avatar
Leandro Melo committed
248 249 250 251 252 253 254 255 256 257
                    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
258
                    if (!isOverloaded() && !function->hasArguments() && skipClosingParenthesis) {
Leandro Melo's avatar
Leandro Melo committed
259 260 261 262 263 264
                        extraChars += QLatin1Char(')');
                        if (endWithSemicolon) {
                            extraChars += semicolon;
                            m_typedChar = QChar();
                        }
                    } else if (autoParenthesesEnabled) {
265
                        const QChar lookAhead = editor->textDocument()->characterAt(editor->position() + 1);
Leandro Melo's avatar
Leandro Melo committed
266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300
                        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;
    }

301 302 303
    // 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);
304 305
    const QString inEditor = editor->textDocument()->textAt(editor->position(),
                                                            lineEnd - editor->position());
306
    int preserveLength = 0;
307
    if (!inEditor.isEmpty()) {
308
        preserveLength = toInsert.length() - (editor->position() - basePosition);
309
        const int inEditorLength = inEditor.length();
310
        while (preserveLength > 0) {
311 312 313 314
            if (inEditor.startsWith(toInsert.right(preserveLength))
                    && (inEditorLength == preserveLength
                        || (!inEditor.at(preserveLength).isLetterOrNumber()
                            && inEditor.at(preserveLength) != QLatin1Char('_')))) {
Yuchen Deng's avatar
Yuchen Deng committed
315
                break;
316 317
            }
            --preserveLength;
Yuchen Deng's avatar
Yuchen Deng committed
318 319
        }
    }
320

Leandro Melo's avatar
Leandro Melo committed
321 322
    for (int i = 0; i < extraChars.length(); ++i) {
        const QChar a = extraChars.at(i);
323
        const QChar b = editor->textDocument()->characterAt(editor->position() + i + preserveLength);
Leandro Melo's avatar
Leandro Melo committed
324 325 326 327 328 329 330 331 332
        if (a == b)
            ++extraLength;
        else
            break;
    }

    toInsert += extraChars;

    // Insert the remainder of the name
333
    const int length = editor->position() - basePosition + preserveLength + extraLength;
Leandro Melo's avatar
Leandro Melo committed
334 335 336 337 338 339 340 341 342 343 344 345
    editor->setCursorPosition(basePosition);
    editor->replace(length, toInsert);
    if (cursorOffset)
        editor->setCursorPosition(editor->position() + cursorOffset);
}

// --------------------
// CppFunctionHintModel
// --------------------
class CppFunctionHintModel : public TextEditor::IFunctionHintProposalModel
{
public:
346 347
    CppFunctionHintModel(QList<Function *> functionSymbols,
                         const QSharedPointer<TypeOfExpression> &typeOfExp)
Leandro Melo's avatar
Leandro Melo committed
348 349
        : m_functionSymbols(functionSymbols)
        , m_currentArg(-1)
350
        , m_typeOfExpression(typeOfExp)
Leandro Melo's avatar
Leandro Melo committed
351 352 353 354 355 356 357 358 359 360
    {}

    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;
361
    QSharedPointer<TypeOfExpression> m_typeOfExpression;
Leandro Melo's avatar
Leandro Melo committed
362 363 364 365 366
};

QString CppFunctionHintModel::text(int index) const
{
    Overview overview;
367 368 369
    overview.showReturnTypes = true;
    overview.showArgumentNames = true;
    overview.markedArgument = m_currentArg + 1;
Leandro Melo's avatar
Leandro Melo committed
370 371
    Function *f = m_functionSymbols.at(index);

372 373 374
    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
375 376 377

    QString hintText;
    hintText += Qt::escape(prettyMethod.left(begin));
378
    hintText += QLatin1String("<b>");
Leandro Melo's avatar
Leandro Melo committed
379
    hintText += Qt::escape(prettyMethod.mid(begin, end - begin));
380
    hintText += QLatin1String("</b>");
Leandro Melo's avatar
Leandro Melo committed
381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396
    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;
397
        else if (!parcount && tk.is(T_COMMA))
Leandro Melo's avatar
Leandro Melo committed
398 399 400 401 402 403 404 405 406 407 408 409 410
            ++argnr;
    }

    if (parcount < 0)
        return -1;

    if (argnr != m_currentArg)
        m_currentArg = argnr;

    return argnr;
}

// ---------------------------
411
// InternalCompletionAssistProvider
Leandro Melo's avatar
Leandro Melo committed
412 413
// ---------------------------

414
IAssistProcessor *InternalCompletionAssistProvider::createProcessor() const
Leandro Melo's avatar
Leandro Melo committed
415
{
416
    return new CppCompletionAssistProcessor;
Leandro Melo's avatar
Leandro Melo committed
417 418
}

419
TextEditor::IAssistInterface *InternalCompletionAssistProvider::createAssistInterface(
420
        ProjectExplorer::Project *project, BaseTextEditor *editor, QTextDocument *document,
421
        int position, TextEditor::AssistReason reason) const
Leandro Melo's avatar
Leandro Melo committed
422
{
423 424
    Q_UNUSED(project);

425
    CppModelManagerInterface *modelManager = CppModelManagerInterface::instance();
426 427 428 429 430 431 432 433 434 435 436 437 438

    if (CppEditorSupport *supp = modelManager->cppEditorSupport(editor)) {
        if (QSharedPointer<SnapshotUpdater> updater = supp->snapshotUpdater()) {
            updater->update(modelManager->workingCopy());
            return new CppTools::Internal::CppCompletionAssistInterface(
                        document,
                        position,
                        editor->document()->filePath(),
                        reason,
                        updater->snapshot(),
                        updater->includePaths(),
                        updater->frameworkPaths());
        }
439
    }
440 441

    return 0;
Leandro Melo's avatar
Leandro Melo committed
442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463
}

// -----------------
// 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)
{
464
    const int oldPosition = editor->position();
Leandro Melo's avatar
Leandro Melo committed
465 466
    editor->setCursorPosition(basePosition() - 1);
    editor->replace(1, QLatin1String("->"));
467
    editor->setCursorPosition(oldPosition + 1);
Leandro Melo's avatar
Leandro Melo committed
468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487
    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)
488
    {
489 490
        overview.showReturnTypes = true;
        overview.showArgumentNames = true;
491
    }
Leandro Melo's avatar
Leandro Melo committed
492 493 494

    BasicProposalItem *operator()(Symbol *symbol)
    {
495
        //using declaration can be qualified
496 497
        if (!symbol || !symbol->name() || (symbol->name()->isQualifiedNameId()
                                           && !symbol->asUsingDeclaration()))
Leandro Melo's avatar
Leandro Melo committed
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
            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)
532 533
    {
        _item = newCompletionItem(name);
534
        if (!_symbol->isScope() || _symbol->isFunction())
535 536
            _item->setDetail(overview.prettyType(_symbol->type(), name));
    }
Leandro Melo's avatar
Leandro Melo committed
537 538 539 540 541 542 543 544 545 546 547

    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)
548 549 550 551
    {
        _item = newCompletionItem(name);
        _item->setDetail(overview.prettyType(_symbol->type(), name));
    }
Leandro Melo's avatar
Leandro Melo committed
552 553 554 555 556 557 558 559 560 561 562 563

    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;
564
    if (Template *templ = ty->asTemplateType()) {
Leandro Melo's avatar
Leandro Melo committed
565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586
        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;
587
    if (Template *templ = ty->asTemplateType()) {
Leandro Melo's avatar
Leandro Melo committed
588 589 590 591 592 593
        if (Symbol *decl = templ->declaration())
            return decl->asFunction();
    }
    return 0;
}

594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611
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()) {
                if (name->isEqualTo(&qPrivateSignalIdentifier))
                    return true;
            }
        }
    }
    return false;
}

Leandro Melo's avatar
Leandro Melo committed
612 613 614 615 616 617 618
} // Anonymous

// ----------------------------
// CppCompletionAssistProcessor
// ----------------------------
CppCompletionAssistProcessor::CppCompletionAssistProcessor()
    : m_startPosition(-1)
619
    , m_snippetCollector(QLatin1String(CppEditor::Constants::CPP_SNIPPETS_GROUP_ID),
Leandro Melo's avatar
Leandro Melo committed
620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635
                         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)
636 637 638 639 640 641 642
{
    // FIXME: C++11?
    m_languageFeatures.objCEnabled = true;
    m_languageFeatures.qtEnabled = true;
    m_languageFeatures.qtKeywordsEnabled = true;
    m_languageFeatures.qtMocRunEnabled = true;
}
Leandro Melo's avatar
Leandro Melo committed
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

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) {
673
            const int column = pos - m_interface->textDocument()->findBlock(start).position();
Leandro Melo's avatar
Leandro Melo committed
674 675 676 677 678 679 680 681
            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);
682
        if (!characterUnderCursor.isLetterOrNumber() && characterUnderCursor != QLatin1Char('_')) {
683
            const int startOfName = findStartOfName(pos);
684
            if (pos - startOfName >= 3) {
Leandro Melo's avatar
Leandro Melo committed
685
                const QChar firstCharacter = m_interface->characterAt(startOfName);
686 687
                if (firstCharacter.isLetter() || firstCharacter == QLatin1Char('_')) {
                    // Finally check that we're not inside a comment or string (code copied from startOfOperator)
688
                    QTextCursor tc(m_interface->textDocument());
689 690
                    tc.setPosition(pos);

691 692 693 694 695 696
                    LanguageFeatures features;
                    features.qtEnabled = true;
                    features.qtMocRunEnabled = true;
                    features.qtKeywordsEnabled = true;
                    features.objCEnabled = true;

697
                    SimpleLexer tokenize;
698
                    tokenize.setLanguageFeatures(features);
699
                    tokenize.setSkipComments(false);
700

701 702 703 704
                    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);

705
                    if (!tk.isComment() && !tk.isLiteral()) {
706
                        return true;
707 708 709 710 711 712 713 714 715 716
                    } 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")
717
                                || (m_languageFeatures.objCEnabled && identifier == QLatin1String("import"))) {
718 719 720
                            return true;
                        }
                    }
721 722
                }
            }
723
        }
724
    }
con's avatar
con committed
725 726 727 728

    return false;
}

Leandro Melo's avatar
Leandro Melo committed
729
IAssistProposal *CppCompletionAssistProcessor::createContentProposal()
con's avatar
con committed
730
{
Leandro Melo's avatar
Leandro Melo committed
731 732 733 734 735 736 737 738 739 740 741 742 743 744
    // 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();
745
                        }
Leandro Melo's avatar
Leandro Melo committed
746
                    }
747 748
                }
            }
Leandro Melo's avatar
Leandro Melo committed
749
        } else {
750
            delete *it;
Leandro Melo's avatar
Leandro Melo committed
751
            it = m_completions.erase(it);
752
        }
Roberto Raggi's avatar
Roberto Raggi committed
753
    }
754

Leandro Melo's avatar
Leandro Melo committed
755 756 757
    m_model->loadContent(m_completions);
    return new CppAssistProposal(m_startPosition, m_model.take());
}
758

Leandro Melo's avatar
Leandro Melo committed
759 760 761
IAssistProposal *CppCompletionAssistProcessor::createHintProposal(
    QList<CPlusPlus::Function *> functionSymbols) const
{
762 763
    IFunctionHintProposalModel *model =
            new CppFunctionHintModel(functionSymbols, m_model->m_typeOfExpression);
Leandro Melo's avatar
Leandro Melo committed
764 765
    IAssistProposal *proposal = new FunctionHintProposal(m_startPosition, model);
    return proposal;
766 767
}

Leandro Melo's avatar
Leandro Melo committed
768 769 770
int CppCompletionAssistProcessor::startOfOperator(int pos,
                                                  unsigned *kind,
                                                  bool wantFunctionCall) const
771
{
Leandro Melo's avatar
Leandro Melo committed
772 773 774 775
    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();

776
    int start = pos - CppCompletionAssistProvider::activationSequenceChar(ch, ch2, ch3, kind, wantFunctionCall);
Leandro Melo's avatar
Leandro Melo committed
777
    if (start != pos) {
778
        QTextCursor tc(m_interface->textDocument());
Leandro Melo's avatar
Leandro Melo committed
779 780 781 782 783 784 785 786 787 788 789 790
        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;
            }
        }
791

Leandro Melo's avatar
Leandro Melo committed
792 793 794 795 796 797 798
        if (*kind == T_COMMA) {
            ExpressionUnderCursor expressionUnderCursor;
            if (expressionUnderCursor.startOfFunctionCall(tc) == -1) {
                *kind = T_EOF_SYMBOL;
                start = pos;
            }
        }
799

Leandro Melo's avatar
Leandro Melo committed
800
        SimpleLexer tokenize;
801
        tokenize.setLanguageFeatures(m_languageFeatures);
Leandro Melo's avatar
Leandro Melo committed
802 803 804 805
        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);
806

Leandro Melo's avatar
Leandro Melo committed
807 808 809 810 811 812 813 814
        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
815 816
                                     && *kind != T_SLASH
                                     && *kind != T_DOT))) {
Leandro Melo's avatar
Leandro Melo committed
817 818 819
            *kind = T_EOF_SYMBOL;
            start = pos;
        // Include completion: can be triggered by slash, but only in a string
820
        } else if (*kind == T_SLASH && (tk.isNot(T_STRING_LITERAL) && tk.isNot(T_ANGLE_STRING_LITERAL))) {
Leandro Melo's avatar
Leandro Melo committed
821 822
            *kind = T_EOF_SYMBOL;
            start = pos;
823
        } else if (*kind == T_LPAREN) {
Leandro Melo's avatar
Leandro Melo committed
824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840
            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
841 842
        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
843 844 845 846 847 848 849 850 851 852 853
            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;
854 855 856
                    }
                }
            }
Leandro Melo's avatar
Leandro Melo committed
857 858 859 860

            if (!include) {
                *kind = T_EOF_SYMBOL;
                start = pos;
861 862 863 864 865 866 867 868
            } 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
869
            }
870 871
        }
    }
Leandro Melo's avatar
Leandro Melo committed
872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887

    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;
888 889
}

Leandro Melo's avatar
Leandro Melo committed
890
int CppCompletionAssistProcessor::startCompletionHelper()
891
{
892
    if (m_languageFeatures.objCEnabled) {
Leandro Melo's avatar
Leandro Melo committed
893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928
        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);

    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) {

929
        QTextCursor c(m_interface->textDocument());
Leandro Melo's avatar
Leandro Melo committed
930 931
        c.setPosition(endOfExpression);
        if (completeInclude(c))
932
            m_startPosition = endOfExpression + 1;
Leandro Melo's avatar
Leandro Melo committed
933 934 935 936
        return m_startPosition;
    }

    ExpressionUnderCursor expressionUnderCursor;
937
    QTextCursor tc(m_interface->textDocument());
Leandro Melo's avatar
Leandro Melo committed
938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960

    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) {
961
            if (expression.endsWith(QLatin1String("SIGNAL"))) {
Leandro Melo's avatar
Leandro Melo committed
962
                m_model->m_completionOperator = T_SIGNAL;
963
            } else if (expression.endsWith(QLatin1String("SLOT"))) {
Leandro Melo's avatar
Leandro Melo committed
964
                m_model->m_completionOperator = T_SLOT;
965
            } else if (m_interface->position() != endOfOperator) {
Leandro Melo's avatar
Leandro Melo committed
966 967 968 969 970 971 972 973 974 975 976 977 978
                // 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;
979
    Convenience::convertPosition(m_interface->textDocument(), startOfExpression, &line, &column);
980
    const QString fileName = m_interface->fileName();
Leandro Melo's avatar
Leandro Melo committed
981 982
    return startCompletionInternal(fileName, line, column, expression, endOfExpression);
}
983

Leandro Melo's avatar
Leandro Melo committed
984 985 986 987
bool CppCompletionAssistProcessor::tryObjCCompletion()
{
    int end = m_interface->position();
    while (m_interface->characterAt(end).isSpace())
988
        ++end;
Leandro Melo's avatar
Leandro Melo committed
989
    if (m_interface->characterAt(end) != QLatin1Char(']'))
990 991
        return false;

992
    QTextCursor tc(m_interface->textDocument());
993 994 995 996 997 998 999 1000 1001 1002
    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
1003
    const QString expr = m_interface->textAt(startPos, m_interface->position() - startPos);
1004

1005
    Document::Ptr thisDocument = m_interface->snapshot().document(m_interface->fileName());
1006
    if (!thisDocument)
1007 1008
        return false;

1009 1010
    m_model->m_typeOfExpression->init(thisDocument, m_interface->snapshot());

1011
    int line = 0, column = 0;
1012
    Convenience::convertPosition(m_interface->textDocument(), m_interface->position(), &line, &column);
1013 1014 1015 1016
    Scope *scope = thisDocument->scopeAt(line, column);
    if (!scope)
        return false;

1017
    const QList<LookupItem> items = (*m_model->m_typeOfExpression)(expr.toUtf8(), scope);
1018
    LookupContext lookupContext(thisDocument, m_interface->snapshot());
1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039

    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
1040
    m_startPosition = m_interface->position();
1041 1042 1043
    return true;
}

1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055
namespace {
enum CompletionOrder {
    // default order is 0
    FunctionArgumentsOrder = 2,
    FunctionLocalsOrder = 2, // includes local types
    PublicClassMemberOrder = 1,
    InjectedClassNameOrder = -1,
    MacrosOrder = -2,
    KeywordsOrder = -2
};
}

Leandro Melo's avatar
Leandro Melo committed
1056 1057 1058 1059
void CppCompletionAssistProcessor::addCompletionItem(const QString &text,
                                                     const QIcon &icon,
                                                     int order,
                                                     const QVariant &data)
1060
{
Leandro Melo's avatar
Leandro Melo committed
1061 1062 1063 1064 1065 1066 1067
    BasicProposalItem *item = new CppAssistProposalItem;
    item->setText(text);
    item->setIcon(icon);
    item->setOrder(order);
    item->setData(data);
    m_completions.append(item);
}
1068

1069 1070
void CppCompletionAssistProcessor::addCompletionItem(CPlusPlus::Symbol *symbol,
                                                     int order)
Leandro Melo's avatar
Leandro Melo committed
1071 1072 1073 1074 1075
{
    ConvertToCompletionItem toCompletionItem;
    BasicProposalItem *item = toCompletionItem(symbol);
    if (item) {
        item->setIcon(m_icons.iconForSymbol(symbol));
1076
        item->setOrder(order);
Leandro Melo's avatar
Leandro Melo committed
1077
        m_completions.append(item);
1078
    }
Leandro Melo's avatar
Leandro Melo committed
1079
}
1080

Leandro Melo's avatar
Leandro Melo committed
1081 1082 1083 1084 1085 1086 1087 1088
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
1089

Leandro Melo's avatar
Leandro Melo committed
1090 1091 1092
    foreach (Scope *scope, memberScopes) {
        for (unsigned i = 0; i < scope->memberCount(); ++i) {
            Symbol *symbol = scope->memberAt(i);
con's avatar
con committed
1093

Leandro Melo's avatar
Leandro Melo committed
1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105
            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);
1106
                            text += QString::fromUtf8(selectorName->nameAt(i)->identifier()->chars());
Leandro Melo's avatar
Leandro Melo committed
1107 1108 1109
                            text += QLatin1Char(':');
                            text += TextEditor::Snippet::kVariableDelimiter;
                            text += QLatin1Char('(');
1110
                            text += oo.prettyType(arg->type());
Leandro Melo's avatar
Leandro Melo committed
1111
                            text += QLatin1Char(')');
1112
                            text += oo.prettyName(arg->name());
Leandro Melo's avatar
Leandro Melo committed
1113 1114 1115
                            text += TextEditor::Snippet::kVariableDelimiter;
                        }
                    } else {
1116
                        text = QString::fromUtf8(selectorName->identifier()->chars());
Leandro Melo's avatar
Leandro Melo committed
1117 1118
                    }
                    data = text;
con's avatar
con committed
1119

Leandro Melo's avatar
Leandro Melo committed
1120 1121 1122 1123
                    if (!text.isEmpty())
                        addCompletionItem(text, QIcon(), 0, QVariant::fromValue(data));
                }
            }
1124 1125
        }
    }
Leandro Melo's avatar
Leandro Melo committed
1126
}
1127

Leandro Melo's avatar
Leandro Melo committed
1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143
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);
1144 1145
    }

Leandro Melo's avatar
Leandro Melo committed
1146 1147
    // Make completion for all relevant includes
    QStringList includePaths = m_interface->includePaths();
1148
    const QString &currentFilePath = QFileInfo(m_interface->fileName()).path();
Leandro Melo's avatar
Leandro Melo committed
1149 1150 1151
    if (!includePaths.contains(currentFilePath))
        includePaths.append(currentFilePath);

1152
    const Core::MimeType mimeType =
hjk's avatar
hjk committed
1153
            Core::MimeDatabase::findByType(QLatin1String("text/x-c++hdr"));
1154 1155
    const QStringList suffixes = mimeType.suffixes();

Leandro Melo's avatar
Leandro Melo committed
1156 1157 1158 1159 1160 1161
    foreach (const QString &includePath, includePaths) {
        QString realPath = includePath;
        if (!directoryPrefix.isEmpty()) {
            realPath += QLatin1Char('/');
            realPath += directoryPrefix;
        }
1162
        completeInclude(realPath, suffixes);
1163 1164
    }

Leandro Melo's avatar
Leandro Melo committed
1165 1166 1167 1168 1169 1170
    foreach (const QString &frameworkPath, m_interface->frameworkPaths()) {
        QString realPath = frameworkPath;
        if (!directoryPrefix.isEmpty()) {
            realPath += QLatin1Char('/');
            realPath += directoryPrefix;
            realPath += QLatin1String(".framework/Headers");
1171
        }
1172
        completeInclude(realPath, suffixes);
1173 1174
    }

Leandro Melo's avatar
Leandro Melo committed
1175 1176
    return !m_completions.isEmpty();
}
1177

1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194
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
1195 1196 1197 1198
void CppCompletionAssistProcessor::completePreprocessor()
{
    foreach (const QString &preprocessorCompletion, preprocessorCompletions)
        addCompletionItem(preprocessorCompletion);