cppcodecompletion.cpp 57.1 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;
526
527
528
529
    case '#':
        completionKind = T_POUND;
        --start;
        break;
con's avatar
con committed
530
531
    }

532
533
534
535
536
537
538
    if (start == pos)
        return start;

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

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

550
    if (completionKind == T_COMMA) {
551
552
        ExpressionUnderCursor expressionUnderCursor;
        if (expressionUnderCursor.startOfFunctionCall(tc) == -1) {
553
            completionKind = T_EOF_SYMBOL;
554
555
556
557
            start = pos;
        }
    }

558
559
560
    static CPlusPlus::TokenUnderCursor tokenUnderCursor;
    const SimpleToken tk = tokenUnderCursor(tc);

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

        if (i == tokens.size()) {
594
            completionKind = T_EOF_SYMBOL;
595
596
597
            start = pos;
        }
    }
598
    // Check for include preprocessor directive
599
    else if (completionKind == T_STRING_LITERAL || completionKind == T_ANGLE_STRING_LITERAL || completionKind == T_SLASH) {
600
        bool include = false;
601
602
603
604
605
606
607
608
609
        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;
610
611
612
613
614
                }
            }
        }

        if (!include) {
615
            completionKind = T_EOF_SYMBOL;
616
617
618
619
            start = pos;
        }
    }

620
    if (kind)
621
        *kind = completionKind;
622

con's avatar
con committed
623
624
625
    return start;
}

626
bool CppCodeCompletion::supportsEditor(TextEditor::ITextEditable *editor)
627
628
{ return m_manager->isCppEditor(editor); }

629
630
631
632
633
634
TextEditor::ITextEditable *CppCodeCompletion::editor() const
{ return m_editor; }

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

con's avatar
con committed
635
636
637
bool CppCodeCompletion::triggersCompletion(TextEditor::ITextEditable *editor)
{
    const int pos = editor->position();
638
    if (startOfOperator(editor, pos, /*token =*/ 0, /*want function call=*/ true) != pos) {
639
640
641
642
643
644
645
646
647
648
        if (m_completionOperator == T_POUND) {
            if (TextEditor::BaseTextEditor *edit = qobject_cast<TextEditor::BaseTextEditor *>(editor->widget())) {
                QTextCursor tc(edit->document());
                tc.setPosition(pos);
                return tc.columnNumber() == 1;
            }

            return false;
        }

con's avatar
con committed
649
        return true;
650
    }
con's avatar
con committed
651
652
653
654
655
656
657
658
659
660
661

    return false;
}

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

    m_editor = editor;
662

663
664
    const int startOfName = findStartOfName();
    m_startPosition = startOfName;
con's avatar
con committed
665
666
    m_completionOperator = T_EOF_SYMBOL;

667
    int endOfOperator = m_startPosition;
con's avatar
con committed
668
669

    // Skip whitespace preceding this position
670
671
    while (editor->characterAt(endOfOperator - 1).isSpace())
        --endOfOperator;
con's avatar
con committed
672

673
674
675
    int endOfExpression = startOfOperator(editor, endOfOperator,
                                          &m_completionOperator,
                                          /*want function call =*/ true);
con's avatar
con committed
676
677
678
679
680
681
682
683

    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;

684
685
686
    if (m_completionOperator == T_DOXY_COMMENT) {
        for (int i = 1; i < T_DOXY_LAST_TAG; ++i) {
            TextEditor::CompletionItem item(this);
687
688
            item.text.append(QString::fromLatin1(doxygenTagSpell(i)));
            item.icon = m_icons.keywordIcon();
689
690
691
692
693
694
            m_completions.append(item);
        }

        return m_startPosition;
    }

695
696
697
698
699
700
701
    // Pre-processor completion
    if (m_completionOperator == T_POUND) {
        completePreprocessor();
        m_startPosition = startOfName;
        return m_startPosition;
    }

702
703
704
705
706
707
708
709
710
711
712
713
    // 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;
    }

714
715
    ExpressionUnderCursor expressionUnderCursor;
    QTextCursor tc(edit->document());
716

717
    if (m_completionOperator == T_COMMA) {
con's avatar
con committed
718
        tc.setPosition(endOfExpression);
719
        const int start = expressionUnderCursor.startOfFunctionCall(tc);
720
721
722
        if (start == -1) {
            m_completionOperator = T_EOF_SYMBOL;
            return -1;
723
        }
724
725
726
727

        endOfExpression = start;
        m_startPosition = start + 1;
        m_completionOperator = T_LPAREN;
728
729
730
731
    }

    QString expression;
    tc.setPosition(endOfExpression);
732

733
    if (m_completionOperator) {
con's avatar
con committed
734
        expression = expressionUnderCursor(tc);
735

con's avatar
con committed
736
737
738
        if (m_completionOperator == T_LPAREN) {
            if (expression.endsWith(QLatin1String("SIGNAL")))
                m_completionOperator = T_SIGNAL;
739

con's avatar
con committed
740
741
            else if (expression.endsWith(QLatin1String("SLOT")))
                m_completionOperator = T_SLOT;
742

743
744
745
746
            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;
747
                m_startPosition = startOfName;
748
            }
con's avatar
con committed
749
750
751
        }
    }

752
    //qDebug() << "***** expression:" << expression;
753
754
    return startCompletionInternal(edit, fileName, line, column, expression, endOfExpression);
}
con's avatar
con committed
755

756
757
758
759
760
761
762
int CppCodeCompletion::startCompletionInternal(TextEditor::BaseTextEditor *edit,
                                               const QString fileName,
                                               unsigned line, unsigned column,
                                               const QString &expr,
                                               int endOfExpression)
{
    QString expression = expr.trimmed();
763
764
    const Snapshot snapshot = m_manager->snapshot();

765
766
767
    Document::Ptr thisDocument = snapshot.document(fileName);
    if (! thisDocument)
        return -1;
con's avatar
con committed
768

769
    typeOfExpression.init(thisDocument, snapshot);
770
771
772

    Scope *scope = thisDocument->scopeAt(line, column);
    Q_ASSERT(scope != 0);
con's avatar
con committed
773

774
    if (expression.isEmpty()) {
775
776
777
778
779
780
781
        if (m_completionOperator == T_EOF_SYMBOL || m_completionOperator == T_COLON_COLON) {
            (void) typeOfExpression(expression, scope);
            globalCompletion(scope);
            if (m_completions.isEmpty())
                return -1;
            return m_startPosition;
        }
con's avatar
con committed
782

783
        else if (m_completionOperator == T_SIGNAL || m_completionOperator == T_SLOT) {
con's avatar
con committed
784
785
786
            // Apply signal/slot completion on 'this'
            expression = QLatin1String("this");
        }
787
    }
con's avatar
con committed
788

789
790
791
    if (debug)
        qDebug() << "scope:" << scope->owner()->fileName() << scope->owner()->line() << scope->owner()->column();

792
    QList<LookupItem> results = typeOfExpression(expression, scope, TypeOfExpression::Preprocess);
793
794
795
796

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

797
798
799
800
    if (results.isEmpty()) {
        if (m_completionOperator == T_SIGNAL || m_completionOperator == T_SLOT) {
            if (! (expression.isEmpty() || expression == QLatin1String("this"))) {
                expression = QLatin1String("this");
801
                results = typeOfExpression(expression, scope);
802
            }
Roberto Raggi's avatar
Cleanup    
Roberto Raggi committed
803

804
805
            if (results.isEmpty())
                return -1;
Roberto Raggi's avatar
Cleanup    
Roberto Raggi committed
806

807
        } else if (m_completionOperator == T_LPAREN) {
808
809
810
811
812
813
814
815
            // 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);
816

817
            ExpressionUnderCursor expressionUnderCursor;
818
            const QString baseExpression = expressionUnderCursor(tc);
819
820

            // Resolve the type of this expression
821
            const QList<LookupItem> results =
822
                    typeOfExpression(baseExpression, scope,
823
                                     TypeOfExpression::Preprocess);
824
825

            // If it's a class, add completions for the constructors
826
827
            foreach (const LookupItem &result, results) {
                if (result.type()->isClassType()) {
828
                    if (completeConstructorOrFunction(results, endOfExpression, true))
829
                        return m_startPosition;
830

831
832
833
                    break;
                }
            }
834
835
836
837
838
839
            return -1;

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

840
        }
con's avatar
con committed
841
842
    }

843
844
    switch (m_completionOperator) {
    case T_LPAREN:
845
        if (completeConstructorOrFunction(results, endOfExpression, false))
846
847
848
849
850
            return m_startPosition;
        break;

    case T_DOT:
    case T_ARROW:
851
        if (completeMember(results))
852
853
854
855
            return m_startPosition;
        break;

    case T_COLON_COLON:
856
        if (completeScope(results))
857
858
859
860
            return m_startPosition;
        break;

    case T_SIGNAL:
861
        if (completeSignal(results))
862
863
864
865
            return m_startPosition;
        break;

    case T_SLOT:
866
        if (completeSlot(results))
867
868
869
870
871
872
873
            return m_startPosition;
        break;

    default:
        break;
    } // end of switch

con's avatar
con committed
874
875
876
877
    // nothing to do.
    return -1;
}

878
void CppCodeCompletion::globalCompletion(Scope *currentScope)
879
{
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
    const LookupContext &context = typeOfExpression.context();

    if (m_completionOperator == T_COLON_COLON) {
        completeNamespace(context.globalNamespace());
        return;
    }

    addKeywords();
    addMacros(context.thisDocument()->fileName(), context.snapshot());

    QList<ClassOrNamespace *> usingBindings;
    ClassOrNamespace *currentBinding = 0;

    for (Scope *scope = currentScope; scope; scope = scope->enclosingScope()) {
        if (scope->isBlockScope()) {
            if (ClassOrNamespace *binding = context.lookupType(scope->owner())) {
                for (unsigned i = 0; i < scope->symbolCount(); ++i) {
                    Symbol *member = scope->symbolAt(i);
                    if (! member->name())
                        continue;
                    else if (UsingNamespaceDirective *u = member->asUsingNamespaceDirective()) {
                        if (ClassOrNamespace *b = binding->lookupType(u->name()))
                            usingBindings.append(b);
                    }
                }
            }
        } else if (scope->isFunctionScope() || scope->isClassScope() || scope->isNamespaceScope()) {
            currentBinding = context.lookupType(scope->owner());
            break;
        }
910
911
    }

912
913
    for (; currentBinding; currentBinding = currentBinding->parent()) {
        const QList<Symbol *> symbols = currentBinding->symbols();
914

915
916
917
918
919
        if (! symbols.isEmpty()) {
            if (symbols.first()->isNamespace())
                completeNamespace(currentBinding);
            else
                completeClass(currentBinding, false);
920
921
922
        }
    }

923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
    foreach (ClassOrNamespace *b, usingBindings)
        completeNamespace(b);

    for (Scope *scope = currentScope; scope; scope = scope->enclosingScope()) {
        if (scope->isBlockScope()) {
            for (unsigned i = 0; i < scope->symbolCount(); ++i) {
                addCompletionItem(scope->symbolAt(i));
            }
        } else if (scope->isFunctionScope()) {
            Scope *arguments = scope->owner()->asFunction()->arguments();
            for (unsigned i = 0; i < arguments->symbolCount(); ++i) {
                addCompletionItem(arguments->symbolAt(i));
            }
            break;
        } else {
            break;
        }
    }
941
942
}

943
bool CppCodeCompletion::completeConstructorOrFunction(const QList<LookupItem> &results,
944
                                                      int endOfExpression, bool toolTipOnly)
con's avatar
con committed
945
{
946
    const LookupContext &context = typeOfExpression.context();
947
948
    QList<Function *> functions;

949
950
    foreach (const LookupItem &result, results) {
        FullySpecifiedType exprTy = result.type().simplified();
Roberto Raggi's avatar
Roberto Raggi committed
951
952

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

Roberto Raggi's avatar
Roberto Raggi committed
957
958
            for (unsigned i = 0; i < klass->memberCount(); ++i) {
                Symbol *member = klass->memberAt(i);
Roberto Raggi's avatar
Roberto Raggi committed
959
                const Name *memberName = member->name();
960
961
962
963
964
965
966
967
968
969
970
971

                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
972
                }
973
            }
Roberto Raggi's avatar
Roberto Raggi committed
974
975

            break;
976
        }
Roberto Raggi's avatar
Roberto Raggi committed
977
978
    }

979
    if (functions.isEmpty()) {
980
981
        foreach (const LookupItem &result, results) {
            FullySpecifiedType ty = result.type().simplified();
Roberto Raggi's avatar
Roberto Raggi committed
982

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

985
986
987
988
989
990
991
992
993
994
995
996
                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
997
                }
998
999
1000

                if (newOverload)
                    functions.append(fun);
con's avatar
con committed
1001
1002
            }
        }
1003
1004
1005
    }

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

1008
1009
        foreach (const LookupItem &result, results) {
            FullySpecifiedType ty = result.type().simplified();
1010
            Scope *scope = result.scope();
1011
1012

            if (NamedType *namedTy = ty->asNamedType()) {
1013
                if (ClassOrNamespace *b = context.lookupType(namedTy->name(), scope)) {
1014
1015
                    foreach (Symbol *overload, b->lookup(functionCallOp)) {
                        FullySpecifiedType overloadTy = overload->type().simplified();
1016

1017
1018
                        if (Function *funTy = overloadTy->asFunctionType())
                            functions.append(funTy);
1019
1020
1021
1022
                    }
                }
            }
        }
con's avatar
con committed
1023
1024
    }

1025
1026
1027
1028
1029
    // 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.
1030

1031
1032
1033
1034
1035
    // 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.
1036
1037
1038
1039
1040
1041
1042
1043
1044

        // 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
1045
        Scope *sc = 0;
1046
1047
        if (typeOfExpression.scope())
            sc = typeOfExpression.scope();
1048
1049
1050
1051
        else if (context.thisDocument())
            sc = context.thisDocument()->globalSymbols();

        while (sc && sc->enclosingScope()) {
1052
1053
1054
1055
1056
            unsigned startLine, startColumn;
            context.thisDocument()->translationUnit()->getPosition(sc->owner()->startOffset(), &startLine, &startColumn);
            unsigned endLine, endColumn;
            context.thisDocument()->translationUnit()->getPosition(sc->owner()->endOffset(), &endLine, &endColumn);

1057
            if (startLine <= line && line <= endLine) {
1058
1059
1060
                if ((startLine != line || startColumn <= column)
                    && (endLine != line || column <= endColumn))
                    break;
1061
            }
1062
1063
1064
1065

            sc = sc->enclosingScope();
        }

1066
        if (sc && (sc->isClassScope() || sc->isNamespaceScope())) {