cppcodecompletion.cpp 54.3 KB
Newer Older
1
/**************************************************************************
con's avatar
con committed
2
3
4
**
** This file is part of Qt Creator
**
hjk's avatar
hjk committed
5
** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
con's avatar
con committed
6
**
7
** Contact: Nokia Corporation (qt-info@nokia.com)
con's avatar
con committed
8
**
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
** If you are unsure which license is appropriate for your use, please
hjk's avatar
hjk committed
26
** contact the sales department at http://qt.nokia.com/contact.
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"
33
#include "cpptoolsconstants.h"
Roberto Raggi's avatar
Roberto Raggi committed
34
#include "cpptoolseditorsupport.h"
con's avatar
con committed
35
36
37
38
39
40
41
42
43
44
45
46

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

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

#include <coreplugin/icore.h>
58
#include <coreplugin/mimedatabase.h>
con's avatar
con committed
59
#include <coreplugin/editormanager/editormanager.h>
60
#include <texteditor/completionsettings.h>
con's avatar
con committed
61
62
63
#include <texteditor/itexteditor.h>
#include <texteditor/itexteditable.h>
#include <texteditor/basetexteditor.h>
64
#include <projectexplorer/projectexplorer.h>
65
66

#include <utils/faketooltip.h>
67
#include <utils/qtcassert.h>
con's avatar
con committed
68
69
70
71
72

#include <QtCore/QDebug>
#include <QtCore/QMap>
#include <QtCore/QFile>
#include <QtGui/QAction>
73
#include <QtGui/QApplication>
74
#include <QtGui/QDesktopWidget>
con's avatar
con committed
75
76
#include <QtGui/QKeyEvent>
#include <QtGui/QLabel>
77
#include <QtGui/QStyle>
78
#include <QtGui/QTextDocument> // Qt::escape()
79
#include <QtGui/QToolButton>
con's avatar
con committed
80
81
#include <QtGui/QVBoxLayout>

82
83
84
85
namespace {
    const bool debug = ! qgetenv("CPLUSPLUS_DEBUG").isEmpty();
}

con's avatar
con committed
86
87
88
89
90
using namespace CPlusPlus;

namespace CppTools {
namespace Internal {

91
92
class FunctionArgumentWidget : public QLabel
{
93
94
    Q_OBJECT

con's avatar
con committed
95
public:
96
    FunctionArgumentWidget();
97
    void showFunctionHint(QList<Function *> functionSymbols,
98
                          const LookupContext &context,
99
                          int startPosition);
con's avatar
con committed
100
101
102
103

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

104
105
106
107
private slots:
    void nextPage();
    void previousPage();

con's avatar
con committed
108
private:
109
    void updateArgumentHighlight();
con's avatar
con committed
110
111
    void updateHintText();

112
113
114
    Function *currentFunction() const
    { return m_items.at(m_current); }

con's avatar
con committed
115
116
    int m_startpos;
    int m_currentarg;
117
    int m_current;
118
    bool m_escapePressed;
con's avatar
con committed
119
120
121

    TextEditor::ITextEditor *m_editor;

122
    QWidget *m_pager;
123
    QLabel *m_numberLabel;
124
    Utils::FakeToolTip *m_popupFrame;
125
    QList<Function *> m_items;
126
    LookupContext m_context;
con's avatar
con committed
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
};

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)
159
            _item.data = QVariant::fromValue(symbol);
con's avatar
con committed
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
        (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;
    }

Roberto Raggi's avatar
Roberto Raggi committed
179
    TextEditor::CompletionItem newCompletionItem(const Name *name)
con's avatar
con committed
180
181
    {
        TextEditor::CompletionItem item(_collector);
182
183
        item.text = overview.prettyName(name);
        item.icon = _collector->iconForSymbol(_symbol);
con's avatar
con committed
184
185
186
        return item;
    }

Roberto Raggi's avatar
Roberto Raggi committed
187
    virtual void visit(const NameId *name)
con's avatar
con committed
188
189
    { _item = newCompletionItem(name); }

Roberto Raggi's avatar
Roberto Raggi committed
190
    virtual void visit(const TemplateNameId *name)
con's avatar
con committed
191
192
    {
        _item = newCompletionItem(name);
193
        _item.text = QLatin1String(name->identifier()->chars());
con's avatar
con committed
194
195
    }

Roberto Raggi's avatar
Roberto Raggi committed
196
    virtual void visit(const DestructorNameId *name)
con's avatar
con committed
197
198
    { _item = newCompletionItem(name); }

Roberto Raggi's avatar
Roberto Raggi committed
199
    virtual void visit(const OperatorNameId *name)
con's avatar
con committed
200
201
    { _item = newCompletionItem(name); }

Roberto Raggi's avatar
Roberto Raggi committed
202
    virtual void visit(const ConversionNameId *name)
con's avatar
con committed
203
204
    { _item = newCompletionItem(name); }

Roberto Raggi's avatar
Roberto Raggi committed
205
    virtual void visit(const QualifiedNameId *name)
con's avatar
con committed
206
207
208
    { _item = newCompletionItem(name->unqualifiedNameId()); }
};

209
210
211
212
213
214
215
216
struct CompleteFunctionDeclaration
{
    explicit CompleteFunctionDeclaration(Function *f = 0)
        : function(f)
    {}

    Function *function;
};
con's avatar
con committed
217
218
219
220
221
222

} // namespace Internal
} // namespace CppTools

using namespace CppTools::Internal;

223
Q_DECLARE_METATYPE(CompleteFunctionDeclaration)
224
225


226
FunctionArgumentWidget::FunctionArgumentWidget():
227
    m_startpos(-1),
228
229
    m_current(0),
    m_escapePressed(false)
con's avatar
con committed
230
{
231
    QObject *editorObject = Core::EditorManager::instance()->currentEditor();
con's avatar
con committed
232
233
    m_editor = qobject_cast<TextEditor::ITextEditor *>(editorObject);

234
    m_popupFrame = new Utils::FakeToolTip(m_editor->widget());
con's avatar
con committed
235

236
237
238
239
    QToolButton *downArrow = new QToolButton;
    downArrow->setArrowType(Qt::DownArrow);
    downArrow->setFixedSize(16, 16);
    downArrow->setAutoRaise(true);
240

241
242
243
244
    QToolButton *upArrow = new QToolButton;
    upArrow->setArrowType(Qt::UpArrow);
    upArrow->setFixedSize(16, 16);
    upArrow->setAutoRaise(true);
245

con's avatar
con committed
246
247
248
    setParent(m_popupFrame);
    setFocusPolicy(Qt::NoFocus);

249
250
251
252
    m_pager = new QWidget;
    QHBoxLayout *hbox = new QHBoxLayout(m_pager);
    hbox->setMargin(0);
    hbox->setSpacing(0);
253
    hbox->addWidget(upArrow);
254
255
    m_numberLabel = new QLabel;
    hbox->addWidget(m_numberLabel);
256
    hbox->addWidget(downArrow);
257

258
    QHBoxLayout *layout = new QHBoxLayout;
con's avatar
con committed
259
    layout->setMargin(0);
260
261
262
    layout->setSpacing(0);
    layout->addWidget(m_pager);
    layout->addWidget(this);
con's avatar
con committed
263
264
    m_popupFrame->setLayout(layout);

265
266
    connect(upArrow, SIGNAL(clicked()), SLOT(previousPage()));
    connect(downArrow, SIGNAL(clicked()), SLOT(nextPage()));
267

con's avatar
con committed
268
    setTextFormat(Qt::RichText);
269
270

    qApp->installEventFilter(this);
con's avatar
con committed
271
272
}

273
void FunctionArgumentWidget::showFunctionHint(QList<Function *> functionSymbols,
274
                                              const LookupContext &context,
275
                                              int startPosition)
con's avatar
con committed
276
{
277
278
    Q_ASSERT(!functionSymbols.isEmpty());

279
280
281
    if (m_startpos == startPosition)
        return;

282
    m_pager->setVisible(functionSymbols.size() > 1);
283

284
    m_items = functionSymbols;
285
    m_context = context;
286
    m_startpos = startPosition;
287
    m_current = 0;
288
    m_escapePressed = false;
con's avatar
con committed
289
290
291

    // update the text
    m_currentarg = -1;
292
    updateArgumentHighlight();
293

con's avatar
con committed
294
295
296
    m_popupFrame->show();
}

297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
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();
}

313
void FunctionArgumentWidget::updateArgumentHighlight()
con's avatar
con committed
314
315
316
{
    int curpos = m_editor->position();
    if (curpos < m_startpos) {
317
        m_popupFrame->close();
con's avatar
con committed
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
        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)
342
        m_popupFrame->close();
con's avatar
con committed
343
344
345
346
347
}

bool FunctionArgumentWidget::eventFilter(QObject *obj, QEvent *e)
{
    switch (e->type()) {
348
349
350
351
352
    case QEvent::ShortcutOverride:
        if (static_cast<QKeyEvent*>(e)->key() == Qt::Key_Escape) {
            m_escapePressed = true;
        }
        break;
353
    case QEvent::KeyPress:
354
355
356
        if (static_cast<QKeyEvent*>(e)->key() == Qt::Key_Escape) {
            m_escapePressed = true;
        }
357
358
359
360
361
362
363
364
        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
365
            }
366
367
368
369
            return false;
        }
        break;
    case QEvent::KeyRelease:
370
        if (static_cast<QKeyEvent*>(e)->key() == Qt::Key_Escape && m_escapePressed) {
371
372
            m_popupFrame->close();
            return false;
con's avatar
con committed
373
        }
374
375
        updateArgumentHighlight();
        break;
con's avatar
con committed
376
377
    case QEvent::WindowDeactivate:
    case QEvent::FocusOut:
378
379
380
        if (obj != m_editor->widget())
            break;
        m_popupFrame->close();
381
        break;
con's avatar
con committed
382
383
384
    case QEvent::MouseButtonPress:
    case QEvent::MouseButtonRelease:
    case QEvent::MouseButtonDblClick:
385
386
387
    case QEvent::Wheel: {
            QWidget *widget = qobject_cast<QWidget *>(obj);
            if (! (widget == this || m_popupFrame->isAncestorOf(widget))) {
388
                m_popupFrame->close();
389
390
            }
        }
con's avatar
con committed
391
392
393
394
395
396
397
398
399
400
401
402
        break;
    default:
        break;
    }
    return false;
}

void FunctionArgumentWidget::updateHintText()
{
    Overview overview;
    overview.setShowReturnTypes(true);
    overview.setShowArgumentNames(true);
403
    overview.setMarkedArgument(m_currentarg + 1);
404
    Function *f = currentFunction();
405

406
407
408
409
410
411
412
413
414
415
416
417
    const QString prettyMethod = overview(f->type(), f->name());
    const int begin = overview.markedArgumentBegin();
    const int end = overview.markedArgumentEnd();

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

418
419
420
    m_numberLabel->setText(tr("%1 of %2").arg(m_current + 1).arg(m_items.size()));

    m_popupFrame->setFixedWidth(m_popupFrame->minimumSizeHint().width());
421
422

    const QDesktopWidget *desktop = QApplication::desktop();
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
423
#ifdef Q_WS_MAC
424
    const QRect screen = desktop->availableGeometry(desktop->screenNumber(m_editor->widget()));
425
#else
426
    const QRect screen = desktop->screenGeometry(desktop->screenNumber(m_editor->widget()));
427
428
429
430
431
432
433
434
435
436
#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
437
438
}

439
CppCodeCompletion::CppCodeCompletion(CppModelManager *manager)
con's avatar
con committed
440
441
    : ICompletionCollector(manager),
      m_manager(manager),
442
443
      m_editor(0),
      m_startPosition(-1),
con's avatar
con committed
444
      m_forcedCompletion(false),
445
446
      m_completionOperator(T_EOF_SYMBOL),
      m_objcEnabled(true)
447
448
{
}
con's avatar
con committed
449
450

QIcon CppCodeCompletion::iconForSymbol(Symbol *symbol) const
451
452
453
454
{
    return m_icons.iconForSymbol(symbol);
}

con's avatar
con committed
455
/*
456
  Searches backwards for an access operator.
con's avatar
con committed
457
458
459
460
461
462
463
464
465
466
*/
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;
467
    int completionKind = T_EOF_SYMBOL;
con's avatar
con committed
468

469
470
471
    switch (ch.toLatin1()) {
    case '.':
        if (ch2 != QLatin1Char('.')) {
472
            completionKind = T_DOT;
473
474
475
476
            --start;
        }
        break;
    case ',':
477
        completionKind = T_COMMA;
478
        --start;
479
480
481
        break;
    case '(':
        if (wantFunctionCall) {
482
            completionKind = T_LPAREN;
483
484
485
486
487
            --start;
        }
        break;
    case ':':
        if (ch3 != QLatin1Char(':') && ch2 == QLatin1Char(':')) {
488
            completionKind = T_COLON_COLON;
489
490
491
492
493
            start -= 2;
        }
        break;
    case '>':
        if (ch2 == QLatin1Char('-')) {
494
            completionKind = T_ARROW;
495
496
497
498
499
            start -= 2;
        }
        break;
    case '*':
        if (ch2 == QLatin1Char('.')) {
500
            completionKind = T_DOT_STAR;
501
502
            start -= 2;
        } else if (ch3 == QLatin1Char('-') && ch2 == QLatin1Char('>')) {
503
            completionKind = T_ARROW_STAR;
504
505
506
507
508
509
            start -= 3;
        }
        break;
    case '\\':
    case '@':
        if (ch2.isNull() || ch2.isSpace()) {
510
            completionKind = T_DOXY_COMMENT;
511
512
513
514
            --start;
        }
        break;
    case '<':
515
        completionKind = T_ANGLE_STRING_LITERAL;
516
        --start;
517
518
        break;
    case '"':
519
        completionKind = T_STRING_LITERAL;
520
        --start;
521
522
        break;
    case '/':
523
        completionKind = T_SLASH;
524
        --start;
525
        break;
con's avatar
con committed
526
527
    }

528
529
530
531
532
533
534
    if (start == pos)
        return start;

    TextEditor::BaseTextEditor *edit = qobject_cast<TextEditor::BaseTextEditor *>(editor->widget());
    QTextCursor tc(edit->textCursor());
    tc.setPosition(pos);

535
    // Include completion: make sure the quote character is the first one on the line
536
    if (completionKind == T_STRING_LITERAL) {
537
538
539
540
        QTextCursor s = tc;
        s.movePosition(QTextCursor::StartOfLine, QTextCursor::KeepAnchor);
        QString sel = s.selectedText();
        if (sel.indexOf(QLatin1Char('"')) < sel.length() - 1) {
541
            completionKind = T_EOF_SYMBOL;
542
543
544
545
            start = pos;
        }
    }

546
    if (completionKind == T_COMMA) {
547
548
        ExpressionUnderCursor expressionUnderCursor;
        if (expressionUnderCursor.startOfFunctionCall(tc) == -1) {
549
            completionKind = T_EOF_SYMBOL;
550
551
552
553
            start = pos;
        }
    }

554
555
556
    static CPlusPlus::TokenUnderCursor tokenUnderCursor;
    const SimpleToken tk = tokenUnderCursor(tc);

557
558
    if (completionKind == T_DOXY_COMMENT && !(tk.is(T_DOXY_COMMENT) || tk.is(T_CPP_DOXY_COMMENT))) {
        completionKind = T_EOF_SYMBOL;
559
        start = pos;
con's avatar
con committed
560
    }
561
    // Don't complete in comments or strings, but still check for include completion
562
563
564
565
566
    else if (tk.is(T_COMMENT) || tk.is(T_CPP_COMMENT) ||
             (tk.isLiteral() && (completionKind != T_STRING_LITERAL
                                 && completionKind != T_ANGLE_STRING_LITERAL
                                 && completionKind != T_SLASH))) {
        completionKind = T_EOF_SYMBOL;
567
568
569
        start = pos;
    }
    // Include completion: can be triggered by slash, but only in a string
570
571
    else if (completionKind == T_SLASH && (tk.isNot(T_STRING_LITERAL) && tk.isNot(T_ANGLE_STRING_LITERAL))) {
        completionKind = T_EOF_SYMBOL;
572
573
        start = pos;
    }
574
    else if (completionKind == T_LPAREN) {
575
576
577
578
579
580
581
582
        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);
583
584
                if (previousToken.is(T_IDENTIFIER) || previousToken.is(T_GREATER)
                    || previousToken.is(T_SIGNAL) || previousToken.is(T_SLOT))
585
586
587
588
589
                    break;
            }
        }

        if (i == tokens.size()) {
590
            completionKind = T_EOF_SYMBOL;
591
592
593
            start = pos;
        }
    }
594
    // Check for include preprocessor directive
595
    else if (completionKind == T_STRING_LITERAL || completionKind == T_ANGLE_STRING_LITERAL || completionKind == T_SLASH) {
596
        bool include = false;
597
598
599
600
601
602
603
604
605
        const QList<SimpleToken> &tokens = tokenUnderCursor.tokens();
        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))) {
                QStringRef directive = tokens.at(1).text();
                if (directive == QLatin1String("include") ||
                    directive == QLatin1String("include_next") ||
                    directive == QLatin1String("import")) {
                    include = true;
606
607
608
609
610
                }
            }
        }

        if (!include) {
611
            completionKind = T_EOF_SYMBOL;
612
613
614
615
            start = pos;
        }
    }

616
    if (kind)
617
        *kind = completionKind;
618

con's avatar
con committed
619
620
621
    return start;
}

622
bool CppCodeCompletion::supportsEditor(TextEditor::ITextEditable *editor)
623
624
{ return m_manager->isCppEditor(editor); }

625
626
627
628
629
630
TextEditor::ITextEditable *CppCodeCompletion::editor() const
{ return m_editor; }

int CppCodeCompletion::startPosition() const
{ return m_startPosition; }

con's avatar
con committed
631
632
633
bool CppCodeCompletion::triggersCompletion(TextEditor::ITextEditable *editor)
{
    const int pos = editor->position();
634
    if (startOfOperator(editor, pos, /*token =*/ 0, /*want function call=*/ true) != pos) {
con's avatar
con committed
635
        return true;
636
    }
con's avatar
con committed
637
638
639
640
641
642
643
644
645
646
647

    return false;
}

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

    m_editor = editor;
648

649
650
    const int startOfName = findStartOfName();
    m_startPosition = startOfName;
con's avatar
con committed
651
652
    m_completionOperator = T_EOF_SYMBOL;

653
    int endOfOperator = m_startPosition;
con's avatar
con committed
654
655

    // Skip whitespace preceding this position
656
657
    while (editor->characterAt(endOfOperator - 1).isSpace())
        --endOfOperator;
con's avatar
con committed
658

659
660
661
    int endOfExpression = startOfOperator(editor, endOfOperator,
                                          &m_completionOperator,
                                          /*want function call =*/ true);
con's avatar
con committed
662
663
664
665
666
667
668
669

    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;

670
671
672
    if (m_completionOperator == T_DOXY_COMMENT) {
        for (int i = 1; i < T_DOXY_LAST_TAG; ++i) {
            TextEditor::CompletionItem item(this);
673
674
            item.text.append(QString::fromLatin1(doxygenTagSpell(i)));
            item.icon = m_icons.keywordIcon();
675
676
677
678
679
680
            m_completions.append(item);
        }

        return m_startPosition;
    }

681
682
683
684
685
686
687
688
689
690
691
692
    // Include completion
    if (m_completionOperator == T_STRING_LITERAL
        || m_completionOperator == T_ANGLE_STRING_LITERAL
        || m_completionOperator == T_SLASH) {

        QTextCursor c = edit->textCursor();
        c.setPosition(endOfExpression);
        if (completeInclude(c))
            m_startPosition = startOfName;
        return m_startPosition;
    }

693
694
    ExpressionUnderCursor expressionUnderCursor;
    QTextCursor tc(edit->document());
695

696
    if (m_completionOperator == T_COMMA) {
con's avatar
con committed
697
        tc.setPosition(endOfExpression);
698
        const int start = expressionUnderCursor.startOfFunctionCall(tc);
699
700
701
        if (start == -1) {
            m_completionOperator = T_EOF_SYMBOL;
            return -1;
702
        }
703
704
705
706

        endOfExpression = start;
        m_startPosition = start + 1;
        m_completionOperator = T_LPAREN;
707
708
709
710
    }

    QString expression;
    tc.setPosition(endOfExpression);
711

712
    if (m_completionOperator) {
con's avatar
con committed
713
        expression = expressionUnderCursor(tc);
714

con's avatar
con committed
715
716
717
        if (m_completionOperator == T_LPAREN) {
            if (expression.endsWith(QLatin1String("SIGNAL")))
                m_completionOperator = T_SIGNAL;
718

con's avatar
con committed
719
720
            else if (expression.endsWith(QLatin1String("SLOT")))
                m_completionOperator = T_SLOT;
721

722
723
724
725
            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;
726
                m_startPosition = startOfName;
727
            }
con's avatar
con committed
728
729
730
        }
    }

731
    //qDebug() << "***** expression:" << expression;
732
733
    return startCompletionInternal(edit, fileName, line, column, expression, endOfExpression);
}
con's avatar
con committed
734

735
736
737
738
739
740
741
int CppCodeCompletion::startCompletionInternal(TextEditor::BaseTextEditor *edit,
                                               const QString fileName,
                                               unsigned line, unsigned column,
                                               const QString &expr,
                                               int endOfExpression)
{
    QString expression = expr.trimmed();
742
743
    const Snapshot snapshot = m_manager->snapshot();

744
745
746
    Document::Ptr thisDocument = snapshot.document(fileName);
    if (! thisDocument)
        return -1;
con's avatar
con committed
747

748
    typeOfExpression.init(thisDocument, snapshot);
749
    Symbol *lastVisibleSymbol = thisDocument->findSymbolAt(line, column);
con's avatar
con committed
750

751
752
753
    if (expression.isEmpty()) {
        if (m_completionOperator == T_EOF_SYMBOL || m_completionOperator == T_COLON_COLON)
            return globalCompletion(lastVisibleSymbol, thisDocument, snapshot);
con's avatar
con committed
754

755
        else if (m_completionOperator == T_SIGNAL || m_completionOperator == T_SLOT) {
con's avatar
con committed
756
757
758
            // Apply signal/slot completion on 'this'
            expression = QLatin1String("this");
        }
759
    }
con's avatar
con committed
760

761
762
    Scope *scope = thisDocument->scopeAt(line, column);
    Q_ASSERT(scope != 0);
Roberto Raggi's avatar
Cleanup  
Roberto Raggi committed
763

764
765
766
    if (debug)
        qDebug() << "scope:" << scope->owner()->fileName() << scope->owner()->line() << scope->owner()->column();

767
    QList<LookupItem> results = typeOfExpression(expression, scope, TypeOfExpression::Preprocess);
768
769
770
771

    if (debug)
        qDebug() << "got:" << results.size() << "results";

772
    LookupContext context = typeOfExpression.lookupContext();
Roberto Raggi's avatar
Cleanup  
Roberto Raggi committed
773

774
775
776
777
    if (results.isEmpty()) {
        if (m_completionOperator == T_SIGNAL || m_completionOperator == T_SLOT) {
            if (! (expression.isEmpty() || expression == QLatin1String("this"))) {
                expression = QLatin1String("this");
778
                results = typeOfExpression(expression, scope);
779
            }
Roberto Raggi's avatar
Cleanup  
Roberto Raggi committed
780

781
782
            if (results.isEmpty())
                return -1;
Roberto Raggi's avatar
Cleanup  
Roberto Raggi committed
783

784
            context = typeOfExpression.lookupContext();
785

786
        } else if (m_completionOperator == T_LPAREN) {
787
788
789
790
791
792
793
794
            // 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);
795

796
            ExpressionUnderCursor expressionUnderCursor;
797
            const QString baseExpression = expressionUnderCursor(tc);
798
799

            // Resolve the type of this expression
800
            const QList<LookupItem> results =
801
                    typeOfExpression(baseExpression, scope,
802
                                     TypeOfExpression::Preprocess);
803
804

            // If it's a class, add completions for the constructors
805
806
            foreach (const LookupItem &result, results) {
                if (result.type()->isClassType()) {
807
                    if (completeConstructorOrFunction(results, context, endOfExpression, true))
808
                        return m_startPosition;
809

810
811
812
                    break;
                }
            }
813
814
815
816
817
818
            return -1;

        } else {
            // nothing to do.
            return -1;

819
        }
con's avatar
con committed
820
821
    }

822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
    switch (m_completionOperator) {
    case T_LPAREN:
        if (completeConstructorOrFunction(results, context, endOfExpression, false))
            return m_startPosition;
        break;

    case T_DOT:
    case T_ARROW:
        if (completeMember(results, context))
            return m_startPosition;
        break;

    case T_COLON_COLON:
        if (completeScope(results, context))
            return m_startPosition;
        break;

    case T_SIGNAL:
        if (completeSignal(results, context))
            return m_startPosition;
        break;

    case T_SLOT:
        if (completeSlot(results, context))
            return m_startPosition;
        break;

    default:
        break;
    } // end of switch

con's avatar
con committed
853
854
855
856
    // nothing to do.
    return -1;
}

857
858
859
860
861
862
863
864
865
866
int CppCodeCompletion::globalCompletion(Symbol *lastVisibleSymbol,
                                        Document::Ptr thisDocument,
                                        const Snapshot &snapshot)
{
    if (m_completionOperator == T_EOF_SYMBOL) {
        addKeywords();
        addMacros(thisDocument->fileName(), snapshot);
    }

    Document::Ptr exprDoc = Document::create(QLatin1String("<expression>"));
867
    const DeprecatedLookupContext context(lastVisibleSymbol, exprDoc, thisDocument, snapshot);
868
869
870
871
872
873
874
875
876
877
878
    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;
}

879
bool CppCodeCompletion::completeConstructorOrFunction(const QList<LookupItem> &results,
880
                                                      const LookupContext &context,
881
                                                      int endOfExpression, bool toolTipOnly)
con's avatar
con committed
882
{
883
884
    QList<Function *> functions;

885
886
    foreach (const LookupItem &result, results) {
        FullySpecifiedType exprTy = result.type().simplified();
Roberto Raggi's avatar
Roberto Raggi committed
887
888

        if (Class *klass = exprTy->asClassType()) {
Roberto Raggi's avatar
Roberto Raggi committed
889
            const Name *className = klass->name();
890
891
892
            if (! className)
                continue; // nothing to do for anonymoous classes.

Roberto Raggi's avatar
Roberto Raggi committed
893
894
            for (unsigned i = 0; i < klass->memberCount(); ++i) {
                Symbol *member = klass->memberAt(i);
Roberto Raggi's avatar
Roberto Raggi committed
895
                const Name *memberName = member->name();
896
897
898
899
900
901
902
903
904
905
906
907

                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
908
                }
909
            }
Roberto Raggi's avatar
Roberto Raggi committed
910
911

            break;
912
        }
Roberto Raggi's avatar
Roberto Raggi committed
913
914
    }

915
    if (functions.isEmpty()) {
916
917
        foreach (const LookupItem &result, results) {
            FullySpecifiedType ty = result.type().simplified();
Roberto Raggi's avatar
Roberto Raggi committed
918

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

921
922
923
924
925
926
927
928
929
930
931
932
                if (! fun->name())
                    continue;
                else if (! functions.isEmpty() && functions.first()->scope() != fun->scope())
                    continue; // skip fun, it's an hidden declaration.

                bool newOverload = true;

                foreach (Function *f, functions) {
                    if (fun->isEqualTo(f)) {
                        newOverload = false;
                        break;
                    }
con's avatar
con committed
933
                }
934
935
936

                if (newOverload)
                    functions.append(fun);
con's avatar
con committed
937
938
            }
        }
939
940
941
    }

    if (functions.isEmpty()) {
Roberto Raggi's avatar
Roberto Raggi committed
942
        const Name *functionCallOp = context.control()->operatorNameId(OperatorNameId::FunctionCallOp);
943

944
945
        foreach (const LookupItem &result, results) {
            FullySpecifiedType ty = result.type().simplified();
946
            Scope *scope = result.scope();
947
948

            if (NamedType *namedTy = ty->asNamedType()) {
949
                if (ClassOrNamespace *b = context.lookupType(namedTy->name(), scope)) {
950
951
                    foreach (Symbol *overload, b->lookup(functionCallOp)) {
                        FullySpecifiedType overloadTy = overload->type().simplified();
952

953
954
                        if (Function *funTy = overloadTy->asFunctionType())
                            functions.append(funTy);
955
956
957
958
                    }
                }
            }
        }
con's avatar
con committed
959
960
    }

961
962
963
964
965
    // There are two different kinds of completion we want to provide:
    // 1. If this is a function call, we want to pop up a tooltip that shows the user
    // the possible overloads with their argument types and names.
    // 2. If this is a function definition, we want to offer autocompletion of
    // the function signature.
966

967
968
969
970
971
    // check if function signature autocompletion is appropriate
    if (! functions.isEmpty() && ! toolTipOnly) {

        // function definitions will only happen in class or namespace scope,
        // so get the current location's enclosing scope.
972
973
974
975
976
977
978
979
980

        // get current line and column
        TextEditor::BaseTextEditor *edit = qobject_cast<TextEditor::BaseTextEditor *>(m_editor->widget());
        int lineSigned = 0, columnSigned = 0;
        edit->convertPosition(m_editor->position(), &lineSigned, &columnSigned);
        unsigned line = lineSigned, column = columnSigned;

        // find a scope that encloses the current location, starting from the lastVisibileSymbol
        // and moving outwards
981
        Scope *sc = 0;
982
983
        if (typeOfExpression.scope())
            sc = typeOfExpression.scope();
984
985
986
987
        else if (context.thisDocument())
            sc = context.thisDocument()->globalSymbols();

        while (sc && sc->enclosingScope()) {
988
989
990
991
992
            unsigned startLine, startColumn;
            context.thisDocument()->translationUnit()->getPosition(sc->owner()->startOffset(), &startLine, &startColumn);
            unsigned endLine, endColumn;
            context.thisDocument()->translationUnit()->getPosition(sc->owner()->endOffset(), &endLine, &endColumn);

993
            if (startLine <= line && line <= endLine) {
994
995
996
                if ((startLine != line || startColumn <= column)
                    && (endLine != line || column <= endColumn))
                    break;
997
            }
998
999
1000
1001

            sc = sc->enclosingScope();
        }

1002
        if (sc && (sc->isClassScope() || sc->isNamespaceScope())) {
1003
1004
1005
1006
1007
1008
1009
            // It may still be a function call. If the whole line parses as a function
            // declaration, we should be certain that it isn't.
            bool autocompleteSignature = false;

            QTextCursor tc(edit->document());
            tc.setPosition(endOfExpression);
            BackwardsScanner bs(tc);
1010
1011
1012
1013
1014
            const int startToken = bs.startToken();
            const int lineStartToken = bs.startOfLine(startToken);
            // make sure the required tokens are actually available
            bs.LA(startToken - lineStartToken);
            QString possibleDecl = bs.mid(lineStartToken).trimmed().append("();");
1015
1016
1017
1018
1019
1020

            Document::Ptr doc = Document::create(QLatin1String("<completion>"));
            doc->setSource(possibleDecl.toLatin1());
            if (doc->parse(Document::ParseDeclaration)) {
                doc->check();
                if (SimpleDeclarationAST *sd = doc->translationUnit()->ast()->asSimpleDeclaration()) {
1021
1022
                    if (sd->declarator_list &&
                        sd->declarator_list && sd->declarator_list->value->postfix_declarator_list
Roberto Raggi's avatar
Roberto Raggi committed
1023
                        && sd->declarator_list->value->postfix_declarator_list->value->asFunctionDeclarator()) {
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
                        autocompleteSignature = true;
                    }
                }
            }

            if (autocompleteSignature) {
                // set up signature autocompletion
                foreach (Function *f, functions) {
                    Overview overview;
                    overview.setShowArgumentNames(true);