CppDocument.cpp 21 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
**************************************************************************/
con's avatar
con committed
29
30

#include "CppDocument.h"
31
#include "FastPreprocessor.h"
32
33
#include "LookupContext.h"
#include "Overview.h"
hjk's avatar
hjk committed
34

con's avatar
con committed
35
36
37
38
39
40
#include <Control.h>
#include <TranslationUnit.h>
#include <DiagnosticClient.h>
#include <Semantic.h>
#include <Literals.h>
#include <Symbols.h>
41
#include <Names.h>
con's avatar
con committed
42
43
#include <AST.h>
#include <Scope.h>
44
#include <SymbolVisitor.h>
hjk's avatar
hjk committed
45

Roberto Raggi's avatar
Roberto Raggi committed
46
47
#include <QtCore/QByteArray>
#include <QtCore/QBitArray>
48
#include <QtCore/QDir>
Roberto Raggi's avatar
Roberto Raggi committed
49
#include <QtCore/QtDebug>
con's avatar
con committed
50

Christian Kamm's avatar
Christian Kamm committed
51
52
53
54
55
/*!
    \namespace CPlusPlus
    The namespace for C++ related tools.
*/

con's avatar
con committed
56
57
58
59
using namespace CPlusPlus;

namespace {

60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
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
class FindScopeAt: protected SymbolVisitor
{
    TranslationUnit *_unit;
    unsigned _line;
    unsigned _column;
    Scope *_scope;

public:
    FindScopeAt(TranslationUnit *unit, unsigned line, unsigned column)
        : _unit(unit), _line(line), _column(column), _scope(0) {}

    Scope *operator()(Symbol *symbol)
    {
        accept(symbol);
        return _scope;
    }

protected:
    bool process(ScopedSymbol *symbol)
    {
        if (! _scope) {
            Scope *scope = symbol->members();

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

                if (_scope)
                    return false;
            }

            unsigned startLine, startColumn;
            _unit->getPosition(symbol->startOffset(), &startLine, &startColumn);

            if (_line > startLine || (_line == startLine && _column >= startColumn)) {
                unsigned endLine, endColumn;
                _unit->getPosition(symbol->endOffset(), &endLine, &endColumn);

                if (_line < endLine || (_line == endLine && _column < endColumn))
                    _scope = scope;
            }
        }

        return false;
    }

    using SymbolVisitor::visit;

    virtual bool preVisit(Symbol *)
    { return ! _scope; }

    virtual bool visit(UsingNamespaceDirective *) { return false; }
    virtual bool visit(UsingDeclaration *) { return false; }
    virtual bool visit(NamespaceAlias *) { return false; }
    virtual bool visit(Declaration *) { return false; }
    virtual bool visit(Argument *) { return false; }
    virtual bool visit(TypenameArgument *) { return false; }
    virtual bool visit(BaseClass *) { return false; }
    virtual bool visit(ForwardClassDeclaration *) { return false; }

    virtual bool visit(Enum *symbol)
    { return process(symbol); }

    virtual bool visit(Function *symbol)
    { return process(symbol); }

    virtual bool visit(Namespace *symbol)
    { return process(symbol); }

    virtual bool visit(Class *symbol)
    { return process(symbol); }

    virtual bool visit(Block *symbol)
    { return process(symbol); }

    // Objective-C
    virtual bool visit(ObjCBaseClass *) { return false; }
    virtual bool visit(ObjCBaseProtocol *) { return false; }
    virtual bool visit(ObjCForwardClassDeclaration *) { return false; }
    virtual bool visit(ObjCForwardProtocolDeclaration *) { return false; }
    virtual bool visit(ObjCPropertyDeclaration *) { return false; }
Erik Verbruggen's avatar
Erik Verbruggen committed
140
141
142
143
144
145
146
147
148

    virtual bool visit(ObjCClass *symbol)
    { return process(symbol); }

    virtual bool visit(ObjCProtocol *symbol)
    { return process(symbol); }

    virtual bool visit(ObjCMethod *symbol)
    { return process(symbol); }
149
150
};

hjk's avatar
hjk committed
151
152
153
154
155
156
157
class DocumentDiagnosticClient : public DiagnosticClient
{
    enum { MAX_MESSAGE_COUNT = 10 };

public:
    DocumentDiagnosticClient(Document *doc, QList<Document::DiagnosticMessage> *messages)
        : doc(doc),
Roberto Raggi's avatar
Roberto Raggi committed
158
159
          messages(messages),
          errorCount(0)
hjk's avatar
hjk committed
160
161
162
    { }

    virtual void report(int level,
Roberto Raggi's avatar
Roberto Raggi committed
163
                        const StringLiteral *fileId,
hjk's avatar
hjk committed
164
165
166
                        unsigned line, unsigned column,
                        const char *format, va_list ap)
    {
Roberto Raggi's avatar
Roberto Raggi committed
167
168
169
170
171
172
        if (level == Error) {
            ++errorCount;

            if (errorCount >= MAX_MESSAGE_COUNT)
                return; // ignore the error
        }
con's avatar
con committed
173

hjk's avatar
hjk committed
174
        const QString fileName = QString::fromUtf8(fileId->chars(), fileId->size());
con's avatar
con committed
175

hjk's avatar
hjk committed
176
177
        if (fileName != doc->fileName())
            return;
con's avatar
con committed
178

hjk's avatar
hjk committed
179
180
        QString message;
        message.vsprintf(format, ap);
con's avatar
con committed
181

hjk's avatar
hjk committed
182
183
184
185
        Document::DiagnosticMessage m(convertLevel(level), doc->fileName(),
                                      line, column, message);
        messages->append(m);
    }
con's avatar
con committed
186

hjk's avatar
hjk committed
187
188
189
190
191
192
    static int convertLevel(int level) {
        switch (level) {
            case Warning: return Document::DiagnosticMessage::Warning;
            case Error:   return Document::DiagnosticMessage::Error;
            case Fatal:   return Document::DiagnosticMessage::Fatal;
            default:      return Document::DiagnosticMessage::Error;
con's avatar
con committed
193
        }
hjk's avatar
hjk committed
194
    }
con's avatar
con committed
195

Roberto Raggi's avatar
Roberto Raggi committed
196
private:
hjk's avatar
hjk committed
197
198
    Document *doc;
    QList<Document::DiagnosticMessage> *messages;
Roberto Raggi's avatar
Roberto Raggi committed
199
    int errorCount;
hjk's avatar
hjk committed
200
};
con's avatar
con committed
201

hjk's avatar
hjk committed
202
} // anonymous namespace
con's avatar
con committed
203

Christian Kamm's avatar
Christian Kamm committed
204

con's avatar
con committed
205
Document::Document(const QString &fileName)
206
    : _fileName(QDir::cleanPath(fileName)),
207
      _globalNamespace(0),
208
209
      _revision(0),
      _editorRevision(0)
con's avatar
con committed
210
211
212
213
214
215
{
    _control = new Control();

    _control->setDiagnosticClient(new DocumentDiagnosticClient(this, &_diagnosticMessages));

    const QByteArray localFileName = fileName.toUtf8();
Roberto Raggi's avatar
Roberto Raggi committed
216
217
    const StringLiteral *fileId = _control->findOrInsertStringLiteral(localFileName.constData(),
                                                                      localFileName.size());
con's avatar
con committed
218
219
    _translationUnit = new TranslationUnit(_control, fileId);
    _translationUnit->setQtMocRunEnabled(true);
Roberto Raggi's avatar
Roberto Raggi committed
220
    _translationUnit->setCxxOxEnabled(true);
Roberto Raggi's avatar
Roberto Raggi committed
221
    _translationUnit->setObjCEnabled(true);
con's avatar
con committed
222
223
224
225
226
227
228
229
230
231
232
    (void) _control->switchTranslationUnit(_translationUnit);
}

Document::~Document()
{
    delete _translationUnit;
    delete _control->diagnosticClient();
    delete _control;
}

Control *Document::control() const
hjk's avatar
hjk committed
233
234
235
{
    return _control;
}
con's avatar
con committed
236

237
238
239
240
241
242
243
244
245
246
unsigned Document::revision() const
{
    return _revision;
}

void Document::setRevision(unsigned revision)
{
    _revision = revision;
}

247
248
249
250
251
252
253
254
255
256
unsigned Document::editorRevision() const
{
    return _editorRevision;
}

void Document::setEditorRevision(unsigned editorRevision)
{
    _editorRevision = editorRevision;
}

257
258
259
260
261
262
263
264
265
266
QDateTime Document::lastModified() const
{
    return _lastModified;
}

void Document::setLastModified(const QDateTime &lastModified)
{
    _lastModified = lastModified;
}

con's avatar
con committed
267
QString Document::fileName() const
hjk's avatar
hjk committed
268
269
270
{
    return _fileName;
}
con's avatar
con committed
271
272

QStringList Document::includedFiles() const
hjk's avatar
hjk committed
273
{
274
275
276
277
278
    QStringList files;
    foreach (const Include &i, _includes)
        files.append(i.fileName());
    files.removeDuplicates();
    return files;
hjk's avatar
hjk committed
279
}
con's avatar
con committed
280

281
void Document::addIncludeFile(const QString &fileName, unsigned line)
hjk's avatar
hjk committed
282
{
283
    _includes.append(Include(QDir::cleanPath(fileName), line));
hjk's avatar
hjk committed
284
}
con's avatar
con committed
285

Roberto Raggi's avatar
Roberto Raggi committed
286
void Document::appendMacro(const Macro &macro)
hjk's avatar
hjk committed
287
{
Roberto Raggi's avatar
Roberto Raggi committed
288
    _definedMacros.append(macro);
con's avatar
con committed
289
290
}

291
void Document::addMacroUse(const Macro &macro, unsigned offset, unsigned length,
292
                           unsigned beginLine,
Christian Kamm's avatar
Christian Kamm committed
293
                           const QVector<MacroArgumentReference> &actuals, bool inCondition)
294
{
295
    MacroUse use(macro, offset, offset + length, beginLine);
Christian Kamm's avatar
Christian Kamm committed
296
    use.setInCondition(inCondition);
297
298
299
300
301
302
303
304

    foreach (const MacroArgumentReference &actual, actuals) {
        const Block arg(actual.position(), actual.position() + actual.length());

        use.addArgument(arg);
    }

    _macroUses.append(use);
305
306
}

Christian Kamm's avatar
Christian Kamm committed
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
void Document::addUndefinedMacroUse(const QByteArray &name, unsigned offset)
{
    QByteArray copy(name.data(), name.size());
    UndefinedMacroUse use(copy, offset);
    _undefinedMacroUses.append(use);
}

/*!
    \class Document::MacroUse
    \brief Represents the usage of a macro in a \l {Document}.
    \sa Document::UndefinedMacroUse
*/

/*!
    \class Document::UndefinedMacroUse
    \brief Represents a macro that was looked up, but not found.

    Holds data about the reference to a macro in an \tt{#ifdef} or \tt{#ifndef}
    or argument to the \tt{defined} operator inside an \tt{#if} or \tt{#elif} that does
    not exist.

    \sa Document::undefinedMacroUses(), Document::MacroUse, Macro
*/

/*!
    \fn QByteArray Document::UndefinedMacroUse::name() const

    Returns the name of the macro that was not found.
*/

/*!
    \fn QList<UndefinedMacroUse> Document::undefinedMacroUses() const

    Returns a list of referenced but undefined macros.

    \sa Document::macroUses(), Document::definedMacros(), Macro
*/

/*!
    \fn QList<MacroUse> Document::macroUses() const

    Returns a list of macros used.

    \sa Document::undefinedMacroUses(), Document::definedMacros(), Macro
*/

/*!
    \fn QList<Macro> Document::definedMacros() const

    Returns the list of macros defined.

    \sa Document::macroUses(), Document::undefinedMacroUses()
*/

con's avatar
con committed
361
TranslationUnit *Document::translationUnit() const
hjk's avatar
hjk committed
362
363
364
{
    return _translationUnit;
}
con's avatar
con committed
365
366

bool Document::skipFunctionBody() const
hjk's avatar
hjk committed
367
368
369
{
    return _translationUnit->skipFunctionBody();
}
con's avatar
con committed
370
371

void Document::setSkipFunctionBody(bool skipFunctionBody)
hjk's avatar
hjk committed
372
373
374
{
    _translationUnit->setSkipFunctionBody(skipFunctionBody);
}
con's avatar
con committed
375
376
377
378
379
380
381
382
383
384

unsigned Document::globalSymbolCount() const
{
    if (! _globalNamespace)
        return 0;

    return _globalNamespace->memberCount();
}

Symbol *Document::globalSymbolAt(unsigned index) const
hjk's avatar
hjk committed
385
386
387
{
    return _globalNamespace->memberAt(index);
}
con's avatar
con committed
388
389
390
391
392
393
394
395
396
397

Scope *Document::globalSymbols() const
{
    if (! _globalNamespace)
        return 0;

    return _globalNamespace->members();
}

Namespace *Document::globalNamespace() const
hjk's avatar
hjk committed
398
399
400
{
    return _globalNamespace;
}
con's avatar
con committed
401

402
403
404
405
406
void Document::setGlobalNamespace(Namespace *globalNamespace)
{
    _globalNamespace = globalNamespace;
}

407
408
409
Scope *Document::scopeAt(unsigned line, unsigned column)
{
    FindScopeAt findScopeAt(_translationUnit, line, column);
410
411
412
    if (Scope *scope = findScopeAt(_globalNamespace))
        return scope;
    return globalSymbols();
413
414
}

415
Symbol *Document::lastVisibleSymbolAt(unsigned line, unsigned column) const
hjk's avatar
hjk committed
416
{
417
    return lastVisibleSymbolAt(line, column, globalSymbols());
hjk's avatar
hjk committed
418
}
con's avatar
con committed
419

420
Symbol *Document::lastVisibleSymbolAt(unsigned line, unsigned column, Scope *scope) const
con's avatar
con committed
421
422
423
424
425
426
427
428
429
430
431
432
433
{
    Symbol *previousSymbol = 0;

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

        previousSymbol = symbol;
    }

    if (previousSymbol) {
        if (ScopedSymbol *scoped = previousSymbol->asScopedSymbol()) {
434
            if (Symbol *member = lastVisibleSymbolAt(line, column, scoped->members()))
con's avatar
con committed
435
436
437
438
439
440
441
                return member;
        }
    }

    return previousSymbol;
}

442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
const Macro *Document::findMacroDefinitionAt(unsigned line) const
{
    foreach (const Macro &macro, _definedMacros) {
        if (macro.line() == line)
            return &macro;
    }
    return 0;
}

const Document::MacroUse *Document::findMacroUseAt(unsigned offset) const
{
    foreach (const Document::MacroUse &use, _macroUses) {
        if (use.contains(offset))
            return &use;
    }
    return 0;
}

const Document::UndefinedMacroUse *Document::findUndefinedMacroUseAt(unsigned offset) const
{
    foreach (const Document::UndefinedMacroUse &use, _undefinedMacroUses) {
        if (use.contains(offset))
            return &use;
    }
    return 0;
}

con's avatar
con committed
469
470
471
472
473
474
Document::Ptr Document::create(const QString &fileName)
{
    Document::Ptr doc(new Document(fileName));
    return doc;
}

Roberto Raggi's avatar
Roberto Raggi committed
475
476
477
QByteArray Document::source() const
{ return _source; }

con's avatar
con committed
478
void Document::setSource(const QByteArray &source)
hjk's avatar
hjk committed
479
{
480
481
    _source = source;
    _translationUnit->setSource(_source.constBegin(), _source.size());
hjk's avatar
hjk committed
482
}
con's avatar
con committed
483
484

void Document::startSkippingBlocks(unsigned start)
hjk's avatar
hjk committed
485
486
487
{
    _skippedBlocks.append(Block(start, 0));
}
con's avatar
con committed
488
489
490

void Document::stopSkippingBlocks(unsigned stop)
{
Roberto Raggi's avatar
Roberto Raggi committed
491
492
493
    if (_skippedBlocks.isEmpty())
        return;

con's avatar
con committed
494
495
496
497
498
499
500
    unsigned start = _skippedBlocks.back().begin();
    if (start > stop)
        _skippedBlocks.removeLast(); // Ignore this block, it's invalid.
    else
        _skippedBlocks.back() = Block(start, stop);
}

501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
bool Document::isTokenized() const
{
    return _translationUnit->isTokenized();
}

void Document::tokenize()
{
    _translationUnit->tokenize();
}

bool Document::isParsed() const
{
    return _translationUnit->isParsed();
}

516
bool Document::parse(ParseMode mode)
hjk's avatar
hjk committed
517
{
518
519
520
521
522
523
524
525
526
527
528
529
530
531
    TranslationUnit::ParseMode m = TranslationUnit::ParseTranlationUnit;
    switch (mode) {
    case ParseTranlationUnit:
        m = TranslationUnit::ParseTranlationUnit;
        break;

    case ParseDeclaration:
        m = TranslationUnit::ParseDeclaration;
        break;

    case ParseExpression:
        m = TranslationUnit::ParseExpression;
        break;

532
533
534
535
    case ParseDeclarator:
        m = TranslationUnit::ParseDeclarator;
        break;

536
537
538
539
540
541
542
543
544
    case ParseStatement:
        m = TranslationUnit::ParseStatement;
        break;

    default:
        break;
    }

    return _translationUnit->parse(m);
hjk's avatar
hjk committed
545
}
con's avatar
con committed
546

547
void Document::check(CheckMode mode)
con's avatar
con committed
548
{
549
    Q_ASSERT(!_globalNamespace);
con's avatar
con committed
550

551
552
553
    if (! isParsed())
        parse();

Roberto Raggi's avatar
Roberto Raggi committed
554
    Semantic semantic(_translationUnit);
555
556
    if (mode == FastCheck)
        semantic.setSkipFunctionBodies(true);
con's avatar
con committed
557
558
559

    _globalNamespace = _control->newNamespace(0);
    Scope *globals = _globalNamespace->members();
560
561
562
563
    if (! _translationUnit->ast())
        return; // nothing to do.

    if (TranslationUnitAST *ast = _translationUnit->ast()->asTranslationUnit()) {
Roberto Raggi's avatar
Roberto Raggi committed
564
        for (DeclarationListAST *decl = ast->declaration_list; decl; decl = decl->next) {
565
            semantic.check(decl->value, globals);
con's avatar
con committed
566
        }
567
568
    } else if (ExpressionAST *ast = _translationUnit->ast()->asExpression()) {
        semantic.check(ast, globals);
con's avatar
con committed
569
570
571
    }
}

572
573
574
575
576
void Document::releaseSource()
{
    _source.clear();
}

con's avatar
con committed
577
void Document::releaseTranslationUnit()
hjk's avatar
hjk committed
578
579
580
{
    _translationUnit->release();
}
581
582
583
584
585
586
587
588
589

Snapshot::Snapshot()
{
}

Snapshot::~Snapshot()
{
}

590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
int Snapshot::size() const
{
    return _documents.size();
}

bool Snapshot::isEmpty() const
{
    return _documents.isEmpty();
}

Document::Ptr Snapshot::operator[](const QString &fileName) const
{
    return _documents.value(fileName, Document::Ptr());
}

Snapshot::const_iterator Snapshot::find(const QString &fileName) const
{
    return _documents.find(fileName);
}

void Snapshot::remove(const QString &fileName)
{
    _documents.remove(fileName);
}

bool Snapshot::contains(const QString &fileName) const
{
    return _documents.contains(fileName);
}

620
621
622
void Snapshot::insert(Document::Ptr doc)
{
    if (doc)
623
        _documents.insert(doc->fileName(), doc);
624
625
}

626
QByteArray Snapshot::preprocessedCode(const QString &source, const QString &fileName) const
627
628
629
630
631
632
633
634
{
    FastPreprocessor pp(*this);
    return pp.run(fileName, source);
}

Document::Ptr Snapshot::documentFromSource(const QByteArray &preprocessedCode,
                                           const QString &fileName) const
{
Roberto Raggi's avatar
Roberto Raggi committed
635
    Document::Ptr newDoc = Document::create(fileName);
636

637
    if (Document::Ptr thisDocument = document(fileName)) {
638
        newDoc->_revision = thisDocument->_revision;
639
        newDoc->_editorRevision = thisDocument->_editorRevision;
640
        newDoc->_lastModified = thisDocument->_lastModified;
641
642
        newDoc->_includes = thisDocument->_includes;
        newDoc->_definedMacros = thisDocument->_definedMacros;
643
        newDoc->_macroUses = thisDocument->_macroUses;
644
645
    }

Roberto Raggi's avatar
Roberto Raggi committed
646
647
    newDoc->setSource(preprocessedCode);
    return newDoc;
648
649
}

650
Document::Ptr Snapshot::document(const QString &fileName) const
651
{
652
    return _documents.value(fileName);
653
654
}

655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
Snapshot Snapshot::simplified(Document::Ptr doc) const
{
    Snapshot snapshot;
    simplified_helper(doc, &snapshot);
    return snapshot;
}

void Snapshot::simplified_helper(Document::Ptr doc, Snapshot *snapshot) const
{
    if (! doc)
        return;

    if (! snapshot->contains(doc->fileName())) {
        snapshot->insert(doc);

        foreach (const Document::Include &incl, doc->includes()) {
671
            Document::Ptr includedDoc = document(incl.fileName());
672
673
674
675
            simplified_helper(includedDoc, snapshot);
        }
    }
}
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717

namespace {
class FindMatchingDefinition: public SymbolVisitor
{
    Symbol *_declaration;
    QList<Function *> _result;

public:
    FindMatchingDefinition(Symbol *declaration)
        : _declaration(declaration) {}

    QList<Function *> result() const { return _result; }

    using SymbolVisitor::visit;

    virtual bool visit(Function *fun)
    {
        if (_declaration->identifier()->isEqualTo(fun->identifier()))
            _result.append(fun);

        return false;
    }

    virtual bool visit(Block *)
    {
        return false;
    }
};
} // end of anonymous namespace

Symbol *Snapshot::findMatchingDefinition(Symbol *symbol) const
{
    if (! symbol->identifier())
        return 0;

    Document::Ptr thisDocument = document(QString::fromUtf8(symbol->fileName(), symbol->fileNameLength()));
    if (! thisDocument) {
        qWarning() << "undefined document:" << symbol->fileName();
        return 0;
    }

    LookupContext thisContext(thisDocument, *this);
718
    const QList<Symbol *> declarationCandidates = thisContext.lookup(symbol->name(), symbol->scope());
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
    if (declarationCandidates.isEmpty()) {
        qWarning() << "unresolved declaration:" << symbol->fileName() << symbol->line() << symbol->column();
        return 0;
    }

    Symbol *declaration = declarationCandidates.first();
    Function *declarationTy = declaration->type()->asFunctionType();
    if (! declarationTy) {
        qWarning() << "not a function:" << declaration->fileName() << declaration->line() << declaration->column();
        return 0;
    }

    foreach (Document::Ptr doc, *this) {
        if (! doc->control()->findIdentifier(declaration->identifier()->chars(),
                                             declaration->identifier()->size()))
            continue;

        FindMatchingDefinition candidates(declaration);
        candidates.accept(doc->globalNamespace());

        const QList<Function *> result = candidates.result();
        if (! result.isEmpty()) {
            LookupContext context(doc, *this);

            QList<Function *> viableFunctions;

745
746
747
748
            ClassOrNamespace *enclosingType = context.lookupType(declaration);
            if (! enclosingType)
                continue; // nothing to do

749
            foreach (Function *fun, result) {
750
                const QList<Symbol *> declarations = context.lookup(fun->name(), fun->scope());
751
752
                if (declarations.isEmpty())
                    continue;
753

754
                else if (enclosingType == context.lookupType(declarations.first()))
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
                    viableFunctions.append(fun);
            }

            if (viableFunctions.isEmpty())
                continue;

            else if (viableFunctions.length() == 1)
                return viableFunctions.first();

            Function *best = 0;

            foreach (Function *fun, viableFunctions) {
                if (fun->identity()->isEqualTo(declaration->identity()))
                    continue;

                else if (fun->argumentCount() == declarationTy->argumentCount()) {
                    if (! best)
                        best = fun;

                    unsigned argc = 0;
                    for (; argc < declarationTy->argumentCount(); ++argc) {
                        Symbol *arg = fun->argumentAt(argc);
                        Symbol *otherArg = declarationTy->argumentAt(argc);
                        if (! arg->type().isEqualTo(otherArg->type()))
                            break;
                    }

                    if (argc == declarationTy->argumentCount())
                        best = fun;
                }
            }

            if (! best)
                best = viableFunctions.first();

            return best;
        }
    }

    return 0;
}
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818

Class *Snapshot::findMatchingClassDeclaration(Symbol *declaration) const
{
    if (! declaration->identifier())
        return 0;

    foreach (Document::Ptr doc, *this) {
        if (! doc->control()->findIdentifier(declaration->identifier()->chars(),
                                             declaration->identifier()->size()))
            continue;

        LookupContext context(doc, *this);

        ClassOrNamespace *type = context.lookupType(declaration);
        if (!type || type->symbols().count() != 1)
            continue;

        if (Class *c = type->symbols().first()->asClass())
            return c;
    }

    return 0;
}