cppcodecompletion.cpp 44.1 KB
Newer Older
1
/**************************************************************************
con's avatar
con committed
2
3
4
**
** This file is part of Qt Creator
**
5
** Copyright (c) 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
** Commercial Usage
10
**
11
12
13
14
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
15
**
16
** GNU Lesser General Public License Usage
17
**
18
19
20
21
22
23
** 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.
24
**
25
26
** If you are unsure which license is appropriate for your use, please
** contact the sales department at qt-sales@nokia.com.
con's avatar
con committed
27
**
28
**************************************************************************/
hjk's avatar
hjk committed
29

con's avatar
con committed
30
31
#include "cppcodecompletion.h"
#include "cppmodelmanager.h"
32
#include "cppdoxygen.h"
con's avatar
con committed
33
34
35
36
37
38
39
40
41
42
43
44

#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
45

con's avatar
con committed
46
47
48
49
50
51
52
53
54
55
#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
56
#include <utils/qtcassert.h>
con's avatar
con committed
57
58
59
60
61
62
#include <texteditor/basetexteditor.h>

#include <QtCore/QDebug>
#include <QtCore/QMap>
#include <QtCore/QFile>
#include <QtGui/QAction>
63
#include <QtGui/QApplication>
64
#include <QtGui/QDesktopWidget>
con's avatar
con committed
65
66
#include <QtGui/QKeyEvent>
#include <QtGui/QLabel>
67
#include <QtGui/QToolButton>
con's avatar
con committed
68
69
70
71
72
73
74
#include <QtGui/QVBoxLayout>

using namespace CPlusPlus;

namespace CppTools {
namespace Internal {

75
76
class FunctionArgumentWidget : public QLabel
{
77
78
    Q_OBJECT

con's avatar
con committed
79
public:
80
    FunctionArgumentWidget();
81
82
83
    void showFunctionHint(QList<Function *> functionSymbols,
                          const LookupContext &context,
                          int startPosition);
con's avatar
con committed
84
85
86
87

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

88
89
90
91
private slots:
    void nextPage();
    void previousPage();

con's avatar
con committed
92
private:
93
    void updateArgumentHighlight();
con's avatar
con committed
94
95
    void updateHintText();

96
97
98
    Function *currentFunction() const
    { return m_items.at(m_current); }

con's avatar
con committed
99
100
    int m_startpos;
    int m_currentarg;
101
    int m_current;
102
    bool m_escapePressed;
con's avatar
con committed
103
104
105

    TextEditor::ITextEditor *m_editor;

106
    QWidget *m_pager;
107
    QLabel *m_numberLabel;
con's avatar
con committed
108
    QFrame *m_popupFrame;
109
    QList<Function *> m_items;
110
    LookupContext m_context;
con's avatar
con committed
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
};

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;

199
FunctionArgumentWidget::FunctionArgumentWidget():
200
    m_startpos(-1),
201
202
    m_current(0),
    m_escapePressed(false)
con's avatar
con committed
203
{
204
    QObject *editorObject = Core::EditorManager::instance()->currentEditor();
con's avatar
con committed
205
206
    m_editor = qobject_cast<TextEditor::ITextEditor *>(editorObject);

207
    m_popupFrame = new QFrame(m_editor->widget(), Qt::ToolTip | Qt::WindowStaysOnTopHint);
con's avatar
con committed
208
209
210
    m_popupFrame->setFocusPolicy(Qt::NoFocus);
    m_popupFrame->setAttribute(Qt::WA_DeleteOnClose);

211
212
213
214
    QToolButton *downArrow = new QToolButton;
    downArrow->setArrowType(Qt::DownArrow);
    downArrow->setFixedSize(16, 16);
    downArrow->setAutoRaise(true);
215

216
217
218
219
    QToolButton *upArrow = new QToolButton;
    upArrow->setArrowType(Qt::UpArrow);
    upArrow->setFixedSize(16, 16);
    upArrow->setAutoRaise(true);
220
221
222

    m_popupFrame->setFrameStyle(QFrame::Box);
    m_popupFrame->setFrameShadow(QFrame::Plain);
con's avatar
con committed
223
224
225
226

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

227
228
229
230
    m_pager = new QWidget;
    QHBoxLayout *hbox = new QHBoxLayout(m_pager);
    hbox->setMargin(0);
    hbox->setSpacing(0);
231
    hbox->addWidget(upArrow);
232
233
    m_numberLabel = new QLabel;
    hbox->addWidget(m_numberLabel);
234
    hbox->addWidget(downArrow);
235

236
    QHBoxLayout *layout = new QHBoxLayout;
con's avatar
con committed
237
    layout->setMargin(0);
238
239
240
    layout->setSpacing(0);
    layout->addWidget(m_pager);
    layout->addWidget(this);
con's avatar
con committed
241
242
    m_popupFrame->setLayout(layout);

243
244
    connect(upArrow, SIGNAL(clicked()), SLOT(previousPage()));
    connect(downArrow, SIGNAL(clicked()), SLOT(nextPage()));
245
246

    QPalette pal = m_popupFrame->palette();
con's avatar
con committed
247
248
    setAutoFillBackground(true);
    pal.setColor(QPalette::Background, QColor(255, 255, 220));
249
    m_popupFrame->setPalette(pal);
con's avatar
con committed
250
251
252

    setTextFormat(Qt::RichText);
    setMargin(1);
253
254

    qApp->installEventFilter(this);
con's avatar
con committed
255
256
}

257
void FunctionArgumentWidget::showFunctionHint(QList<Function *> functionSymbols,
258
259
                                              const LookupContext &context,
                                              int startPosition)
con's avatar
con committed
260
{
261
262
    Q_ASSERT(!functionSymbols.isEmpty());

263
264
265
    if (m_startpos == startPosition)
        return;

266
    m_pager->setVisible(functionSymbols.size() > 1);
267

268
    m_items = functionSymbols;
269
    m_context = context;
270
    m_startpos = startPosition;
271
    m_current = 0;
272
    m_escapePressed = false;
con's avatar
con committed
273
274
275

    // update the text
    m_currentarg = -1;
276
    updateArgumentHighlight();
277

con's avatar
con committed
278
279
280
    m_popupFrame->show();
}

281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
void FunctionArgumentWidget::nextPage()
{
    m_current = (m_current + 1) % m_items.size();
    updateHintText();
}

void FunctionArgumentWidget::previousPage()
{
    if (m_current == 0)
        m_current = m_items.size() - 1;
    else
        --m_current;

    updateHintText();
}

297
void FunctionArgumentWidget::updateArgumentHighlight()
con's avatar
con committed
298
299
300
{
    int curpos = m_editor->position();
    if (curpos < m_startpos) {
301
        m_popupFrame->close();
con's avatar
con committed
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
        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)
326
        m_popupFrame->close();
con's avatar
con committed
327
328
329
330
331
}

bool FunctionArgumentWidget::eventFilter(QObject *obj, QEvent *e)
{
    switch (e->type()) {
332
333
334
335
336
    case QEvent::ShortcutOverride:
        if (static_cast<QKeyEvent*>(e)->key() == Qt::Key_Escape) {
            m_escapePressed = true;
        }
        break;
337
    case QEvent::KeyPress:
338
339
340
        if (static_cast<QKeyEvent*>(e)->key() == Qt::Key_Escape) {
            m_escapePressed = true;
        }
341
342
343
344
345
346
347
348
        if (m_items.size() > 1) {
            QKeyEvent *ke = static_cast<QKeyEvent*>(e);
            if (ke->key() == Qt::Key_Up) {
                previousPage();
                return true;
            } else if (ke->key() == Qt::Key_Down) {
                nextPage();
                return true;
con's avatar
con committed
349
            }
350
351
352
353
            return false;
        }
        break;
    case QEvent::KeyRelease:
354
        if (static_cast<QKeyEvent*>(e)->key() == Qt::Key_Escape && m_escapePressed) {
355
356
            m_popupFrame->close();
            return false;
con's avatar
con committed
357
        }
358
359
        updateArgumentHighlight();
        break;
con's avatar
con committed
360
361
    case QEvent::WindowDeactivate:
    case QEvent::FocusOut:
362
363
364
        if (obj != m_editor->widget())
            break;
        m_popupFrame->close();
365
        break;
con's avatar
con committed
366
367
368
    case QEvent::MouseButtonPress:
    case QEvent::MouseButtonRelease:
    case QEvent::MouseButtonDblClick:
369
370
371
    case QEvent::Wheel: {
            QWidget *widget = qobject_cast<QWidget *>(obj);
            if (! (widget == this || m_popupFrame->isAncestorOf(widget))) {
372
                m_popupFrame->close();
373
374
            }
        }
con's avatar
con committed
375
376
377
378
379
380
381
382
383
384
        break;
    default:
        break;
    }
    return false;
}

void FunctionArgumentWidget::updateHintText()
{
    Overview overview;
385
    overview.setRichText(true);
con's avatar
con committed
386
387
388
    overview.setShowReturnTypes(true);
    overview.setShowArgumentNames(true);
    overview.setMarkArgument(m_currentarg + 1);
389
    Function *f = currentFunction();
390

391
    setText(overview(f->type(), f->name()));
392
393
394
    m_numberLabel->setText(tr("%1 of %2").arg(m_current + 1).arg(m_items.size()));

    m_popupFrame->setFixedWidth(m_popupFrame->minimumSizeHint().width());
395
396
397

    const QDesktopWidget *desktop = QApplication::desktop();
#ifdef Q_OS_MAC
398
    const QRect screen = desktop->availableGeometry(desktop->screenNumber(m_editor->widget()));
399
#else
400
    const QRect screen = desktop->screenGeometry(desktop->screenNumber(m_editor->widget()));
401
402
403
404
405
406
407
408
409
410
#endif

    const QSize sz = m_popupFrame->sizeHint();
    QPoint pos = m_editor->cursorRect(m_startpos).topLeft();
    pos.setY(pos.y() - sz.height() - 1);

    if (pos.x() + sz.width() > screen.right())
        pos.setX(screen.right() - sz.width());

    m_popupFrame->move(pos);
con's avatar
con committed
411
412
}

413
CppCodeCompletion::CppCodeCompletion(CppModelManager *manager)
con's avatar
con committed
414
415
    : ICompletionCollector(manager),
      m_manager(manager),
416
      m_caseSensitivity(Qt::CaseSensitive),
417
      m_autoInsertBrackets(true),
con's avatar
con committed
418
419
      m_forcedCompletion(false),
      m_completionOperator(T_EOF_SYMBOL)
420
421
{
}
con's avatar
con committed
422
423

QIcon CppCodeCompletion::iconForSymbol(Symbol *symbol) const
424
425
426
427
428
429
430
431
432
433
434
435
436
437
{
    return m_icons.iconForSymbol(symbol);
}

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

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

438
bool CppCodeCompletion::autoInsertBrackets() const
439
{
440
    return m_autoInsertBrackets;
441
442
}

443
void CppCodeCompletion::setAutoInsertBrackets(bool autoInsertBrackets)
444
{
445
    m_autoInsertBrackets = autoInsertBrackets;
446
}
con's avatar
con committed
447

448
449
450
451
452
453
454
455
456
457
bool CppCodeCompletion::isPartialCompletionEnabled() const
{
    return m_partialCompletionEnabled;
}

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

con's avatar
con committed
458
459
460
461
462
463
464
465
466
467
468
469
/*
  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;
470
    int k = T_EOF_SYMBOL;
con's avatar
con committed
471
472

    if        (ch2 != QLatin1Char('.') && ch == QLatin1Char('.')) {
473
        k = T_DOT;
con's avatar
con committed
474
        --start;
475
476
477
    } else if (ch == QLatin1Char(',')) {
        k = T_COMMA;
        --start;
con's avatar
con committed
478
    } else if (wantFunctionCall        && ch == QLatin1Char('(')) {
479
        k = T_LPAREN;
con's avatar
con committed
480
        --start;
481
    } else if (ch3 != QLatin1Char(':') && ch2 == QLatin1Char(':') && ch == QLatin1Char(':')) {
482
        k = T_COLON_COLON;
con's avatar
con committed
483
484
        start -= 2;
    } else if (ch2 == QLatin1Char('-') && ch == QLatin1Char('>')) {
485
        k = T_ARROW;
con's avatar
con committed
486
487
        start -= 2;
    } else if (ch2 == QLatin1Char('.') && ch == QLatin1Char('*')) {
488
        k = T_DOT_STAR;
con's avatar
con committed
489
490
        start -= 2;
    } else if (ch3 == QLatin1Char('-') && ch2 == QLatin1Char('>') && ch == QLatin1Char('*')) {
491
        k = T_ARROW_STAR;
con's avatar
con committed
492
        start -= 3;
493
    } else if ((ch2.isNull() || ch2.isSpace()) && (ch == QLatin1Char('@') || ch == QLatin1Char('\\'))) {
494
495
        k = T_DOXY_COMMENT;
        --start;
con's avatar
con committed
496
497
    }

498
499
500
501
502
503
504
505
506
507
508
509
510
    if (start == pos)
        return start;

    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 (k == T_DOXY_COMMENT && tk.isNot(T_DOXY_COMMENT)) {
        k = T_EOF_SYMBOL;
        start = pos;
con's avatar
con committed
511
    }
512
513
514
515
516
    else if (tk.is(T_COMMENT) || tk.isLiteral()) {
        k = T_EOF_SYMBOL;
        start = pos;
    }

517
518
519
520
521
522
523
524
525
    if (k == T_LPAREN) {
        const QList<SimpleToken> &tokens = tokenUnderCursor.tokens();
        int i = 0;
        for (; i < tokens.size(); ++i) {
            const SimpleToken &token = tokens.at(i);
            if (token.position() == tk.position()) {
                if (i == 0) // no token on the left, but might be on a previous line
                    break;
                const SimpleToken &previousToken = tokens.at(i - 1);
526
527
                if (previousToken.is(T_IDENTIFIER) || previousToken.is(T_GREATER)
                    || previousToken.is(T_SIGNAL) || previousToken.is(T_SLOT))
528
529
530
531
532
533
534
535
536
537
                    break;
            }
        }

        if (i == tokens.size()) {
            k = T_EOF_SYMBOL;
            start = pos;
        }
    }

538
539
540
    if (kind)
        *kind = k;

con's avatar
con committed
541
542
543
    return start;
}

544
bool CppCodeCompletion::supportsEditor(TextEditor::ITextEditable *editor)
545
546
{ return m_manager->isCppEditor(editor); }

con's avatar
con committed
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
bool CppCodeCompletion::triggersCompletion(TextEditor::ITextEditable *editor)
{
    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;
564
565
    const int startOfName = findStartOfName();
    m_startPosition = startOfName;
con's avatar
con committed
566
567
    m_completionOperator = T_EOF_SYMBOL;

568
    int endOfOperator = m_startPosition;
con's avatar
con committed
569
570

    // Skip whitespace preceding this position
571
572
    while (editor->characterAt(endOfOperator - 1).isSpace())
        --endOfOperator;
con's avatar
con committed
573

574
575
576
    int endOfExpression = startOfOperator(editor, endOfOperator,
                                          &m_completionOperator,
                                          /*want function call =*/ true);
con's avatar
con committed
577
578
579
580
581
582
583
584

    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;

585
586
587
588
    if (m_completionOperator == T_DOXY_COMMENT) {
        for (int i = 1; i < T_DOXY_LAST_TAG; ++i) {
            TextEditor::CompletionItem item(this);
            item.m_text.append(QString::fromLatin1(doxygenTagSpell(i)));
589
            item.m_icon = m_icons.keywordIcon();
590
591
592
593
594
595
            m_completions.append(item);
        }

        return m_startPosition;
    }

596
597
    ExpressionUnderCursor expressionUnderCursor;
    QTextCursor tc(edit->document());
598

599
    if (m_completionOperator == T_COMMA) {
con's avatar
con committed
600
        tc.setPosition(endOfExpression);
601
602
603
604
605
606
607
608
609
610
        const int start = expressionUnderCursor.startOfFunctionCall(tc);
        if (start != -1) {
            endOfExpression = start;
            m_startPosition = start + 1;
            m_completionOperator = T_LPAREN;
        }
    }

    QString expression;
    tc.setPosition(endOfExpression);
611

612
    if (m_completionOperator) {
con's avatar
con committed
613
        expression = expressionUnderCursor(tc);
614

con's avatar
con committed
615
616
617
        if (m_completionOperator == T_LPAREN) {
            if (expression.endsWith(QLatin1String("SIGNAL")))
                m_completionOperator = T_SIGNAL;
618

con's avatar
con committed
619
620
            else if (expression.endsWith(QLatin1String("SLOT")))
                m_completionOperator = T_SLOT;
621

622
623
624
625
            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;
626
                m_startPosition = startOfName;
627
            }
con's avatar
con committed
628
629
630
        }
    }

631
    //qDebug() << "***** expression:" << expression;
con's avatar
con committed
632

633
634
635
    const Snapshot snapshot = m_manager->snapshot();

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

638
        typeOfExpression.setSnapshot(m_manager->snapshot());
con's avatar
con committed
639

640
641
        QList<TypeOfExpression::Result> resolvedTypes = typeOfExpression(expression, thisDocument, symbol,
                                                                         TypeOfExpression::Preprocess);
con's avatar
con committed
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
        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();
        }

Roberto Raggi's avatar
Cleanup    
Roberto Raggi committed
670
671
        if (! resolvedTypes.isEmpty()) {
            if (m_completionOperator == T_LPAREN && completeConstructorOrFunction(resolvedTypes)) {
con's avatar
con committed
672
                return m_startPosition;
Roberto Raggi's avatar
Cleanup    
Roberto Raggi committed
673

674
            } else if ((m_completionOperator == T_DOT || m_completionOperator == T_ARROW) &&
675
                      completeMember(resolvedTypes, context)) {
con's avatar
con committed
676
                return m_startPosition;
Roberto Raggi's avatar
Cleanup    
Roberto Raggi committed
677

678
            } else if (m_completionOperator == T_COLON_COLON && completeScope(resolvedTypes, context)) {
con's avatar
con committed
679
                return m_startPosition;
Roberto Raggi's avatar
Cleanup    
Roberto Raggi committed
680
681

            } else if (m_completionOperator == T_SIGNAL      && completeSignal(resolvedTypes, context)) {
con's avatar
con committed
682
                return m_startPosition;
Roberto Raggi's avatar
Cleanup    
Roberto Raggi committed
683
684

            } else if (m_completionOperator == T_SLOT        && completeSlot(resolvedTypes, context)) {
con's avatar
con committed
685
686
687
                return m_startPosition;
            }
        }
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705

        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) {
706
                if (result.first->isClassType()) {
Roberto Raggi's avatar
Cleanup    
Roberto Raggi committed
707
                    if (completeConstructorOrFunction(results))
708
709
710
711
712
                        return m_startPosition;
                    break;
                }
            }
        }
con's avatar
con committed
713
714
715
716
717
718
    }

    // nothing to do.
    return -1;
}

Roberto Raggi's avatar
Cleanup    
Roberto Raggi committed
719
bool CppCodeCompletion::completeConstructorOrFunction(const QList<TypeOfExpression::Result> &results)
con's avatar
con committed
720
{
721
722
    QList<Function *> functions;

Roberto Raggi's avatar
Roberto Raggi committed
723
724
725
726
    foreach (const TypeOfExpression::Result &result, results) {
        FullySpecifiedType exprTy = result.first;

        if (Class *klass = exprTy->asClassType()) {
727
728
729
730
            Name *className = klass->name();
            if (! className)
                continue; // nothing to do for anonymoous classes.

Roberto Raggi's avatar
Roberto Raggi committed
731
732
            for (unsigned i = 0; i < klass->memberCount(); ++i) {
                Symbol *member = klass->memberAt(i);
733
734
735
736
737
738
739
740
741
742
743
744
745
                Name *memberName = member->name();

                if (! memberName)
                    continue; // skip anonymous member.

                else if (memberName->isQualifiedNameId())
                    continue; // skip

                if (Function *funTy = member->type()->asFunctionType()) {
                    if (memberName->isEqualTo(className)) {
                        // it's a ctor.
                        functions.append(funTy);
                    }
Roberto Raggi's avatar
Roberto Raggi committed
746
                }
747
            }
Roberto Raggi's avatar
Roberto Raggi committed
748
749

            break;
750
        }
Roberto Raggi's avatar
Roberto Raggi committed
751
752
    }

753
    if (functions.isEmpty()) {
Roberto Raggi's avatar
Roberto Raggi committed
754
        foreach (const TypeOfExpression::Result &p, results) {
con's avatar
con committed
755
            FullySpecifiedType ty = p.first;
Roberto Raggi's avatar
Roberto Raggi committed
756

757
            if (Function *fun = ty->asFunctionType()) {
con's avatar
con committed
758

759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
                if (! fun->name())
                    continue;
                else if (! functions.isEmpty() && functions.first()->scope() != fun->scope())
                    continue; // skip fun, it's an hidden declaration.

                Name *name = fun->name();
                if (QualifiedNameId *q = fun->name()->asQualifiedNameId())
                    name = q->unqualifiedNameId();

                bool newOverload = true;

                foreach (Function *f, functions) {
                    if (fun->isEqualTo(f)) {
                        newOverload = false;
                        break;
                    }
con's avatar
con committed
775
                }
776
777
778

                if (newOverload)
                    functions.append(fun);
con's avatar
con committed
779
780
            }
        }
781

con's avatar
con committed
782
783
    }

784
    if (! functions.isEmpty()) {
785

786
787
788
        // Recreate if necessary
        if (!m_functionArgumentWidget)
            m_functionArgumentWidget = new FunctionArgumentWidget;
789

790
791
792
        m_functionArgumentWidget->showFunctionHint(functions,
                                                   typeOfExpression.lookupContext(),
                                                   m_startPosition);
793
794
795
    }

    return false;
con's avatar
con committed
796
797
}

798
bool CppCodeCompletion::completeMember(const QList<TypeOfExpression::Result> &results,
con's avatar
con committed
799
800
                                       const LookupContext &context)
{
801
    if (results.isEmpty())
Roberto Raggi's avatar
Roberto Raggi committed
802
        return false;
con's avatar
con committed
803

804
    TypeOfExpression::Result result = results.first();
con's avatar
con committed
805
806
807
    QList<Symbol *> classObjectCandidates;

    if (m_completionOperator == T_ARROW)  {
808
        FullySpecifiedType ty = result.first;
con's avatar
con committed
809
810
811
812

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

813
        if (Class *classTy = ty->asClassType()) {
814
815
816
            Symbol *symbol = result.second;
            if (symbol && ! symbol->isClass())
                classObjectCandidates.append(classTy);
817
        } else if (NamedType *namedTy = ty->asNamedType()) {
818
819
820
821
822
823
824
825
826
827
828
829
            // ### 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
830
831
        if (NamedType *namedTy = ty->asNamedType()) {
            ResolveExpression resolveExpression(context);
832
            ResolveClass resolveClass;
con's avatar
con committed
833

834
            const QList<Symbol *> candidates = resolveClass(result, context);
con's avatar
con committed
835
836
            foreach (Symbol *classObject, candidates) {
                const QList<TypeOfExpression::Result> overloads =
837
                        resolveExpression.resolveArrowOperator(result, namedTy,
con's avatar
con committed
838
839
840
841
                                                               classObject->asClass());

                foreach (TypeOfExpression::Result r, overloads) {
                    FullySpecifiedType ty = r.first;
842
                    Function *funTy = ty->asFunctionType();
con's avatar
con committed
843
844
845
846
847
848
849
850
851
852
853
                    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 =
854
                                    resolveClass(namedTy, result, context);
con's avatar
con committed
855
856
857
858
859
860
861
862
863
864
865

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

868
869
                const QList<Symbol *> classes = resolveClass(namedTy, result,
                                                             context);
con's avatar
con committed
870
871
872
873
874

                foreach (Symbol *c, classes) {
                    if (! classObjectCandidates.contains(c))
                        classObjectCandidates.append(c);
                }
875
            } else if (Class *classTy = ptrTy->elementType()->asClassType()) {
876
877
878
879
                // typedef struct { int x } *Ptr;
                // Ptr p;
                // p->
                classObjectCandidates.append(classTy);
con's avatar
con committed
880
881
882
            }
        }
    } else if (m_completionOperator == T_DOT) {
883
        FullySpecifiedType ty = result.first;
con's avatar
con committed
884
885
886
887
888

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

        NamedType *namedTy = 0;
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906

        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
907
        if (PointerType *ptrTy = ty->asPointerType()) {
908
909
910
911
912
913
914
915
            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();
            }
916
        } else if (Class *classTy = ty->asClassType()) {
917
918
919
            Symbol *symbol = result.second;
            if (symbol && ! symbol->isClass())
                classObjectCandidates.append(classTy);
con's avatar
con committed
920
921
922
        } else {
            namedTy = ty->asNamedType();
            if (! namedTy) {
923
                Function *fun = ty->asFunctionType();
con's avatar
con committed
924
925
926
927
928
929
                if (fun && (fun->scope()->isBlockScope() || fun->scope()->isNamespaceScope()))
                    namedTy = fun->returnType()->asNamedType();
            }
        }

        if (namedTy) {
930
            ResolveClass resolveClass;
931
932
            const QList<Symbol *> symbols = resolveClass(namedTy, result,
                                                         context);
Roberto Raggi's avatar
Roberto Raggi committed
933
934
935
936
937
            foreach (Symbol *symbol, symbols) {
                if (classObjectCandidates.contains(symbol))
                    continue;
                if (Class *klass = symbol->asClass())
                    classObjectCandidates.append(klass);
con's avatar
con committed
938
939
940
941
942
943
944
945
946
947
948
            }
        }
    }

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

    return false;
}

949
bool CppCodeCompletion::completeScope(const QList<TypeOfExpression::Result> &results,
con's avatar
con committed
950
951
                                      const LookupContext &context)
{
952
    QList<Symbol *> classes, namespaces;
953

954
    foreach (TypeOfExpression::Result result, results) {
955
956
        FullySpecifiedType ty = result.first;

957
958
        if (Class *classTy = ty->asClassType())
            classes.append(classTy);
con's avatar
con committed
959

960
961
        else if (Namespace *namespaceTy = ty->asNamespaceType())
            namespaces.append(namespaceTy);
con's avatar
con committed
962
963
    }

964
965
966
967
968
969
    if (! classes.isEmpty())
        completeClass(classes, context);

    else if (! namespaces.isEmpty() && m_completions.isEmpty())
        completeNamespace(namespaces, context);

con's avatar
con committed
970
971
972
973
974
975
    return ! m_completions.isEmpty();
}

void CppCodeCompletion::addKeywords()
{
    // keyword completion items.
976
    for (int i = T_FIRST_KEYWORD; i < T_FIRST_OBJC_AT_KEYWORD; ++i) {
con's avatar
con committed
977
978
979
980
981
982
983
984
985
986
        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)
{
    QSet<QString> processed;
987
988
989
990
    QSet<QString> definedMacros;

    addMacros_helper(context, context.thisDocument()->fileName(),
                     &processed, &definedMacros);
con's avatar
con committed
991

992
    foreach (const QString &macroName, definedMacros) {
con's avatar
con committed
993
        TextEditor::CompletionItem item(this);
994
        item.m_text = macroName;
con's avatar
con committed
995
996
997
998
999
        item.m_icon = m_icons.macroIcon();
        m_completions.append(item);
    }
}

1000
void CppCodeCompletion::addMacros_helper(const LookupContext &context,