aboutsummaryrefslogtreecommitdiffstats
path: root/src/libs/cplusplus/CppDocument.cpp
blob: cdc036f1777e8cbe16deb9f911f0fa89aeb4fc82 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
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
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
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
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
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
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
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
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
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
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
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
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
718
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
745
746
747
748
749
750
751
752
753
754
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
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
// Copyright (C) 2016 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0

#include "CppDocument.h"
#include "FastPreprocessor.h"
#include "LookupContext.h"
#include "Overview.h"

#include <cplusplus/Bind.h>
#include <cplusplus/Control.h>
#include <cplusplus/TranslationUnit.h>
#include <cplusplus/DiagnosticClient.h>
#include <cplusplus/Literals.h>
#include <cplusplus/Symbols.h>
#include <cplusplus/Names.h>
#include <cplusplus/AST.h>
#include <cplusplus/ASTPatternBuilder.h>
#include <cplusplus/ASTMatcher.h>
#include <cplusplus/Scope.h>
#include <cplusplus/SymbolVisitor.h>
#include <cplusplus/NameVisitor.h>
#include <cplusplus/TypeVisitor.h>
#include <cplusplus/CoreTypes.h>

#include <utils/algorithm.h>

#include <QByteArray>
#include <QDebug>
#include <QStack>

/*!
    \namespace CPlusPlus
    The namespace for C++ related tools.
*/

using namespace CPlusPlus;
using namespace Utils;

namespace {

class LastVisibleSymbolAt: protected SymbolVisitor
{
    Symbol *root;
    int line;
    int column;
    Symbol *symbol;

public:
    LastVisibleSymbolAt(Symbol *root)
        : root(root), line(0), column(0), symbol(nullptr) {}

    Symbol *operator()(int line, int column)
    {
        this->line = line;
        this->column = column;
        this->symbol = nullptr;
        accept(root);
        if (! symbol)
            symbol = root;
        return symbol;
    }

protected:
    bool preVisit(Symbol *s) final
    {
        if (s->line() < line || (s->line() == line && s->column() <= column)) {
            // skip blocks
            if (!s->asBlock())
                symbol = s;
            return true;
        }

        return false;
    }
};

class FindScopeAt: protected SymbolVisitor
{
    TranslationUnit *_unit;
    int _line;
    int _column;
    Scope *_scope;

public:
    /** line and column should be 1-based */
    FindScopeAt(TranslationUnit *unit, int line, int column)
        : _unit(unit), _line(line), _column(column), _scope(nullptr) {}

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

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

            for (int i = 0; i < scope->memberCount(); ++i) {
                accept(scope->memberAt(i));

                if (_scope)
                    return false;
            }

            int startLine, startColumn;
            _unit->getPosition(scope->startOffset(), &startLine, &startColumn);

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

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

        return false;
    }

    using SymbolVisitor::visit;

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

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

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

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

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

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

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

    bool visit(Template *symbol) override
    {
        if (Symbol *decl = symbol->declaration()) {
            if (decl->asFunction() || decl->asClass() || decl->asDeclaration())
                return process(symbol);
        }
        return true;
    }

    bool visit(Declaration *decl) override
    {
        if (const auto func = decl->type().type()->asFunctionType())
            return process(func);
        return false;
    }

    // Objective-C
    bool visit(ObjCBaseClass *) override { return false; }
    bool visit(ObjCBaseProtocol *) override { return false; }
    bool visit(ObjCForwardClassDeclaration *) override { return false; }
    bool visit(ObjCForwardProtocolDeclaration *) override { return false; }
    bool visit(ObjCPropertyDeclaration *) override { return false; }

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

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

    bool visit(ObjCMethod *symbol) override
    { return process(symbol); }
};


#define DO_NOT_DUMP_ALL_PARSER_ERRORS

class DocumentDiagnosticClient : public DiagnosticClient
{
    enum { MAX_MESSAGE_COUNT = 10 };

public:
    DocumentDiagnosticClient(Document *doc, QList<Document::DiagnosticMessage> *messages)
        : doc(doc),
          messages(messages),
          errorCount(0)
    { }

    void report(int level,
                const StringLiteral *fileId,
                int line, int column,
                const char *format, va_list ap) override
    {
        if (level == Error) {
            ++errorCount;

#ifdef DO_NOT_DUMP_ALL_PARSER_ERRORS
            if (errorCount >= MAX_MESSAGE_COUNT)
                return; // ignore the error
#endif // DO_NOT_DUMP_ALL_PARSER_ERRORS
        }

        const QString fileName = QString::fromUtf8(fileId->chars(), fileId->size());

        if (fileName != doc->filePath().pathView())
            return;

        const QString message = QString::vasprintf(format, ap);

#ifndef DO_NOT_DUMP_ALL_PARSER_ERRORS
        {
            const char *levelStr = "Unknown level";
            if (level == Document::DiagnosticMessage::Warning) levelStr = "Warning";
            if (level == Document::DiagnosticMessage::Error) levelStr = "Error";
            if (level == Document::DiagnosticMessage::Fatal) levelStr = "Fatal";
            qDebug("%s:%u:%u: %s: %s", fileId->chars(), line, column, levelStr, message.toUtf8().constData());
        }
#endif // DO_NOT_DUMP_ALL_PARSER_ERRORS

        Document::DiagnosticMessage m(convertLevel(level), doc->filePath(),
                                      line, column, message);
        messages->append(m);
    }

    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;
        }
    }

private:
    Document *doc;
    QList<Document::DiagnosticMessage> *messages;
    int errorCount;
};

} // anonymous namespace


Document::Document(const FilePath &filePath)
    : _filePath(filePath),
      _globalNamespace(nullptr),
      _revision(0),
      _editorRevision(0),
      _checkMode(0)
{
    _control = new Control();

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

    const QByteArray localFileName = filePath.path().toUtf8();
    const StringLiteral *fileId = _control->stringLiteral(localFileName.constData(),
                                                          localFileName.size());
    _translationUnit = new TranslationUnit(_control, fileId);
    _translationUnit->setLanguageFeatures(LanguageFeatures::defaultFeatures());
}

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

Control *Document::swapControl(Control *newControl)
{
    if (newControl) {
        const StringLiteral *fileId = newControl->stringLiteral(_translationUnit->fileId()->chars(),
                                                                _translationUnit->fileId()->size());
        const auto newTranslationUnit = new TranslationUnit(newControl, fileId);
        newTranslationUnit->setLanguageFeatures(_translationUnit->languageFeatures());
        delete _translationUnit;
        _translationUnit = newTranslationUnit;
    } else {
        delete _translationUnit;
        _translationUnit = nullptr;
    }

    Control *oldControl = _control;
    _control = newControl;
    return oldControl;
}

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

FilePaths Document::includedFiles(Duplicates duplicates) const
{
    FilePaths files;
    for (const Include &i : std::as_const(_resolvedIncludes))
        files.append(i.resolvedFileName());
    if (duplicates == Duplicates::Remove)
        FilePath::removeDuplicates(files);
    return files;
}

// This assumes to be called with a QDir::cleanPath cleaned fileName.
void Document::addIncludeFile(const Document::Include &include)
{
    if (include.resolvedFileName().isEmpty())
        _unresolvedIncludes.append(include);
    else
        _resolvedIncludes.append(include);
}

void Document::appendMacro(const Macro &macro)
{
    _definedMacros.append(macro);
}

void Document::addMacroUse(const Macro &macro,
                           int bytesOffset, int bytesLength,
                           int utf16charsOffset, int utf16charLength,
                           int beginLine,
                           const QVector<MacroArgumentReference> &actuals)
{
    MacroUse use(macro,
                 bytesOffset, bytesOffset + bytesLength,
                 utf16charsOffset, utf16charsOffset + utf16charLength,
                 beginLine);

    for (const MacroArgumentReference &actual : actuals) {
        const Block arg(actual.bytesOffset(),
                        actual.bytesOffset() + actual.bytesLength(),
                        actual.utf16charsOffset(),
                        actual.utf16charsOffset() + actual.utf16charsLength());
        use.addArgument(arg);
    }

    _macroUses.append(use);
}

void Document::addUndefinedMacroUse(const QByteArray &name,
                                    int bytesOffset, int utf16charsOffset)
{
    QByteArray copy(name.data(), name.size());
    UndefinedMacroUse use(copy, bytesOffset, utf16charsOffset);
    _undefinedMacroUses.append(use);
}

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

/*!
    \class Document::UndefinedMacroUse
    \brief The UndefinedMacroUse class represents a macro that was looked for,
    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()
*/

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

void Document::setSkipFunctionBody(bool skipFunctionBody)
{
    _translationUnit->setSkipFunctionBody(skipFunctionBody);
}

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

    return _globalNamespace->memberCount();
}

Symbol *Document::globalSymbolAt(int index) const
{
    return _globalNamespace->memberAt(index);
}

void Document::setGlobalNamespace(Namespace *globalNamespace)
{
    _globalNamespace = globalNamespace;
}

/*!
 * Extract the function name including scope at the given position.
 *
 * Note that a function (scope) starts at the name of that function, not at the return type. The
 * implication is that this function will return an empty string when the line/column is on the
 * return type.
 *
 * \param line the line number, starting with line 1
 * \param column the column number, starting with column 1
 * \param lineOpeningDeclaratorParenthesis optional output parameter, the line of the opening
          parenthesis of the declarator starting with 1
 * \param lineClosingBrace optional output parameter, the line of the closing brace starting with 1
 */
QString Document::functionAt(int line, int column, int *lineOpeningDeclaratorParenthesis,
                             int *lineClosingBrace) const
{
    if (line < 1 || column < 1)
        return QString();

    Symbol *symbol = lastVisibleSymbolAt(line, column);
    if (!symbol)
        return QString();

    // Find the enclosing function scope (which might be several levels up, or we might be standing
    // on it)
    Scope *scope = symbol->asScope();
    if (!scope)
        scope = symbol->enclosingScope();

    while (scope && !scope->asFunction() )
        scope = scope->enclosingScope();

    if (!scope)
        return QString();

    // We found the function scope
    if (lineOpeningDeclaratorParenthesis)
        translationUnit()->getPosition(scope->startOffset(), lineOpeningDeclaratorParenthesis);

    if (lineClosingBrace)
        translationUnit()->getPosition(scope->endOffset(), lineClosingBrace);

    const QList<const Name *> fullyQualifiedName = LookupContext::fullyQualifiedName(scope);
    return Overview().prettyName(fullyQualifiedName);
}

Scope *Document::scopeAt(int line, int column)
{
    FindScopeAt findScopeAt(_translationUnit, line, column);
    if (Scope *scope = findScopeAt(_globalNamespace))
        return scope;
    return globalNamespace();
}

Symbol *Document::lastVisibleSymbolAt(int line, int column) const
{
    LastVisibleSymbolAt lastVisibleSymbolAt(globalNamespace());
    return lastVisibleSymbolAt(line, column);
}

const Macro *Document::findMacroDefinitionAt(int line) const
{
    for (const Macro &macro : std::as_const(_definedMacros)) {
        if (macro.line() == line)
            return &macro;
    }
    return nullptr;
}

const Document::MacroUse *Document::findMacroUseAt(int utf16charsOffset) const
{
    for (const Document::MacroUse &use : std::as_const(_macroUses)) {
        if (use.containsUtf16charOffset(utf16charsOffset)
                && (utf16charsOffset < use.utf16charsBegin() + use.macro().nameToQString().size())) {
            return &use;
        }
    }
    return nullptr;
}

const Document::UndefinedMacroUse *Document::findUndefinedMacroUseAt(int utf16charsOffset) const
{
    for (const Document::UndefinedMacroUse &use : std::as_const(_undefinedMacroUses)) {
        if (use.containsUtf16charOffset(utf16charsOffset)
                && (utf16charsOffset < use.utf16charsBegin()
                    + QString::fromUtf8(use.name(), use.name().size()).length()))
            return &use;
    }
    return nullptr;
}

Document::Ptr Document::create(const FilePath &filePath)
{
    Document::Ptr doc(new Document(filePath));
    return doc;
}

void Document::setUtf8Source(const QByteArray &source)
{
    _source = source;
    _translationUnit->setSource(_source.constData(), _source.size());
}

LanguageFeatures Document::languageFeatures() const
{
    if (TranslationUnit *tu = translationUnit())
        return tu->languageFeatures();
    return LanguageFeatures::defaultFeatures();
}

void Document::setLanguageFeatures(LanguageFeatures features)
{
    if (TranslationUnit *tu = translationUnit())
        tu->setLanguageFeatures(features);
}

void Document::startSkippingBlocks(int utf16charsOffset)
{
    _skippedBlocks.append(Block(0, 0, utf16charsOffset, 0));
}

void Document::stopSkippingBlocks(int utf16charsOffset)
{
    if (_skippedBlocks.isEmpty())
        return;

    int start = _skippedBlocks.back().utf16charsBegin();
    if (start > utf16charsOffset)
        _skippedBlocks.removeLast(); // Ignore this block, it's invalid.
    else
        _skippedBlocks.back() = Block(0, 0, start, utf16charsOffset);
}

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

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

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

bool Document::parse(ParseMode mode)
{
    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;

    case ParseDeclarator:
        m = TranslationUnit::ParseDeclarator;
        break;

    case ParseStatement:
        m = TranslationUnit::ParseStatement;
        break;

    default:
        break;
    }

    return _translationUnit->parse(m);
}

void Document::check(CheckMode mode)
{
    Q_ASSERT(!_globalNamespace);

    _checkMode = mode;

    if (! isParsed())
        parse();

    _globalNamespace = _control->newNamespace(0);
    Bind semantic(_translationUnit);
    if (mode == FastCheck)
        semantic.setSkipFunctionBodies(true);

    if (! _translationUnit->ast())
        return; // nothing to do.

    if (TranslationUnitAST *ast = _translationUnit->ast()->asTranslationUnit())
        semantic(ast, _globalNamespace);
    else if (StatementAST *ast = _translationUnit->ast()->asStatement())
        semantic(ast, _globalNamespace);
    else if (ExpressionAST *ast = _translationUnit->ast()->asExpression())
        semantic(ast, _globalNamespace);
    else if (DeclarationAST *ast = translationUnit()->ast()->asDeclaration())
        semantic(ast, _globalNamespace);
}

void Document::keepSourceAndAST()
{
    _keepSourceAndASTCount.ref();
}

void Document::releaseSourceAndAST()
{
    if (!_keepSourceAndASTCount.deref()) {
        _source.clear();
        _translationUnit->release();
    }
}

bool Document::DiagnosticMessage::operator==(const Document::DiagnosticMessage &other) const
{
    return
            _line == other._line &&
            _column == other._column &&
            _length == other._length &&
            _level == other._level &&
            _filePath == other._filePath &&
            _text == other._text;
}

bool Document::DiagnosticMessage::operator!=(const Document::DiagnosticMessage &other) const
{
    return !operator==(other);
}

Snapshot::Snapshot()
{
}

Snapshot::~Snapshot()
{
}

int Snapshot::size() const
{
    return _documents.size();
}

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

Snapshot::const_iterator Snapshot::find(const FilePath &filePath) const
{
    return _documents.find(filePath);
}

void Snapshot::remove(const FilePath &filePath)
{
    _documents.remove(filePath);
}

bool Snapshot::contains(const FilePath &filePath) const
{
    return _documents.contains(filePath);
}

void Snapshot::insert(Document::Ptr doc)
{
    if (doc) {
        _documents.insert(doc->filePath(), doc);
        m_deps.files.clear(); // Will trigger re-build when accessed.
    }
}

static QList<Macro> macrosDefinedUntilLine(const QList<Macro> &macros, int line)
{
    QList<Macro> filtered;

    for (const Macro &macro : macros) {
        if (macro.line() <= line)
            filtered.append(macro);
        else
            break;
    }

    return filtered;
}

Document::Ptr Snapshot::preprocessedDocument(const QByteArray &source,
                                             const FilePath &filePath,
                                             int withDefinedMacrosFromDocumentUntilLine) const
{
    Document::Ptr newDoc = Document::create(filePath);
    if (Document::Ptr thisDocument = document(filePath)) {
        newDoc->_revision = thisDocument->_revision;
        newDoc->_editorRevision = thisDocument->_editorRevision;
        newDoc->_lastModified = thisDocument->_lastModified;
        newDoc->_resolvedIncludes = thisDocument->_resolvedIncludes;
        newDoc->_unresolvedIncludes = thisDocument->_unresolvedIncludes;
        newDoc->setLanguageFeatures(thisDocument->languageFeatures());
        if (withDefinedMacrosFromDocumentUntilLine != -1) {
            newDoc->_definedMacros = macrosDefinedUntilLine(thisDocument->_definedMacros,
                                                            withDefinedMacrosFromDocumentUntilLine);
        }
    }

    FastPreprocessor pp(*this);
    const bool mergeDefinedMacrosOfDocument = !newDoc->_definedMacros.isEmpty();
    const QByteArray preprocessedCode = pp.run(newDoc, source, mergeDefinedMacrosOfDocument);
    newDoc->setUtf8Source(preprocessedCode);
    return newDoc;
}

Document::Ptr Snapshot::documentFromSource(const QByteArray &preprocessedCode,
                                           const FilePath &filePath) const
{
    Document::Ptr newDoc = Document::create(filePath);

    if (Document::Ptr thisDocument = document(filePath)) {
        newDoc->_revision = thisDocument->_revision;
        newDoc->_editorRevision = thisDocument->_editorRevision;
        newDoc->_lastModified = thisDocument->_lastModified;
        newDoc->_resolvedIncludes = thisDocument->_resolvedIncludes;
        newDoc->_unresolvedIncludes = thisDocument->_unresolvedIncludes;
        newDoc->_definedMacros = thisDocument->_definedMacros;
        newDoc->_macroUses = thisDocument->_macroUses;
        newDoc->setLanguageFeatures(thisDocument->languageFeatures());
    }

    newDoc->setUtf8Source(preprocessedCode);
    return newDoc;
}

QSet<FilePath> Snapshot::allIncludesForDocument(const FilePath &filePath) const
{
    QSet<FilePath> result;

    QStack<FilePath> files;
    files.push(filePath);

    while (!files.isEmpty()) {
        FilePath file = files.pop();
        if (Document::Ptr doc = document(file)) {
            const FilePaths includedFiles = doc->includedFiles(Document::Duplicates::Keep);
            for (const FilePath &inc : includedFiles) {
                if (Utils::insert(result, inc))
                    files.push(inc);
            }
        }
    }

    return result;
}

QList<Snapshot::IncludeLocation> Snapshot::includeLocationsOfDocument(
        const FilePath &fileNameOrPath) const
{
    const bool matchFullPath = fileNameOrPath.isAbsolutePath();
    const auto isMatch = [&](const Document::Include &include) {
        if (matchFullPath)
            return include.resolvedFileName() == fileNameOrPath;
        return include.resolvedFileName().fileName() == fileNameOrPath.fileName();
    };
    QList<IncludeLocation> result;
    for (const_iterator cit = begin(), citEnd = end(); cit != citEnd; ++cit) {
        const Document::Ptr doc = cit.value();
        const QList<Document::Include> includeFiles = doc->resolvedIncludes();
        bool foundMatch = false;
        for (const Document::Include &includeFile : includeFiles) {
            if (isMatch(includeFile)) {
                foundMatch = true;
                result.push_back({doc, includeFile.line()});
            }
        }
        if (!matchFullPath && !foundMatch) {
            for (const auto &includeFile : cit.value()->unresolvedIncludes()) {
                if (includeFile.unresolvedFileName() == fileNameOrPath.path())
                    result.push_back({doc, includeFile.line()});
            }
        }
    }
    return result;
}

FilePaths Snapshot::filesDependingOn(const FilePath &filePath) const
{
    updateDependencyTable();
    return m_deps.filesDependingOn(filePath);
}

void Snapshot::updateDependencyTable(const std::optional<QFuture<void>> &future) const
{
    if (m_deps.files.isEmpty())
        m_deps.build(future, *this);
}

bool Snapshot::operator==(const Snapshot &other) const
{
    return _documents == other._documents;
}

Document::Ptr Snapshot::document(const FilePath &filePath) const
{
    return _documents.value(filePath);
}

Snapshot Snapshot::simplified(Document::Ptr doc) const
{
    Snapshot snapshot;

    if (doc) {
        snapshot.insert(doc);
        const QSet<FilePath> filePaths = allIncludesForDocument(doc->filePath());
        for (const FilePath &filePath : filePaths)
            if (Document::Ptr inc = document(filePath))
                snapshot.insert(inc);
    }

    return snapshot;
}