cppcodecompletion.cpp 40 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
63
64
65
66
67
68
69
70
71
72
#include <texteditor/basetexteditor.h>

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

using namespace CPlusPlus;

namespace CppTools {
namespace Internal {

73
74
class FunctionArgumentWidget : public QLabel
{
con's avatar
con committed
75
public:
76
    FunctionArgumentWidget();
77
    void showFunctionHint(Function *functionSymbol, const LookupContext &context);
con's avatar
con committed
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93

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

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

    int m_startpos;
    int m_currentarg;

    TextEditor::ITextEditor *m_editor;

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

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;

183
FunctionArgumentWidget::FunctionArgumentWidget()
con's avatar
con committed
184
185
    : m_item(0)
{
186
    QObject *editorObject = Core::EditorManager::instance()->currentEditor();
con's avatar
con committed
187
188
    m_editor = qobject_cast<TextEditor::ITextEditor *>(editorObject);

189
    m_popupFrame = new QFrame(0, Qt::ToolTip | Qt::WindowStaysOnTopHint);
con's avatar
con committed
190
191
192
193
194
195
196
197
198
    m_popupFrame->setFocusPolicy(Qt::NoFocus);
    m_popupFrame->setAttribute(Qt::WA_DeleteOnClose);

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

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

199
    QVBoxLayout *layout = new QVBoxLayout;
con's avatar
con committed
200
201
202
203
204
205
206
207
208
209
210
211
212
    layout->addWidget(this);
    layout->setMargin(0);
    m_popupFrame->setLayout(layout);

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

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

213
void FunctionArgumentWidget::showFunctionHint(Function *functionSymbol,
214
                                              const LookupContext &context)
con's avatar
con committed
215
{
216
217
    m_popupFrame->hide();

con's avatar
con committed
218
    m_item = functionSymbol;
219
    m_context = context;
con's avatar
con committed
220
221
222
223
224
225
226
227
228
229
230
    m_startpos = m_editor->position();

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

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

231
    qApp->installEventFilter(this);
con's avatar
con committed
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
}

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

    QString str = m_editor->textAt(m_startpos, curpos - m_startpos);
    int argnr = 0;
    int parcount = 0;
    SimpleLexer tokenize;
    QList<SimpleToken> tokens = tokenize(str);
    for (int i = 0; i < tokens.count(); ++i) {
        const SimpleToken &tk = tokens.at(i);
        if (tk.is(T_LPAREN))
            ++parcount;
        else if (tk.is(T_RPAREN))
            --parcount;
        else if (! parcount && tk.is(T_COMMA))
            ++argnr;
    }

    if (m_currentarg != argnr) {
        m_currentarg = argnr;
        updateHintText();
    }

    if (parcount < 0)
        close();
}

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

    return false;
}

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

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

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

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

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

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

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

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

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

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

con's avatar
con committed
358
359
360
361
362
363
364
365
366
367
368
369
/*
  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;
370
    int k = T_EOF_SYMBOL;
con's avatar
con committed
371
372

    if        (ch2 != QLatin1Char('.') && ch == QLatin1Char('.')) {
373
        k = T_DOT;
con's avatar
con committed
374
375
        --start;
    } else if (wantFunctionCall        && ch == QLatin1Char('(')) {
376
        k = T_LPAREN;
con's avatar
con committed
377
378
        --start;
    } else if (ch2 == QLatin1Char(':') && ch == QLatin1Char(':')) {
379
        k = T_COLON_COLON;
con's avatar
con committed
380
381
        start -= 2;
    } else if (ch2 == QLatin1Char('-') && ch == QLatin1Char('>')) {
382
        k = T_ARROW;
con's avatar
con committed
383
384
        start -= 2;
    } else if (ch2 == QLatin1Char('.') && ch == QLatin1Char('*')) {
385
        k = T_DOT_STAR;
con's avatar
con committed
386
387
        start -= 2;
    } else if (ch3 == QLatin1Char('-') && ch2 == QLatin1Char('>') && ch == QLatin1Char('*')) {
388
        k = T_ARROW_STAR;
con's avatar
con committed
389
        start -= 3;
390
    } else if ((ch2.isNull() || ch2.isSpace()) && (ch == QLatin1Char('@') || ch == QLatin1Char('\\'))) {
391
392
        k = T_DOXY_COMMENT;
        --start;
con's avatar
con committed
393
394
    }

395
396
397
398
399
400
401
402
403
404
405
406
407
    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
408
409
    }

410
411
412
413
414
415
416
417
    else if (tk.is(T_COMMENT) || tk.isLiteral()) {
        k = T_EOF_SYMBOL;
        start = pos;
    }

    if (kind)
        *kind = k;

con's avatar
con committed
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
    return start;
}

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

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

    return false;
}

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

    m_editor = editor;
441
    m_startPosition = findStartOfName();
con's avatar
con committed
442
443
    m_completionOperator = T_EOF_SYMBOL;

444
    int endOfOperator = m_startPosition;
con's avatar
con committed
445
446

    // Skip whitespace preceding this position
447
448
    while (editor->characterAt(endOfOperator - 1).isSpace())
        --endOfOperator;
con's avatar
con committed
449

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

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

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

    ExpressionUnderCursor expressionUnderCursor;
    QString expression;

464
465
466
467
468

    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)));
469
            item.m_icon = m_icons.keywordIcon();
470
471
472
473
474
475
476
            m_completions.append(item);
        }

        return m_startPosition;
    }


con's avatar
con committed
477
478
479
    if (m_completionOperator) {
        QTextCursor tc(edit->document());
        tc.setPosition(endOfExpression);
480

con's avatar
con committed
481
        expression = expressionUnderCursor(tc);
482

con's avatar
con committed
483
484
485
        if (m_completionOperator == T_LPAREN) {
            if (expression.endsWith(QLatin1String("SIGNAL")))
                m_completionOperator = T_SIGNAL;
486

con's avatar
con committed
487
488
            else if (expression.endsWith(QLatin1String("SLOT")))
                m_completionOperator = T_SLOT;
489

490
491
492
493
494
            else if (editor->position() != endOfOperator) {
                // We don't want a function completion when the cursor isn't at the opening brace
                expression.clear();
                m_completionOperator = T_EOF_SYMBOL;
            }
con's avatar
con committed
495
496
497
498
499
500
        }
    }

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

501
502
503
    const Snapshot snapshot = m_manager->snapshot();

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

506
        typeOfExpression.setSnapshot(m_manager->snapshot());
con's avatar
con committed
507

508
509
        QList<TypeOfExpression::Result> resolvedTypes = typeOfExpression(expression, thisDocument, symbol,
                                                                         TypeOfExpression::Preprocess);
con's avatar
con committed
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
        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
538
539
        if (! resolvedTypes.isEmpty()) {
            if (m_completionOperator == T_LPAREN && completeConstructorOrFunction(resolvedTypes)) {
con's avatar
con committed
540
                return m_startPosition;
Roberto Raggi's avatar
Cleanup  
Roberto Raggi committed
541

542
            } else if ((m_completionOperator == T_DOT || m_completionOperator == T_ARROW) &&
543
                      completeMember(resolvedTypes, context)) {
con's avatar
con committed
544
                return m_startPosition;
Roberto Raggi's avatar
Cleanup  
Roberto Raggi committed
545

546
            } else if (m_completionOperator == T_COLON_COLON && completeScope(resolvedTypes, context)) {
con's avatar
con committed
547
                return m_startPosition;
Roberto Raggi's avatar
Cleanup  
Roberto Raggi committed
548
549

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

            } else if (m_completionOperator == T_SLOT        && completeSlot(resolvedTypes, context)) {
con's avatar
con committed
553
554
555
                return m_startPosition;
            }
        }
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573

        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) {
574
                if (result.first->isClassType()) {
Roberto Raggi's avatar
Cleanup  
Roberto Raggi committed
575
                    if (completeConstructorOrFunction(results))
576
577
578
579
580
                        return m_startPosition;
                    break;
                }
            }
        }
con's avatar
con committed
581
582
583
584
585
586
    }

    // nothing to do.
    return -1;
}

Roberto Raggi's avatar
Cleanup  
Roberto Raggi committed
587
bool CppCodeCompletion::completeConstructorOrFunction(const QList<TypeOfExpression::Result> &results)
con's avatar
con committed
588
{
589
590
591
592
593
    ConvertToCompletionItem toCompletionItem(this);
    Overview o;
    o.setShowReturnTypes(true);
    o.setShowArgumentNames(true);

Roberto Raggi's avatar
Roberto Raggi committed
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
    foreach (const TypeOfExpression::Result &result, results) {
        FullySpecifiedType exprTy = result.first;

        if (Class *klass = exprTy->asClassType()) {
            for (unsigned i = 0; i < klass->memberCount(); ++i) {
                Symbol *member = klass->memberAt(i);
                if (! member->type()->isFunctionType())
                    continue;
                else if (! member->identity())
                    continue;
                else if (! member->identity()->isEqualTo(klass->identity()))
                    continue;
                if (TextEditor::CompletionItem item = toCompletionItem(member)) {
                    item.m_text = o(member->type(), member->name());
                    m_completions.append(item);
                }
610
            }
Roberto Raggi's avatar
Roberto Raggi committed
611
612

            break;
613
        }
Roberto Raggi's avatar
Roberto Raggi committed
614
615
616
    }

    if (m_completions.isEmpty()) {
con's avatar
con committed
617
        QSet<QString> signatures;
Roberto Raggi's avatar
Roberto Raggi committed
618
619

        foreach (const TypeOfExpression::Result &p, results) {
con's avatar
con committed
620
            FullySpecifiedType ty = p.first;
Roberto Raggi's avatar
Roberto Raggi committed
621

622
            if (Function *fun = ty->asFunctionType()) {
con's avatar
con committed
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
                if (TextEditor::CompletionItem item = toCompletionItem(fun)) {
                    QString signature;
                    signature += overview.prettyName(fun->name());
                    signature += overview.prettyType(fun->type());
                    if (signatures.contains(signature))
                        continue;
                    signatures.insert(signature);

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

638
639
640
641
    // If there is only one item, show the function argument widget immediately
    if (m_completions.size() == 1)
        complete(m_completions.takeFirst());

con's avatar
con committed
642
643
644
    return ! m_completions.isEmpty();
}

645
bool CppCodeCompletion::completeMember(const QList<TypeOfExpression::Result> &results,
con's avatar
con committed
646
647
                                       const LookupContext &context)
{
648
    if (results.isEmpty())
Roberto Raggi's avatar
Roberto Raggi committed
649
        return false;
con's avatar
con committed
650

651
    TypeOfExpression::Result result = results.first();
con's avatar
con committed
652
653
654
    QList<Symbol *> classObjectCandidates;

    if (m_completionOperator == T_ARROW)  {
655
        FullySpecifiedType ty = result.first;
con's avatar
con committed
656
657
658
659

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

660
        if (Class *classTy = ty->asClassType()) {
661
662
663
            Symbol *symbol = result.second;
            if (symbol && ! symbol->isClass())
                classObjectCandidates.append(classTy);
664
        } else if (NamedType *namedTy = ty->asNamedType()) {
665
666
667
668
669
670
671
672
673
674
675
676
            // ### 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
677
678
        if (NamedType *namedTy = ty->asNamedType()) {
            ResolveExpression resolveExpression(context);
679
            ResolveClass resolveClass;
con's avatar
con committed
680

681
            const QList<Symbol *> candidates = resolveClass(result, context);
con's avatar
con committed
682
683
            foreach (Symbol *classObject, candidates) {
                const QList<TypeOfExpression::Result> overloads =
684
                        resolveExpression.resolveArrowOperator(result, namedTy,
con's avatar
con committed
685
686
687
688
                                                               classObject->asClass());

                foreach (TypeOfExpression::Result r, overloads) {
                    FullySpecifiedType ty = r.first;
689
                    Function *funTy = ty->asFunctionType();
con's avatar
con committed
690
691
692
693
694
695
696
697
698
699
700
                    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 =
701
                                    resolveClass(namedTy, result, context);
con's avatar
con committed
702
703
704
705
706
707
708
709
710
711
712

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

715
716
                const QList<Symbol *> classes = resolveClass(namedTy, result,
                                                             context);
con's avatar
con committed
717
718
719
720
721

                foreach (Symbol *c, classes) {
                    if (! classObjectCandidates.contains(c))
                        classObjectCandidates.append(c);
                }
722
            } else if (Class *classTy = ptrTy->elementType()->asClassType()) {
723
724
725
726
                // typedef struct { int x } *Ptr;
                // Ptr p;
                // p->
                classObjectCandidates.append(classTy);
con's avatar
con committed
727
728
729
            }
        }
    } else if (m_completionOperator == T_DOT) {
730
        FullySpecifiedType ty = result.first;
con's avatar
con committed
731
732
733
734
735

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

        NamedType *namedTy = 0;
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753

        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
754
        if (PointerType *ptrTy = ty->asPointerType()) {
755
756
757
758
759
760
761
762
            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();
            }
763
        } else if (Class *classTy = ty->asClassType()) {
764
765
766
            Symbol *symbol = result.second;
            if (symbol && ! symbol->isClass())
                classObjectCandidates.append(classTy);
con's avatar
con committed
767
768
769
        } else {
            namedTy = ty->asNamedType();
            if (! namedTy) {
770
                Function *fun = ty->asFunctionType();
con's avatar
con committed
771
772
773
774
775
776
                if (fun && (fun->scope()->isBlockScope() || fun->scope()->isNamespaceScope()))
                    namedTy = fun->returnType()->asNamedType();
            }
        }

        if (namedTy) {
777
            ResolveClass resolveClass;
778
779
            const QList<Symbol *> symbols = resolveClass(namedTy, result,
                                                         context);
Roberto Raggi's avatar
Roberto Raggi committed
780
781
782
783
784
            foreach (Symbol *symbol, symbols) {
                if (classObjectCandidates.contains(symbol))
                    continue;
                if (Class *klass = symbol->asClass())
                    classObjectCandidates.append(klass);
con's avatar
con committed
785
786
787
788
789
790
791
792
793
794
795
            }
        }
    }

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

    return false;
}

796
bool CppCodeCompletion::completeScope(const QList<TypeOfExpression::Result> &results,
con's avatar
con committed
797
798
                                      const LookupContext &context)
{
799
    QList<Symbol *> classes, namespaces;
800

801
    foreach (TypeOfExpression::Result result, results) {
802
803
        FullySpecifiedType ty = result.first;

804
805
        if (Class *classTy = ty->asClassType())
            classes.append(classTy);
con's avatar
con committed
806

807
808
        else if (Namespace *namespaceTy = ty->asNamespaceType())
            namespaces.append(namespaceTy);
con's avatar
con committed
809
810
    }

811
812
813
814
815
816
    if (! classes.isEmpty())
        completeClass(classes, context);

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

con's avatar
con committed
817
818
819
820
821
822
    return ! m_completions.isEmpty();
}

void CppCodeCompletion::addKeywords()
{
    // keyword completion items.
823
    for (int i = T_FIRST_KEYWORD; i < T_FIRST_OBJC_AT_KEYWORD; ++i) {
con's avatar
con committed
824
825
826
827
828
829
830
831
832
833
        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;
834
835
836
837
    QSet<QString> definedMacros;

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

839
    foreach (const QString &macroName, definedMacros) {
con's avatar
con committed
840
        TextEditor::CompletionItem item(this);
841
        item.m_text = macroName;
con's avatar
con committed
842
843
844
845
846
        item.m_icon = m_icons.macroIcon();
        m_completions.append(item);
    }
}

847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
void CppCodeCompletion::addMacros_helper(const LookupContext &context,
                                         const QString &fileName,
                                         QSet<QString> *processed,
                                         QSet<QString> *definedMacros)
{
    Document::Ptr doc = context.document(fileName);

    if (! doc || processed->contains(doc->fileName()))
        return;

    processed->insert(doc->fileName());

    foreach (const Document::Include &i, doc->includes()) {
        addMacros_helper(context, i.fileName(), processed, definedMacros);
    }

    foreach (const Macro &macro, doc->definedMacros()) {
        const QString macroName = QString::fromUtf8(macro.name().constData(), macro.name().length());
        if (! macro.isHidden())
            definedMacros->insert(macroName);
        else
            definedMacros->remove(macroName);
    }
}

con's avatar
con committed
872
873
874
875
876
877
878
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
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
void CppCodeCompletion::addCompletionItem(Symbol *symbol)
{
    ConvertToCompletionItem toCompletionItem(this);
    if (TextEditor::CompletionItem item = toCompletionItem(symbol))
        m_completions.append(item);
}

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

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

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

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

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

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

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

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

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

            addCompletionItem(symbol);
        }
    }
}

Roberto Raggi's avatar
Cleanup  
Roberto Raggi committed
928
bool CppCodeCompletion::completeQtMethod(const QList<TypeOfExpression::Result> &results,
con's avatar
con committed
929
930
931
932
933
934
                                         const LookupContext &context,
                                         bool wantSignals)
{
    if (results.isEmpty())
        return false;

935
936
    ResolveClass resolveClass;

con's avatar
con committed
937
938
939
940
941
942
943
    ConvertToCompletionItem toCompletionItem(this);
    Overview o;
    o.setShowReturnTypes(false);
    o.setShowArgumentNames(false);
    o.setShowFunctionSignatures(true);

    QSet<QString> signatures;
Roberto Raggi's avatar
Cleanup  
Roberto Raggi committed
944
    foreach (const TypeOfExpression::Result &p, results) {
con's avatar
con committed
945
946
947
948
949
950
951
952
953
954
955
956
957
        FullySpecifiedType ty = p.first;
        if (ReferenceType *refTy = ty->asReferenceType())
            ty = refTy->elementType();
        if (PointerType *ptrTy = ty->asPointerType())
            ty = ptrTy->elementType();
        else
            continue; // not a pointer or a reference to a pointer.

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

        const QList<Symbol *> classObjects =
958
                resolveClass(namedTy, p, context);
con's avatar
con committed
959
960
961
962
963
964
965

        if (classObjects.isEmpty())
            continue;

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

        QList<Scope *> todo;
966
        const QList<Scope *> visibleScopes = context.visibleScopes(p);
con's avatar
con committed
967
968
969
970
971
972
973
974
        context.expand(klass->members(), visibleScopes, &todo);

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

            for (unsigned i = 0; i < scope->symbolCount(); ++i) {
                Symbol *member = scope->symbolAt(i);
975
                Function *fun = member->type()->asFunctionType();
con's avatar
con committed
976
977
978
979
980
981
982
983
984
                if (! fun)
                    continue;
                if (wantSignals && ! fun->isSignal())
                    continue;
                else if (! wantSignals && ! fun->isSlot())
                    continue;
                if (TextEditor::CompletionItem item = toCompletionItem(fun)) {
                    unsigned count = fun->argumentCount();
                    while (true) {
Friedemann Kleint's avatar
Friedemann Kleint committed
985
                        TextEditor::CompletionItem ci = item;
con's avatar
con committed
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005

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

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

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

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

Friedemann Kleint's avatar
Friedemann Kleint committed
1006
1007
                            ci.m_text = signature; // fix the completion item.
                            m_completions.append(ci);
con's avatar
con committed
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
                        }

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

    return ! m_completions.isEmpty();
}

void CppCodeCompletion::completions(QList<TextEditor::CompletionItem> *completions)
{
    const int length = m_editor->position() - m_startPosition;

    if (length == 0)
        *completions = m_completions;
    else if (length > 0) {
        const QString key = m_editor->textAt(m_startPosition, length);

        if (m_completionOperator != T_LPAREN) {
            /*
             * This code builds a regular expression in order to more intelligently match
             * camel-case style. This means upper-case characters will be rewritten as follows:
             *
             *   A => [a-z0-9_]*A (for any but the first capital letter)
             *
             * Meaning it allows any sequence of lower-case characters to preceed an
             * upper-case character. So for example gAC matches getActionController.
             */
            QString keyRegExp;
            keyRegExp += QLatin1Char('^');
            bool first = true;
            foreach (const QChar &c, key) {
1046
1047
1048
1049
1050
1051
1052
1053
                if (c.isUpper() && !first) {
                    keyRegExp += QLatin1String("[a-z0-9_]*");
                    keyRegExp += c;
                } else if (m_caseSensitivity == Qt::CaseInsensitive && c.isLower()) {
                    keyRegExp += QLatin1Char('[');
                    keyRegExp += c;
                    keyRegExp += c.toUpper();
                    keyRegExp += QLatin1Char(']');
con's avatar
con committed
1054
                } else {
1055
                    keyRegExp += QRegExp::escape(c);
con's avatar
con committed
1056
1057
1058
                }
                first = false;
            }
1059
            const QRegExp regExp(keyRegExp, Qt::CaseSensitive);
con's avatar
con committed
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090

            foreach (TextEditor::CompletionItem item, m_completions) {
                if (regExp.indexIn(item.m_text) == 0) {
                    item.m_relevance = (key.length() > 0 &&
                                         item.m_text.startsWith(key, Qt::CaseInsensitive)) ? 1 : 0;
                    (*completions) << item;
                }
            }
        } else if (m_completionOperator == T_LPAREN ||
                   m_completionOperator == T_SIGNAL ||
                   m_completionOperator == T_SLOT) {
            foreach (TextEditor::CompletionItem item, m_completions) {
                if (item.m_text.startsWith(key, Qt::CaseInsensitive)) {
                    (*completions) << item;
                }
            }
        }
    }
}

void CppCodeCompletion::complete(const TextEditor::CompletionItem &item)
{
    Symbol *symbol = 0;

    if (item.m_data.isValid())
        symbol = item.m_data.value<Symbol *>();

    // qDebug() << "*** complete symbol:" << symbol->fileName() << symbol->line();

    if (m_completionOperator == T_LPAREN) {
        if (symbol) {
1091
            Function *function = symbol->type()->asFunctionType();
hjk's avatar
hjk committed
1092
            QTC_ASSERT(function, return);
con's avatar
con committed
1093

1094
1095
1096
1097
            // Recreate if necessary
            if (!m_functionArgumentWidget)
                m_functionArgumentWidget = new FunctionArgumentWidget;

1098
            m_functionArgumentWidget->showFunctionHint(function, typeOfExpression.lookupContext());
con's avatar
con committed
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
        }
    } else if (m_completionOperator == T_SIGNAL || m_completionOperator == T_SLOT) {
        QString toInsert = item.m_text;
        toInsert += QLatin1Char(')');
        // Insert the remainder of the name
        int length = m_editor->position() - m_startPosition;
        m_editor->setCurPos(m_startPosition);
        m_editor->replace(length, toInsert);
    } else {
        QString toInsert = item.m_text;
1109
        int extraLength = 0;
con's avatar
con committed
1110
1111
1112
1113

        //qDebug() << "current symbol:" << overview.prettyName(symbol->name())
        //<< overview.prettyType(symbol->type());

1114
        if (m_autoInsertBraces && symbol && symbol->type()) {
1115
1116
            QString extraChars;

1117
            if (Function *function = symbol->type()->asFunctionType()) {
con's avatar
con committed
1118
1119
                // If the member is a function, automatically place the opening parenthesis,
                // except when it might take template parameters.
1120
1121
1122
1123
                const bool hasReturnType = function->returnType().isValid()  ||
                                           function->returnType().isSigned() ||
                                           function->returnType().isUnsigned();
                if (! hasReturnType && (function->identity() && !function->identity()->isDestructorNameId())) {
con's avatar
con committed
1124
1125
1126
1127
1128
                    // Don't insert any magic, since the user might have just wanted to select the class

                } else if (function->templateParameterCount() != 0) {
                    // If there are no arguments, then we need the template specification
                    if (function->argumentCount() == 0) {
1129
                        extraChars += QLatin1Char('<');
con's avatar
con committed
1130
                    }
1131
                } else if (! function->isAmbiguous()) {
1132
                    extraChars += QLatin1Char('(');
con's avatar
con committed
1133
1134

                    // If the function takes no arguments, automatically place the closing parenthesis
1135
                    if (function->argumentCount() == 0 || (function->argumentCount() == 1 &&
con's avatar
con committed
1136
                                                           function->argumentAt(0)->type()->isVoidType())) {
1137
                        extraChars += QLatin1Char(')');
con's avatar
con committed
1138
1139
1140

                        // If the function doesn't return anything, automatically place the semicolon,
                        // unless we're doing a scope completion (then it might be function definition).
1141
                        if (function->returnType()->isVoidType() && m_completionOperator != T_COLON_COLON) {
1142
                            extraChars += QLatin1Char(';');
con's avatar
con committed
1143
1144
1145
1146
                        }
                    }
                }
            }
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158

            // Avoid inserting characters that are already there
            for (int i = 0; i < extraChars.length(); ++i) {
                const QChar a = extraChars.at(i);
                const QChar b = m_editor->characterAt(m_editor->position() + i);
                if (a == b)
                    ++extraLength;
                else
                    break;
            }

            toInsert += extraChars;
con's avatar
con committed
1159
1160
1161
        }

        // Insert the remainder of the name
1162
        int length = m_editor->position() - m_startPosition + extraLength;
con's avatar
con committed
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
        m_editor->setCurPos(m_startPosition);
        m_editor->replace(length, toInsert);
    }
}

bool CppCodeCompletion::partiallyComplete(const QList<TextEditor::CompletionItem> &completionItems)
{
    if (m_completionOperator == T_SIGNAL || m_completionOperator == T_SLOT) {
        return false;
    } else if (completionItems.count() == 1) {
        complete(completionItems.first());
        return true;
1175
    } else if (m_partialCompletionEnabled && m_completionOperator != T_LPAREN) {
con's avatar
con committed
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
        // Compute common prefix
        QString firstKey = completionItems.first().m_text;
        QString lastKey = completionItems.last().m_text;
        const int length = qMin(firstKey.length(), lastKey.length());
        firstKey.truncate(length);
        lastKey.truncate(length);

        while (firstKey != lastKey) {
            firstKey.chop(1);
            lastKey.chop(1);
        }

        int typedLength = m_editor->position() - m_startPosition;
        if (!firstKey.isEmpty() && firstKey.length() > typedLength) {
            m_editor->setCurPos(m_startPosition);
            m_editor->replace(typedLength, firstKey);
        }
    }

    return false;
}

void CppCodeCompletion::cleanup()
{
    m_completions.clear();
1201
1202
1203

    // Set empty map in order to avoid referencing old versions of the documents
    // until the next completion
1204
    typeOfExpression.setSnapshot(Snapshot());
con's avatar
con committed
1205
1206
}

1207
int CppCodeCompletion::findStartOfName(int pos) const
con's avatar
con committed
1208
{
1209
1210
    if (pos == -1)
        pos = m_editor->position();
con's avatar
con committed
1211
1212
1213
1214
    QChar chr;

    // Skip to the start of a name
    do {
1215
        chr = m_editor->characterAt(--pos);
con's avatar
con committed
1216
1217
1218
1219
    } while (chr.isLetterOrNumber() || chr == QLatin1Char('_'));

    return pos + 1;
}