cppcodecompletion.cpp 39.8 KB
Newer Older
con's avatar
con committed
1
2
3
4
/***************************************************************************
**
** This file is part of Qt Creator
**
5
** Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies).
con's avatar
con committed
6
7
8
**
** Contact:  Qt Software Information (qt-info@nokia.com)
**
9
10
11
**
** Non-Open Source Usage
**
con's avatar
con committed
12
13
14
** Licensees may use this file in accordance with the Qt Beta Version
** License Agreement, Agreement version 2.2 provided with the Software or,
** alternatively, in accordance with the terms contained in a written
15
16
17
18
** agreement between you and Nokia.
**
** GNU General Public License Usage
**
con's avatar
con committed
19
20
21
22
23
24
25
26
27
28
** Alternatively, this file may be used under the terms of the GNU General
** Public License versions 2.0 or 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the packaging
** of this file.  Please review the following information to ensure GNU
** General Public Licensing requirements will be met:
**
** http://www.fsf.org/licensing/licenses/info/GPLv2.html and
** http://www.gnu.org/copyleft/gpl.html.
**
** In addition, as a special exception, Nokia gives you certain additional
29
** rights. These rights are described in the Nokia Qt GPL Exception
30
** version 1.3, included in the file GPL_EXCEPTION.txt in this package.
31
32
**
***************************************************************************/
hjk's avatar
hjk committed
33

con's avatar
con committed
34
#include "cppcodecompletion.h"
hjk's avatar
hjk committed
35

con's avatar
con committed
36
37
38
39
40
41
42
43
44
45
46
47
48
#include "cppmodelmanager.h"

#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>
hjk's avatar
hjk committed
49

con's avatar
con committed
50
51
52
53
54
55
56
57
58
59
#include <cplusplus/ResolveExpression.h>
#include <cplusplus/LookupContext.h>
#include <cplusplus/Overview.h>
#include <cplusplus/ExpressionUnderCursor.h>
#include <cplusplus/TokenUnderCursor.h>

#include <coreplugin/icore.h>
#include <coreplugin/editormanager/editormanager.h>
#include <texteditor/itexteditor.h>
#include <texteditor/itexteditable.h>
hjk's avatar
hjk committed
60
#include <utils/qtcassert.h>
con's avatar
con committed
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
#include <texteditor/basetexteditor.h>

#include <QtCore/QDebug>
#include <QtCore/QMap>
#include <QtCore/QFile>
#include <QtGui/QAction>
#include <QtGui/QKeyEvent>
#include <QtGui/QLabel>
#include <QtGui/QVBoxLayout>
#include <QtGui/QApplication>

using namespace CPlusPlus;

namespace CppTools {
namespace Internal {

77
78
class FunctionArgumentWidget : public QLabel
{
con's avatar
con committed
79
public:
80
    FunctionArgumentWidget();
81
    void showFunctionHint(Function *functionSymbol, const Snapshot &snapshot);
con's avatar
con committed
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97

protected:
    bool eventFilter(QObject *obj, QEvent *e);

private:
    void update();
    void close();
    void updateHintText();

    int m_startpos;
    int m_currentarg;

    TextEditor::ITextEditor *m_editor;

    QFrame *m_popupFrame;
    Function *m_item;
98
    Snapshot m_snapshot;
con's avatar
con committed
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
};

class ConvertToCompletionItem: protected NameVisitor
{
    // The completion collector.
    CppCodeCompletion *_collector;

    // The completion item.
    TextEditor::CompletionItem _item;

    // The current symbol.
    Symbol *_symbol;

    // The pretty printer.
    Overview overview;

public:
    ConvertToCompletionItem(CppCodeCompletion *collector)
        : _collector(collector),
          _item(0),
          _symbol(0)
    { }

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

        TextEditor::CompletionItem previousItem = switchCompletionItem(0);
        Symbol *previousSymbol = switchSymbol(symbol);
        accept(symbol->identity());
        if (_item)
            _item.m_data = QVariant::fromValue(symbol);
        (void) switchSymbol(previousSymbol);
        return switchCompletionItem(previousItem);
    }

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

    TextEditor::CompletionItem switchCompletionItem(TextEditor::CompletionItem item)
    {
        TextEditor::CompletionItem previousItem = _item;
        _item = item;
        return previousItem;
    }

    TextEditor::CompletionItem newCompletionItem(Name *name)
    {
        TextEditor::CompletionItem item(_collector);
        item.m_text = overview.prettyName(name);
        item.m_icon = _collector->iconForSymbol(_symbol);
        return item;
    }

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

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

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

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

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

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


} // namespace Internal
} // namespace CppTools

using namespace CppTools::Internal;

187
FunctionArgumentWidget::FunctionArgumentWidget()
con's avatar
con committed
188
189
    : m_item(0)
{
190
    QObject *editorObject = Core::ICore::instance()->editorManager()->currentEditor();
con's avatar
con committed
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
    m_editor = qobject_cast<TextEditor::ITextEditor *>(editorObject);

    m_popupFrame = new QFrame(0, Qt::ToolTip|Qt::WindowStaysOnTopHint);
    m_popupFrame->setFocusPolicy(Qt::NoFocus);
    m_popupFrame->setAttribute(Qt::WA_DeleteOnClose);

    setFrameStyle(QFrame::Box);
    setFrameShadow(QFrame::Plain);

    setParent(m_popupFrame);
    setFocusPolicy(Qt::NoFocus);

    QVBoxLayout *layout = new QVBoxLayout();
    layout->addWidget(this);
    layout->setMargin(0);
    m_popupFrame->setLayout(layout);

    QPalette pal = palette();
    setAutoFillBackground(true);
    pal.setColor(QPalette::Background, QColor(255, 255, 220));
    setPalette(pal);

    setTextFormat(Qt::RichText);
    setMargin(1);
}

217
218
void FunctionArgumentWidget::showFunctionHint(Function *functionSymbol,
                                              const Snapshot &snapshot)
con's avatar
con committed
219
220
{
    m_item = functionSymbol;
221
    m_snapshot = snapshot;
con's avatar
con committed
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
    m_startpos = m_editor->position();

    // update the text
    m_currentarg = -1;
    update();

    QPoint pos = m_editor->cursorRect().topLeft();
    pos.setY(pos.y() - sizeHint().height());
    m_popupFrame->move(pos);
    m_popupFrame->show();

    QCoreApplication::instance()->installEventFilter(this);
}

void FunctionArgumentWidget::update()
{
    int curpos = m_editor->position();
    if (curpos < m_startpos) {
        close();
        return;
    }

    QString str = m_editor->textAt(m_startpos, curpos - m_startpos);
    int argnr = 0;
    int parcount = 0;
    SimpleLexer tokenize;
    QList<SimpleToken> tokens = tokenize(str);
    for (int i = 0; i < tokens.count(); ++i) {
        const SimpleToken &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 (m_currentarg != argnr) {
        m_currentarg = argnr;
        updateHintText();
    }

    if (parcount < 0)
        close();
}

bool FunctionArgumentWidget::eventFilter(QObject *obj, QEvent *e)
{
    switch (e->type()) {
    case QEvent::KeyRelease:
        {
            if (static_cast<QKeyEvent*>(e)->key() == Qt::Key_Escape) {
                close();
                return false;
            }
            update();
            break;
        }
    case QEvent::WindowDeactivate:
    case QEvent::Leave:
    case QEvent::FocusOut:
        {
            if (obj != m_editor->widget())
                break;
        }
    case QEvent::MouseButtonPress:
    case QEvent::MouseButtonRelease:
    case QEvent::MouseButtonDblClick:
    case QEvent::Wheel:
        close();
        break;
    default:
        break;
    }

    return false;
}

void FunctionArgumentWidget::close()
{
    m_popupFrame->close();
}

void FunctionArgumentWidget::updateHintText()
{
    Overview overview;
    overview.setShowReturnTypes(true);
    overview.setShowArgumentNames(true);
    overview.setMarkArgument(m_currentarg + 1);
    QString text = overview(m_item->type(), m_item->name());
    setText(text);
}

315
CppCodeCompletion::CppCodeCompletion(CppModelManager *manager)
con's avatar
con committed
316
317
    : ICompletionCollector(manager),
      m_manager(manager),
318
319
      m_caseSensitivity(Qt::CaseSensitive),
      m_autoInsertBraces(true),
con's avatar
con committed
320
321
      m_forcedCompletion(false),
      m_completionOperator(T_EOF_SYMBOL)
322
323
{
}
con's avatar
con committed
324
325

QIcon CppCodeCompletion::iconForSymbol(Symbol *symbol) const
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
{
    return m_icons.iconForSymbol(symbol);
}

Qt::CaseSensitivity CppCodeCompletion::caseSensitivity() const
{
    return m_caseSensitivity;
}

void CppCodeCompletion::setCaseSensitivity(Qt::CaseSensitivity caseSensitivity)
{
    m_caseSensitivity = caseSensitivity;
}

bool CppCodeCompletion::autoInsertBraces() const
{
    return m_autoInsertBraces;
}

void CppCodeCompletion::setAutoInsertBraces(bool autoInsertBraces)
{
    m_autoInsertBraces = autoInsertBraces;
}
con's avatar
con committed
349

350
351
352
353
354
355
356
357
358
359
bool CppCodeCompletion::isPartialCompletionEnabled() const
{
    return m_partialCompletionEnabled;
}

void CppCodeCompletion::setPartialCompletionEnabled(bool partialCompletionEnabled)
{
    m_partialCompletionEnabled = partialCompletionEnabled;
}

con's avatar
con committed
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
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
/*
  Searches beckward for an access operator.
*/
static int startOfOperator(TextEditor::ITextEditable *editor,
                           int pos, unsigned *kind,
                           bool wantFunctionCall)
{
    const QChar ch  = pos > -1 ? editor->characterAt(pos - 1) : QChar();
    const QChar ch2 = pos >  0 ? editor->characterAt(pos - 2) : QChar();
    const QChar ch3 = pos >  1 ? editor->characterAt(pos - 3) : QChar();

    int start = pos;

    if        (ch2 != QLatin1Char('.') && ch == QLatin1Char('.')) {
        if (kind)
            *kind = T_DOT;
        --start;
    } else if (wantFunctionCall        && ch == QLatin1Char('(')) {
        if (kind)
            *kind = T_LPAREN;
        --start;
    } else if (ch2 == QLatin1Char(':') && ch == QLatin1Char(':')) {
        if (kind)
            *kind = T_COLON_COLON;
        start -= 2;
    } else if (ch2 == QLatin1Char('-') && ch == QLatin1Char('>')) {
        if (kind)
            *kind = T_ARROW;
        start -= 2;
    } else if (ch2 == QLatin1Char('.') && ch == QLatin1Char('*')) {
        if (kind)
            *kind = T_DOT_STAR;
        start -= 2;
    } else if (ch3 == QLatin1Char('-') && ch2 == QLatin1Char('>') && ch == QLatin1Char('*')) {
        if (kind)
            *kind = T_ARROW_STAR;
        start -= 3;
    }

    if (start != pos) {
        TextEditor::BaseTextEditor *edit = qobject_cast<TextEditor::BaseTextEditor *>(editor->widget());
        QTextCursor tc(edit->textCursor());
        tc.setPosition(pos);
        static CPlusPlus::TokenUnderCursor tokenUnderCursor;
        const SimpleToken tk = tokenUnderCursor(tc);
        if (tk.is(T_COMMENT) || tk.isLiteral()) {
            if (kind)
                *kind = T_EOF_SYMBOL;
            return pos;
        }
    }

    return start;
}

bool CppCodeCompletion::triggersCompletion(TextEditor::ITextEditable *editor)
{
    if (! m_manager->isCppEditor(editor)) // ### remove me
        return false;

    const int pos = editor->position();
    if (startOfOperator(editor, pos, /*token =*/ 0,
                        /*want function call=*/ true) != pos)
        return true;

    return false;
}

int CppCodeCompletion::startCompletion(TextEditor::ITextEditable *editor)
{
    TextEditor::BaseTextEditor *edit = qobject_cast<TextEditor::BaseTextEditor *>(editor->widget());
    if (! edit)
        return -1;

    m_editor = editor;
435
    m_startPosition = findStartOfName();
con's avatar
con committed
436
437
    m_completionOperator = T_EOF_SYMBOL;

438
    int endOfOperator = m_startPosition;
con's avatar
con committed
439
440

    // Skip whitespace preceding this position
441
442
    while (editor->characterAt(endOfOperator - 1).isSpace())
        --endOfOperator;
con's avatar
con committed
443

444
445
446
    int endOfExpression = startOfOperator(editor, endOfOperator,
                                          &m_completionOperator,
                                          /*want function call =*/ true);
con's avatar
con committed
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466

    Core::IFile *file = editor->file();
    QString fileName = file->fileName();

    int line = 0, column = 0;
    edit->convertPosition(editor->position(), &line, &column);
    // qDebug() << "line:" << line << "column:" << column;

    ExpressionUnderCursor expressionUnderCursor;
    QString expression;

    if (m_completionOperator) {
        QTextCursor tc(edit->document());
        tc.setPosition(endOfExpression);
        expression = expressionUnderCursor(tc);
        if (m_completionOperator == T_LPAREN) {
            if (expression.endsWith(QLatin1String("SIGNAL")))
                m_completionOperator = T_SIGNAL;
            else if (expression.endsWith(QLatin1String("SLOT")))
                m_completionOperator = T_SLOT;
467
468
469
470
471
            else if (editor->position() != endOfOperator) {
                // We don't want a function completion when the cursor isn't at the opening brace
                expression.clear();
                m_completionOperator = T_EOF_SYMBOL;
            }
con's avatar
con committed
472
473
474
475
476
477
        }
    }

    //if (! expression.isEmpty())
        //qDebug() << "***** expression:" << expression;

478
479
480
    const Snapshot snapshot = m_manager->snapshot();

    if (Document::Ptr thisDocument = snapshot.value(fileName)) {
con's avatar
con committed
481
482
        Symbol *symbol = thisDocument->findSymbolAt(line, column);

483
        typeOfExpression.setSnapshot(m_manager->snapshot());
con's avatar
con committed
484

485
486
        QList<TypeOfExpression::Result> resolvedTypes = typeOfExpression(expression, thisDocument, symbol,
                                                                         TypeOfExpression::Preprocess);
con's avatar
con committed
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
        LookupContext context = typeOfExpression.lookupContext();

        if (!typeOfExpression.expressionAST() && (! m_completionOperator ||
                                                    m_completionOperator == T_COLON_COLON)) {
            if (!m_completionOperator) {
                addKeywords();
                addMacros(context);
            }

            const QList<Scope *> scopes = context.expand(context.visibleScopes());
            foreach (Scope *scope, scopes) {
                for (unsigned i = 0; i < scope->symbolCount(); ++i) {
                    addCompletionItem(scope->symbolAt(i));
                }
            }
            return m_startPosition;
        }

        // qDebug() << "found" << resolvedTypes.count() << "symbols for expression:" << expression;

        if (resolvedTypes.isEmpty() && (m_completionOperator == T_SIGNAL ||
                                        m_completionOperator == T_SLOT)) {
            // Apply signal/slot completion on 'this'
            expression = QLatin1String("this");
            resolvedTypes = typeOfExpression(expression, thisDocument, symbol);
            context = typeOfExpression.lookupContext();
        }

515
        if (! resolvedTypes.isEmpty() && resolvedTypes.first().first) {
con's avatar
con committed
516
517
518
519
520
521
522
            FullySpecifiedType exprTy = resolvedTypes.first().first;

            if (exprTy->isReferenceType())
                exprTy = exprTy->asReferenceType()->elementType();

            if (m_completionOperator == T_LPAREN && completeFunction(exprTy, resolvedTypes, context)) {
                return m_startPosition;
523
            } else if ((m_completionOperator == T_DOT || m_completionOperator == T_ARROW) &&
524
                      completeMember(resolvedTypes, context)) {
con's avatar
con committed
525
                return m_startPosition;
526
            } else if (m_completionOperator == T_COLON_COLON && completeScope(resolvedTypes, context)) {
con's avatar
con committed
527
528
529
530
531
532
533
                return m_startPosition;
            } else if (m_completionOperator == T_SIGNAL && completeSignal(exprTy, resolvedTypes, context)) {
                return m_startPosition;
            } else if (m_completionOperator == T_SLOT && completeSlot(exprTy, resolvedTypes, context)) {
                return m_startPosition;
            }
        }
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551

        if (m_completionOperator == T_LPAREN) {
            // Find the expression that precedes the current name
            int index = endOfExpression;
            while (m_editor->characterAt(index - 1).isSpace())
                --index;
            index = findStartOfName(index);

            QTextCursor tc(edit->document());
            tc.setPosition(index);
            QString baseExpression = expressionUnderCursor(tc);

            // Resolve the type of this expression
            QList<TypeOfExpression::Result> results =
                    typeOfExpression(baseExpression, thisDocument, symbol, TypeOfExpression::Preprocess);

            // If it's a class, add completions for the constructors
            foreach (const TypeOfExpression::Result &result, results) {
552
                if (result.first->isClassType()) {
553
                    FullySpecifiedType exprTy = result.first;
554
                    if (completeConstructors(exprTy->asClassType()))
555
556
557
558
559
                        return m_startPosition;
                    break;
                }
            }
        }
con's avatar
con committed
560
561
562
563
564
565
566
567
568
569
    }

    // nothing to do.
    return -1;
}

bool CppCodeCompletion::completeFunction(FullySpecifiedType exprTy,
                                         const QList<TypeOfExpression::Result> &resolvedTypes,
                                         const LookupContext &)
{
570
    if (Class *klass = exprTy->asClassType()) {
571
        completeConstructors(klass);
con's avatar
con committed
572
    } else {
573
574
575
576
577
        ConvertToCompletionItem toCompletionItem(this);
        Overview o;
        o.setShowReturnTypes(true);
        o.setShowArgumentNames(true);

con's avatar
con committed
578
579
580
        QSet<QString> signatures;
        foreach (TypeOfExpression::Result p, resolvedTypes) {
            FullySpecifiedType ty = p.first;
581
            if (Function *fun = ty->asFunctionType()) {
con's avatar
con committed
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
                if (TextEditor::CompletionItem item = toCompletionItem(fun)) {
                    QString signature;
                    signature += overview.prettyName(fun->name());
                    signature += overview.prettyType(fun->type());
                    if (signatures.contains(signature))
                        continue;
                    signatures.insert(signature);

                    item.m_text = o(ty, fun->name());
                    m_completions.append(item);
                }
            }
        }
    }

    return ! m_completions.isEmpty();
}

600
bool CppCodeCompletion::completeMember(const QList<TypeOfExpression::Result> &results,
con's avatar
con committed
601
602
                                       const LookupContext &context)
{
Roberto Raggi's avatar
Roberto Raggi committed
603
604
    if (results.isEmpty())
        return false;
con's avatar
con committed
605

606
    TypeOfExpression::Result result = results.first();
con's avatar
con committed
607
608
609
    QList<Symbol *> classObjectCandidates;

    if (m_completionOperator == T_ARROW)  {
610
        FullySpecifiedType ty = result.first;
con's avatar
con committed
611
612
613
614

        if (ReferenceType *refTy = ty->asReferenceType())
            ty = refTy->elementType();

615
        if (Class *classTy = ty->asClassType()) {
616
617
618
            Symbol *symbol = result.second;
            if (symbol && ! symbol->isClass())
                classObjectCandidates.append(classTy);
619
        } else if (NamedType *namedTy = ty->asNamedType()) {
620
621
622
623
624
625
626
627
628
629
630
631
            // ### This code is pretty slow.
            const QList<Symbol *> candidates = context.resolve(namedTy->name());
            foreach (Symbol *candidate, candidates) {
                if (candidate->isTypedef()) {
                    ty = candidate->type();
                    const ResolveExpression::Result r(ty, candidate);
                    result = r;
                    break;
                }
            }
        }

con's avatar
con committed
632
633
        if (NamedType *namedTy = ty->asNamedType()) {
            ResolveExpression resolveExpression(context);
634
            ResolveClass resolveClass;
con's avatar
con committed
635

636
            const QList<Symbol *> candidates = resolveClass(result, context);
con's avatar
con committed
637
638
            foreach (Symbol *classObject, candidates) {
                const QList<TypeOfExpression::Result> overloads =
639
                        resolveExpression.resolveArrowOperator(result, namedTy,
con's avatar
con committed
640
641
642
643
                                                               classObject->asClass());

                foreach (TypeOfExpression::Result r, overloads) {
                    FullySpecifiedType ty = r.first;
644
                    Function *funTy = ty->asFunctionType();
con's avatar
con committed
645
646
647
648
649
650
651
652
653
654
655
                    if (! funTy)
                        continue;

                    ty = funTy->returnType();

                    if (ReferenceType *refTy = ty->asReferenceType())
                        ty = refTy->elementType();

                    if (PointerType *ptrTy = ty->asPointerType()) {
                        if (NamedType *namedTy = ptrTy->elementType()->asNamedType()) {
                            const QList<Symbol *> classes =
656
                                    resolveClass(namedTy, result, context);
con's avatar
con committed
657
658
659
660
661
662
663
664
665
666
667

                            foreach (Symbol *c, classes) {
                                if (! classObjectCandidates.contains(c))
                                    classObjectCandidates.append(c);
                            }
                        }
                    }
                }
            }
        } else if (PointerType *ptrTy = ty->asPointerType()) {
            if (NamedType *namedTy = ptrTy->elementType()->asNamedType()) {
668
                ResolveClass resolveClass;
669

670
671
                const QList<Symbol *> classes = resolveClass(namedTy, result,
                                                             context);
con's avatar
con committed
672
673
674
675
676

                foreach (Symbol *c, classes) {
                    if (! classObjectCandidates.contains(c))
                        classObjectCandidates.append(c);
                }
677
            } else if (Class *classTy = ptrTy->elementType()->asClassType()) {
678
679
680
681
                // typedef struct { int x } *Ptr;
                // Ptr p;
                // p->
                classObjectCandidates.append(classTy);
con's avatar
con committed
682
683
684
            }
        }
    } else if (m_completionOperator == T_DOT) {
685
        FullySpecifiedType ty = result.first;
con's avatar
con committed
686
687
688
689
690

        if (ReferenceType *refTy = ty->asReferenceType())
            ty = refTy->elementType();

        NamedType *namedTy = 0;
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708

        if (ArrayType *arrayTy = ty->asArrayType()) {
            // Replace . with [0]. when `ty' is an array type.
            FullySpecifiedType elementTy = arrayTy->elementType();

            if (ReferenceType *refTy = elementTy->asReferenceType())
                elementTy = refTy->elementType();

            if (elementTy->isNamedType() || elementTy->isPointerType()) {
                ty = elementTy;

                const int length = m_editor->position() - m_startPosition + 1;
                m_editor->setCurPos(m_startPosition - 1);
                m_editor->replace(length, QLatin1String("[0]."));
                m_startPosition += 3;
            }
        }

con's avatar
con committed
709
        if (PointerType *ptrTy = ty->asPointerType()) {
710
711
712
713
714
715
716
717
            if (ptrTy->elementType()->isNamedType()) {
                // Replace . with ->
                int length = m_editor->position() - m_startPosition + 1;
                m_editor->setCurPos(m_startPosition - 1);
                m_editor->replace(length, QLatin1String("->"));
                ++m_startPosition;
                namedTy = ptrTy->elementType()->asNamedType();
            }
718
        } else if (Class *classTy = ty->asClassType()) {
719
720
721
            Symbol *symbol = result.second;
            if (symbol && ! symbol->isClass())
                classObjectCandidates.append(classTy);
con's avatar
con committed
722
723
724
        } else {
            namedTy = ty->asNamedType();
            if (! namedTy) {
725
                Function *fun = ty->asFunctionType();
con's avatar
con committed
726
727
728
729
730
731
                if (fun && (fun->scope()->isBlockScope() || fun->scope()->isNamespaceScope()))
                    namedTy = fun->returnType()->asNamedType();
            }
        }

        if (namedTy) {
732
            ResolveClass resolveClass;
733
734
            const QList<Symbol *> symbols = resolveClass(namedTy, result,
                                                         context);
Roberto Raggi's avatar
Roberto Raggi committed
735
736
737
738
739
            foreach (Symbol *symbol, symbols) {
                if (classObjectCandidates.contains(symbol))
                    continue;
                if (Class *klass = symbol->asClass())
                    classObjectCandidates.append(klass);
con's avatar
con committed
740
741
742
743
744
745
746
747
748
749
750
            }
        }
    }

    completeClass(classObjectCandidates, context, /*static lookup = */ false);
    if (! m_completions.isEmpty())
        return true;

    return false;
}

751
bool CppCodeCompletion::completeScope(const QList<TypeOfExpression::Result> &results,
con's avatar
con committed
752
753
                                      const LookupContext &context)
{
754
755
756
    if (results.isEmpty())
        return false; // nothing to do.

con's avatar
con committed
757
    // Search for a class or a namespace.
758
    TypeOfExpression::Result result;
759
760
761
    foreach (result, results) {
        FullySpecifiedType ty = result.first;

762
        if (ty->isClassType() || ty->isNamespaceType())
con's avatar
con committed
763
764
765
            break;
    }

766
767
768
    FullySpecifiedType exprTy = result.first;
    if (! exprTy) {
        return false;
769
    } else if (exprTy->isNamespaceType()) {
con's avatar
con committed
770
        QList<Symbol *> candidates;
771
        foreach (TypeOfExpression::Result p, results) {
772
            if (Namespace *ns = p.first->asNamespaceType())
con's avatar
con committed
773
774
775
                candidates.append(ns);
        }
        completeNamespace(candidates, context);
776
    } else if (exprTy->isClassType()) {
con's avatar
con committed
777
        QList<Symbol *> candidates;
778
        foreach (TypeOfExpression::Result p, results) {
779
            if (Class *k = p.first->asClassType())
con's avatar
con committed
780
781
782
                candidates.append(k);
        }
        completeClass(candidates, context);
783
784
    } else if (Symbol *symbol = result.second) {
        if (symbol->isTypedef()) {
785
            ResolveClass resolveClass;
786
            const QList<Symbol *> candidates = resolveClass(result, context);
787
788
            completeClass(candidates, context);
        }
con's avatar
con committed
789
790
791
792
793
794
795
796
    }

    return ! m_completions.isEmpty();
}

void CppCodeCompletion::addKeywords()
{
    // keyword completion items.
797
    for (int i = T_FIRST_KEYWORD; i < T_FIRST_OBJC_AT_KEYWORD; ++i) {
con's avatar
con committed
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
        TextEditor::CompletionItem item(this);
        item.m_text = QLatin1String(Token::name(i));
        item.m_icon = m_icons.keywordIcon();
        m_completions.append(item);
    }
}

void CppCodeCompletion::addMacros(const LookupContext &context)
{
    // macro completion items.
    QSet<QByteArray> macroNames;
    QSet<QString> processed;
    QList<QString> todo;
    todo.append(context.thisDocument()->fileName());
    while (! todo.isEmpty()) {
        QString fn = todo.last();
        todo.removeLast();
        if (processed.contains(fn))
            continue;
        processed.insert(fn);
        if (Document::Ptr doc = context.document(fn)) {
819
            foreach (const Macro &macro, doc->definedMacros()) {
820
                macroNames.insert(macro.name());
Roberto Raggi's avatar
Roberto Raggi committed
821
            }
con's avatar
con committed
822
823
824
825
            todo += doc->includedFiles();
        }
    }

826
    foreach (const QByteArray &macroName, macroNames) {
con's avatar
con committed
827
        TextEditor::CompletionItem item(this);
828
        item.m_text = QString::fromUtf8(macroName.constData(), macroName.length());
con's avatar
con committed
829
830
831
832
833
834
835
836
837
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
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
        item.m_icon = m_icons.macroIcon();
        m_completions.append(item);
    }
}

void CppCodeCompletion::addCompletionItem(Symbol *symbol)
{
    ConvertToCompletionItem toCompletionItem(this);
    if (TextEditor::CompletionItem item = toCompletionItem(symbol))
        m_completions.append(item);
}

void CppCodeCompletion::completeNamespace(const QList<Symbol *> &candidates,
                                          const LookupContext &context)
{
    QList<Scope *> todo;
    QList<Scope *> visibleScopes = context.visibleScopes();
    foreach (Symbol *candidate, candidates) {
        if (Namespace *ns = candidate->asNamespace())
            context.expand(ns->members(), visibleScopes, &todo);
    }

    foreach (Scope *scope, todo) {
        addCompletionItem(scope->owner());

        for (unsigned i = 0; i < scope->symbolCount(); ++i) {
            addCompletionItem(scope->symbolAt(i));
        }
    }
}

void CppCodeCompletion::completeClass(const QList<Symbol *> &candidates,
                                      const LookupContext &context,
                                      bool staticLookup)
{
    if (candidates.isEmpty())
        return;

    Class *klass = candidates.first()->asClass();

    QList<Scope *> todo;
    context.expand(klass->members(), context.visibleScopes(), &todo);

    foreach (Scope *scope, todo) {
        addCompletionItem(scope->owner());

        for (unsigned i = 0; i < scope->symbolCount(); ++i) {
            Symbol *symbol = scope->symbolAt(i);

            if (symbol->type().isFriend())
                continue;
            else if (! staticLookup && (symbol->isTypedef() ||
                                        symbol->isEnum()    ||
                                        symbol->isClass()))
                continue;

            addCompletionItem(symbol);
        }
    }
}

890
891
892
893
894
895
896
897
898
bool CppCodeCompletion::completeConstructors(Class *klass)
{
    ConvertToCompletionItem toCompletionItem(this);
    Overview o;
    o.setShowReturnTypes(true);
    o.setShowArgumentNames(true);

    for (unsigned i = 0; i < klass->memberCount(); ++i) {
        Symbol *member = klass->memberAt(i);
899
        if (! member->type()->isFunctionType())
900
901
902
903
904
905
906
907
908
909
910
911
912
913
            continue;
        else if (! member->identity())
            continue;
        else if (! member->identity()->isEqualTo(klass->identity()))
            continue;
        if (TextEditor::CompletionItem item = toCompletionItem(member)) {
            item.m_text = o(member->type(), member->name());
            m_completions.append(item);
        }
    }

    return ! m_completions.isEmpty();
}

con's avatar
con committed
914
915
916
917
918
919
920
921
bool CppCodeCompletion::completeQtMethod(CPlusPlus::FullySpecifiedType,
                                         const QList<TypeOfExpression::Result> &results,
                                         const LookupContext &context,
                                         bool wantSignals)
{
    if (results.isEmpty())
        return false;

922
923
    ResolveClass resolveClass;

con's avatar
con committed
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
    ConvertToCompletionItem toCompletionItem(this);
    Overview o;
    o.setShowReturnTypes(false);
    o.setShowArgumentNames(false);
    o.setShowFunctionSignatures(true);

    QSet<QString> signatures;
    foreach (TypeOfExpression::Result p, results) {
        FullySpecifiedType ty = p.first;
        if (ReferenceType *refTy = ty->asReferenceType())
            ty = refTy->elementType();
        if (PointerType *ptrTy = ty->asPointerType())
            ty = ptrTy->elementType();
        else
            continue; // not a pointer or a reference to a pointer.

        NamedType *namedTy = ty->asNamedType();
        if (! namedTy) // not a class name.
            continue;

        const QList<Symbol *> classObjects =
945
                resolveClass(namedTy, p, context);
con's avatar
con committed
946
947
948
949
950
951
952

        if (classObjects.isEmpty())
            continue;

        Class *klass = classObjects.first()->asClass();

        QList<Scope *> todo;
953
        const QList<Scope *> visibleScopes = context.visibleScopes(p);
con's avatar
con committed
954
955
956
957
958
959
960
961
        context.expand(klass->members(), visibleScopes, &todo);

        foreach (Scope *scope, todo) {
            if (! scope->isClassScope())
                continue;

            for (unsigned i = 0; i < scope->symbolCount(); ++i) {
                Symbol *member = scope->symbolAt(i);
962
                Function *fun = member->type()->asFunctionType();
con's avatar
con committed
963
964
965
966
967
968
969
970
971
                if (! fun)
                    continue;
                if (wantSignals && ! fun->isSignal())
                    continue;
                else if (! wantSignals && ! fun->isSlot())
                    continue;
                if (TextEditor::CompletionItem item = toCompletionItem(fun)) {
                    unsigned count = fun->argumentCount();
                    while (true) {
Friedemann Kleint's avatar
Friedemann Kleint committed
972
                        TextEditor::CompletionItem ci = item;
con's avatar
con committed
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992

                        QString signature;
                        signature += overview.prettyName(fun->name());
                        signature += QLatin1Char('(');
                        for (unsigned i = 0; i < count; ++i) {
                            Symbol *arg = fun->argumentAt(i);
                            if (i != 0)
                                signature += QLatin1Char(',');
                            signature += o.prettyType(arg->type());
                        }
                        signature += QLatin1Char(')');

                        const QByteArray normalized =
                                QMetaObject::normalizedSignature(signature.toLatin1());

                        signature = QString::fromLatin1(normalized, normalized.size());

                        if (! signatures.contains(signature)) {
                            signatures.insert(signature);

Friedemann Kleint's avatar
Friedemann Kleint committed
993
994
                            ci.m_text = signature; // fix the completion item.
                            m_completions.append(ci);
con's avatar
con committed
995
996
997
998
999
1000
                        }

                        if (count && fun->argumentAt(count - 1)->asArgument()->hasInitializer())
                            --count;
                        else
                            break;