File: topducontext.cpp

package info (click to toggle)
kdevelop 4%3A5.6.2-4
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 57,892 kB
  • sloc: cpp: 278,773; javascript: 3,558; python: 3,385; sh: 1,317; ansic: 689; xml: 273; php: 95; makefile: 40; lisp: 13; sed: 12
file content (1229 lines) | stat: -rw-r--r-- 46,018 bytes parent folder | download
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
858
859
860
861
862
863
864
865
866
867
868
869
870
871
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
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
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
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
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
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
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
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
/* This  is part of KDevelop
    Copyright 2006 Hamish Rodda <rodda@kde.org>
    Copyright 2007-2009 David Nolden <david.nolden.kdevelop@art-master.de>

   This library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Library General Public
   License version 2 as published by the Free Software Foundation.

   This library is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   Library General Public License for more details.

   You should have received a copy of the GNU Library General Public License
   along with this library; see the file COPYING.LIB.  If not, write to
   the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
   Boston, MA 02110-1301, USA.
 */

#include "topducontext.h"
#include "topducontextutils.h"

#include <limits>

#include "persistentsymboltable.h"
#include "problem.h"
#include "declaration.h"
#include "duchain.h"
#include "duchainlock.h"
#include "parsingenvironment.h"
#include "duchainpointer.h"
#include "declarationid.h"
#include "namespacealiasdeclaration.h"
#include "aliasdeclaration.h"
#include "uses.h"
#include "topducontextdata.h"
#include "duchainregister.h"
#include "topducontextdynamicdata.h"
#include <debug.h>

#include <language/interfaces/iastcontainer.h>

// #define DEBUG_SEARCH

const uint maxApplyAliasesRecursion = 100;

namespace KDevelop {
Utils::BasicSetRepository* RecursiveImportRepository::repository()
{
    static Utils::BasicSetRepository recursiveImportRepositoryObject(QStringLiteral(
            "Recursive Imports"), &KDevelop::globalItemRepositoryRegistry());
    return &recursiveImportRepositoryObject;
}

ReferencedTopDUContext::ReferencedTopDUContext(TopDUContext* context) : m_topContext(context)
{
    if (m_topContext)
        DUChain::self()->refCountUp(m_topContext);
}

ReferencedTopDUContext::ReferencedTopDUContext(const ReferencedTopDUContext& rhs) : m_topContext(rhs.m_topContext)
{
    if (m_topContext)
        DUChain::self()->refCountUp(m_topContext);
}

ReferencedTopDUContext::~ReferencedTopDUContext()
{
    if (m_topContext && !DUChain::deleted())
        DUChain::self()->refCountDown(m_topContext);
}

ReferencedTopDUContext& ReferencedTopDUContext::operator=(const ReferencedTopDUContext& rhs)
{
    if (m_topContext == rhs.m_topContext)
        return *this;

    if (m_topContext)
        DUChain::self()->refCountDown(m_topContext);

    m_topContext = rhs.m_topContext;

    if (m_topContext)
        DUChain::self()->refCountUp(m_topContext);
    return *this;
}

DEFINE_LIST_MEMBER_HASH(TopDUContextData, m_usedDeclarationIds, DeclarationId)
DEFINE_LIST_MEMBER_HASH(TopDUContextData, m_problems, LocalIndexedProblem)
REGISTER_DUCHAIN_ITEM(TopDUContext);

QMutex importStructureMutex(QMutex::Recursive);

//Contains data that is not shared among top-contexts that share their duchain entries
class TopDUContextLocalPrivate
{
public:
    TopDUContextLocalPrivate (TopDUContext* ctxt, uint index) :
        m_ctxt(ctxt)
        , m_ownIndex(index)
        , m_inDuChain(false)
    {
        m_indexedRecursiveImports.insert(index);
    }

    ~TopDUContextLocalPrivate()
    {
        //Either we use some other contexts data and have no users, or we own the data and have users that share it.
        QMutexLocker lock(&importStructureMutex);

        for (const DUContext::Import& import : qAsConst(m_importedContexts)) {
            if (DUChain::self()->isInMemory(import.topContextIndex()) &&
                dynamic_cast<TopDUContext*>(import.context(nullptr)))
                dynamic_cast<TopDUContext*>(import.context(nullptr))->m_local->m_directImporters.remove(m_ctxt);
        }
    }

    ///@todo Make all this work consistently together with import-caching

    //After loading, should rebuild the links
    void rebuildDynamicImportStructure()
    {
        //Currently we do not store the whole data in TopDUContextLocalPrivate, so we reconstruct it from what was stored by DUContext.
        Q_ASSERT(m_importedContexts.isEmpty());

        FOREACH_FUNCTION(const DUContext::Import& import, m_ctxt->d_func()->m_importedContexts) {
            if (DUChain::self()->isInMemory(import.topContextIndex())) {
                Q_ASSERT(import.context(nullptr));
                TopDUContext* top = import.context(nullptr)->topContext();
                Q_ASSERT(top);
                addImportedContextRecursively(top, false, true);
            }
        }
        FOREACH_FUNCTION(const IndexedDUContext &importer, m_ctxt->d_func()->m_importers) {
            if (DUChain::self()->isInMemory(importer.topContextIndex())) {
                Q_ASSERT(importer.context());
                TopDUContext* top = importer.context()->topContext();
                Q_ASSERT(top);
                top->m_local->addImportedContextRecursively(m_ctxt, false, true);
            }
        }
    }

    //Index of this top-context within the duchain
    //Since the data of top-contexts can be shared among multiple, this can be used to add imports that are local to this top-context.
    QVector<DUContext::Import> m_importedContexts;
//   mutable bool m_haveImportStructure : 1;
    TopDUContext* m_ctxt;

    QSet<DUContext*> m_directImporters;

    ParsingEnvironmentFilePointer m_file;

    QExplicitlySharedDataPointer<IAstContainer> m_ast;

    uint m_ownIndex;

    bool m_inDuChain;

    void clearImportedContextsRecursively()
    {
        QMutexLocker lock(&importStructureMutex);

//     Q_ASSERT(m_recursiveImports.size() == m_indexedRecursiveImports.count()-1);

        QSet<QPair<TopDUContext*, const TopDUContext*>> rebuild;

        for (const DUContext::Import& import : qAsConst(m_importedContexts)) {
            auto* top = dynamic_cast<TopDUContext*>(import.context(nullptr));
            if (top) {
                top->m_local->m_directImporters.remove(m_ctxt);

                if (!m_ctxt->usingImportsCache()) {
                    removeImportedContextRecursion(top, top, 1, rebuild);

                    QHash<const TopDUContext*, QPair<int, const TopDUContext*>> b = top->m_local->m_recursiveImports;
                    for (RecursiveImports::const_iterator it = b.constBegin(); it != b.constEnd(); ++it) {
                        if (m_recursiveImports.contains(it.key()) && m_recursiveImports[it.key()].second == top)
                            removeImportedContextRecursion(top, it.key(), it->first + 1, rebuild); //Remove all contexts that are imported through the context
                    }
                }
            }
        }

        m_importedContexts.clear();

        rebuildImportStructureRecursion(rebuild);

        Q_ASSERT(m_recursiveImports.isEmpty());
//     Q_ASSERT(m_recursiveImports.size() == m_indexedRecursiveImports.count()-1);
    }

    //Adds the context to this and all contexts that import this, and manages m_recursiveImports
    void addImportedContextRecursively(TopDUContext* context, bool temporary, bool local)
    {
        QMutexLocker lock(&importStructureMutex);

        context->m_local->m_directImporters.insert(m_ctxt);

        if (local) {
            // note: m_importedContexts may end up with duplicate entries -- not sure whether we should protect against this --Kevin
            m_importedContexts << DUContext::Import(context, m_ctxt);
        }

        if (!m_ctxt->usingImportsCache()) {
            addImportedContextRecursion(context, context, 1, temporary);

            QHash<const TopDUContext*, QPair<int, const TopDUContext*>> b = context->m_local->m_recursiveImports;
            for (RecursiveImports::const_iterator it = b.constBegin(); it != b.constEnd(); ++it)
                addImportedContextRecursion(context, it.key(), (*it).first + 1, temporary); //Add contexts that were imported earlier into the given one
        }
    }

    //Removes the context from this and all contexts that import this, and manages m_recursiveImports
    void removeImportedContextRecursively(TopDUContext* context, bool local)
    {
        QMutexLocker lock(&importStructureMutex);

        context->m_local->m_directImporters.remove(m_ctxt);

        if (local)
            m_importedContexts.removeAll(DUContext::Import(context, m_ctxt));

        QSet<QPair<TopDUContext*, const TopDUContext*>> rebuild;
        if (!m_ctxt->usingImportsCache()) {
            removeImportedContextRecursion(context, context, 1, rebuild);

            QHash<const TopDUContext*, QPair<int, const TopDUContext*>> b = context->m_local->m_recursiveImports;
            for (RecursiveImports::const_iterator it = b.constBegin(); it != b.constEnd(); ++it) {
                if (m_recursiveImports.contains(it.key()) && m_recursiveImports[it.key()].second == context)
                    removeImportedContextRecursion(context, it.key(), it->first + 1, rebuild); //Remove all contexts that are imported through the context
            }
        }

        rebuildImportStructureRecursion(rebuild);
    }

    void removeImportedContextsRecursively(const QList<TopDUContext*>& contexts, bool local)
    {
        QMutexLocker lock(&importStructureMutex);

        QSet<QPair<TopDUContext*, const TopDUContext*>> rebuild;
        for (TopDUContext* context : contexts) {
            context->m_local->m_directImporters.remove(m_ctxt);

            if (local)
                m_importedContexts.removeAll(DUContext::Import(context, m_ctxt));

            if (!m_ctxt->usingImportsCache()) {
                removeImportedContextRecursion(context, context, 1, rebuild);

                QHash<const TopDUContext*, QPair<int, const TopDUContext*>> b = context->m_local->m_recursiveImports;
                for (RecursiveImports::const_iterator it = b.constBegin(); it != b.constEnd(); ++it) {
                    const auto recursiveImportIt = m_recursiveImports.constFind(it.key());
                    if (recursiveImportIt != m_recursiveImports.constEnd() && recursiveImportIt->second == context)
                        removeImportedContextRecursion(context, it.key(), it->first + 1, rebuild); //Remove all contexts that are imported through the context
                }
            }
        }

        rebuildImportStructureRecursion(rebuild);
    }

    //Has an entry for every single recursively imported file, that contains the shortest path, and the next context on that path to the imported context.
    //This does not need to be stored to disk, because it is defined implicitly.
    //What makes this most complicated is the fact that loops are allowed in the import structure.
    using RecursiveImports = QHash<const TopDUContext*, QPair<int, const TopDUContext*>>;
    mutable RecursiveImports m_recursiveImports;
    mutable TopDUContext::IndexedRecursiveImports m_indexedRecursiveImports;

private:
    void addImportedContextRecursion(const TopDUContext* traceNext, const TopDUContext* imported, int depth,
                                     bool temporary = false)
    {
        if (m_ctxt->usingImportsCache())
            return;

//     if(!m_haveImportStructure)
//       return;

        if (imported == m_ctxt)
            return;

        const bool computeShortestPaths = false; ///@todo We do not compute the shortest path. Think what's right.

//     traceNext->m_local->needImportStructure();
//     imported->m_local->needImportStructure();

        RecursiveImports::iterator it = m_recursiveImports.find(imported);
        if (it == m_recursiveImports.end()) {
            //Insert new path to "imported"
            m_recursiveImports[imported] = qMakePair(depth, traceNext);

            m_indexedRecursiveImports.insert(imported->indexed());
//       Q_ASSERT(m_indexedRecursiveImports.size() == m_recursiveImports.size()+1);

            Q_ASSERT(traceNext != m_ctxt);
        } else {
            if (!computeShortestPaths)
                return;

            if (temporary) //For temporary imports, we don't record the best path.
                return;
            //It would be better if we would use the following code, but it creates too much cost in updateImportedContextRecursion when imports are removed again.

            //Check whether the new way to "imported" is shorter than the stored one
            if ((*it).first > depth) {
                //Add a shorter path
                (*it).first = depth;
                Q_ASSERT(traceNext);
                (*it).second = traceNext;
                Q_ASSERT(traceNext == imported ||
                         (traceNext->m_local->m_recursiveImports.contains(imported) &&
                          traceNext->m_local->m_recursiveImports[imported].first < (*it).first));
            } else {
                //The imported context is already imported through a same/better path, so we can just stop processing. This saves us from endless recursion.
                return;
            }
        }

        if (temporary)
            return;

        for (auto* context : qAsConst(m_directImporters)) {
            auto* top = dynamic_cast<TopDUContext*>(context);
            if (top) ///@todo also record this for local imports
                top->m_local->addImportedContextRecursion(m_ctxt, imported, depth + 1);
        }
    }

    void removeImportedContextRecursion(const TopDUContext* traceNext, const TopDUContext* imported, int distance,
                                        QSet<QPair<TopDUContext*, const TopDUContext*>>& rebuild)
    {
        if (m_ctxt->usingImportsCache())
            return;

        if (imported == m_ctxt)
            return;

//     if(!m_haveImportStructure)
//       return;

        RecursiveImports::iterator it = m_recursiveImports.find(imported);
        if (it == m_recursiveImports.end()) {
            //We don't import. Just return, this saves us from endless recursion.
            return;
        } else {
            //Check whether we have imported "imported" through "traceNext". If not, return. Else find a new trace.
            if ((*it).second == traceNext && (*it).first == distance) {
                //We need to remove the import through traceNext. Check whether there is another imported context that imports it.

                m_recursiveImports.erase(it); //In order to prevent problems, we completely remove everything, and re-add it.
                                              //Just updating these complex structures is very hard.
                Q_ASSERT(imported != m_ctxt);

                m_indexedRecursiveImports.remove(imported->indexed());
//         Q_ASSERT(m_indexedRecursiveImports.size() == m_recursiveImports.size());

                rebuild.insert(qMakePair(m_ctxt, imported));
                //We MUST do this before finding another trace, because else we would create loops
                for (QSet<DUContext*>::const_iterator childIt = m_directImporters.constBegin();
                     childIt != m_directImporters.constEnd(); ++childIt) {
                    auto* top = dynamic_cast<TopDUContext*>(const_cast<DUContext*>(*childIt)); //Avoid detaching, so use const iterator
                    if (top)
                        top->m_local->removeImportedContextRecursion(m_ctxt, imported, distance + 1, rebuild); //Don't use 'it' from here on, it may be invalid
                }
            }
        }
    }

    //Updates the trace to 'imported'
    void rebuildStructure(const TopDUContext* imported);

    void rebuildImportStructureRecursion(const QSet<QPair<TopDUContext*, const TopDUContext*>>& rebuild)
    {
        for (auto& rebuildPair : rebuild) {
            //for(int a = rebuild.size()-1; a >= 0; --a) {
            //Find the best imported parent
            rebuildPair.first->m_local->rebuildStructure(rebuildPair.second);
        }
    }
};

const TopDUContext::IndexedRecursiveImports& TopDUContext::recursiveImportIndices() const
{
//   No lock-check for performance reasons
    QMutexLocker lock(&importStructureMutex);
    if (!d_func()->m_importsCache.isEmpty())
        return d_func()->m_importsCache;

    return m_local->m_indexedRecursiveImports;
}

void TopDUContextData::updateImportCacheRecursion(uint baseIndex, IndexedTopDUContext currentContext,
                                                  TopDUContext::IndexedRecursiveImports& visited)
{
    if (visited.contains(currentContext.index()))
        return;
    Q_ASSERT(currentContext.index()); //The top-context must be in the repository when this is called
    if (!currentContext.data()) {
        qCDebug(LANGUAGE) << "importing invalid context";
        return;
    }
    visited.insert(currentContext.index());

    const TopDUContextData* currentData = currentContext.data()->topContext()->d_func();
    if (currentData->m_importsCache.contains(baseIndex) || currentData->m_importsCache.isEmpty()) {
        //If we have a loop or no imports-cache is used, we have to look at each import separately.
        const KDevelop::DUContext::Import* imports = currentData->m_importedContexts();
        uint importsSize = currentData->m_importedContextsSize();
        for (uint a = 0; a < importsSize; ++a) {
            IndexedTopDUContext next(imports[a].topContextIndex());
            if (next.isValid())
                updateImportCacheRecursion(baseIndex, next, visited);
        }
    } else {
        //If we don't have a loop with baseIndex, we can safely just merge with the imported importscache
        visited += currentData->m_importsCache;
    }
}

void TopDUContextData::updateImportCacheRecursion(IndexedTopDUContext currentContext, std::set<uint>& visited)
{
    if (visited.find(currentContext.index()) != visited.end())
        return;
    Q_ASSERT(currentContext.index()); //The top-context must be in the repository when this is called
    if (!currentContext.data()) {
        qCDebug(LANGUAGE) << "importing invalid context";
        return;
    }
    visited.insert(currentContext.index());
    const TopDUContextData* currentData = currentContext.data()->topContext()->d_func();
    const KDevelop::DUContext::Import* imports = currentData->m_importedContexts();
    uint importsSize = currentData->m_importedContextsSize();
    for (uint a = 0; a < importsSize; ++a) {
        IndexedTopDUContext next(imports[a].topContextIndex());
        if (next.isValid())
            updateImportCacheRecursion(next, visited);
    }
}

void TopDUContext::updateImportsCache()
{
    QMutexLocker lock(&importStructureMutex);

    const bool use_fully_recursive_import_cache_computation = false;

    if (use_fully_recursive_import_cache_computation) {
        std::set<uint> visited;
        TopDUContextData::updateImportCacheRecursion(this, visited);
        Q_ASSERT(visited.find(ownIndex()) != visited.end());
        d_func_dynamic()->m_importsCache = IndexedRecursiveImports(visited);
    } else {
        d_func_dynamic()->m_importsCache = IndexedRecursiveImports();
        TopDUContextData::updateImportCacheRecursion(ownIndex(), this, d_func_dynamic()->m_importsCache);
    }
    Q_ASSERT(d_func_dynamic()->m_importsCache.contains(IndexedTopDUContext(this)));
    Q_ASSERT(usingImportsCache());
    Q_ASSERT(imports(this, CursorInRevision::invalid()));

    if (parsingEnvironmentFile())
        parsingEnvironmentFile()->setImportsCache(d_func()->m_importsCache);
}

bool TopDUContext::usingImportsCache() const
{
    return !d_func()->m_importsCache.isEmpty();
}

CursorInRevision TopDUContext::importPosition(const DUContext* target) const
{
    ENSURE_CAN_READ
        DUCHAIN_D(DUContext);
    Import import(const_cast<DUContext*>(target), const_cast<TopDUContext*>(this), CursorInRevision::invalid());
    for (unsigned int a = 0; a < d->m_importedContextsSize(); ++a)
        if (d->m_importedContexts()[a] == import)
            return d->m_importedContexts()[a].position;

    return DUContext::importPosition(target);
}

void TopDUContextLocalPrivate::rebuildStructure(const TopDUContext* imported)
{
    if (m_ctxt == imported)
        return;

    for (auto& importedContext : qAsConst(m_importedContexts)) {
        auto* top = dynamic_cast<TopDUContext*>(importedContext.context(nullptr));
        if (top) {
//       top->m_local->needImportStructure();
            if (top == imported) {
                addImportedContextRecursion(top, imported, 1);
            } else {
                RecursiveImports::const_iterator it2 = top->m_local->m_recursiveImports.constFind(imported);
                if (it2 != top->m_local->m_recursiveImports.constEnd()) {
                    addImportedContextRecursion(top, imported, (*it2).first + 1);
                }
            }
        }
    }

    for (unsigned int a = 0; a < m_ctxt->d_func()->m_importedContextsSize(); ++a) {
        auto* top =
            dynamic_cast<TopDUContext*>(const_cast<DUContext*>(m_ctxt->d_func()->m_importedContexts()[a].context(nullptr)));           //To avoid detaching, use const iterator
        if (top) {
//       top->m_local->needImportStructure();
            if (top == imported) {
                addImportedContextRecursion(top, imported, 1);
            } else {
                RecursiveImports::const_iterator it2 = top->m_local->m_recursiveImports.constFind(imported);
                if (it2 != top->m_local->m_recursiveImports.constEnd()) {
                    addImportedContextRecursion(top, imported, (*it2).first + 1);
                }
            }
        }
    }
}

void TopDUContext::rebuildDynamicImportStructure()
{
    m_local->rebuildDynamicImportStructure();
}

void TopDUContext::rebuildDynamicData(DUContext* parent, uint ownIndex)
{
    Q_ASSERT(parent == nullptr && ownIndex != 0);
    m_local->m_ownIndex = ownIndex;

    DUContext::rebuildDynamicData(parent, 0);
}

IndexedTopDUContext TopDUContext::indexed() const
{
    return IndexedTopDUContext(m_local->m_ownIndex);
}

uint TopDUContext::ownIndex() const
{
    return m_local->m_ownIndex;
}

TopDUContext::TopDUContext(TopDUContextData& data) : DUContext(data)
    , m_local(new TopDUContextLocalPrivate(this, data.m_ownIndex))
    , m_dynamicData(new TopDUContextDynamicData(this))
{
}

TopDUContext::TopDUContext(const IndexedString& url, const RangeInRevision& range, ParsingEnvironmentFile* file)
    : DUContext(*new TopDUContextData(url), range)
    , m_local(new TopDUContextLocalPrivate(this, DUChain::newTopContextIndex()))
    , m_dynamicData(new TopDUContextDynamicData(this))
{
    Q_ASSERT(url.toUrl().isValid() && !url.toUrl().isRelative());
    d_func_dynamic()->setClassId(this);
    setType(Global);

    DUCHAIN_D_DYNAMIC(TopDUContext);
    d->m_features = VisibleDeclarationsAndContexts;
    d->m_ownIndex = m_local->m_ownIndex;
    setParsingEnvironmentFile(file);
    setInSymbolTable(true);
}

QExplicitlySharedDataPointer<ParsingEnvironmentFile> TopDUContext::parsingEnvironmentFile() const
{
    return m_local->m_file;
}

TopDUContext::~TopDUContext()
{
    m_dynamicData->m_deleting = true;

    //Clear the AST, so that the 'feature satisfaction' cache is eventually updated
    clearAst();

    if (!isOnDisk()) {
        //Clear the 'feature satisfaction' cache which is managed in ParsingEnvironmentFile
        setFeatures(Empty);

        clearUsedDeclarationIndices();
    }

    deleteChildContextsRecursively();
    deleteLocalDeclarations();
    m_dynamicData->clear();
}

void TopDUContext::deleteSelf()
{
    //We've got to make sure that m_dynamicData and m_local are still valid while all the sub-contexts are destroyed
    TopDUContextLocalPrivate* local = m_local;
    TopDUContextDynamicData* dynamicData = m_dynamicData;

    m_dynamicData->m_deleting = true;

    delete this;

    delete local;
    delete dynamicData;
}

TopDUContext::Features TopDUContext::features() const
{
    uint ret = d_func()->m_features;

    if (ast())
        ret |= TopDUContext::AST;

    return ( TopDUContext::Features )ret;
}

void TopDUContext::setFeatures(Features features)
{
    features = ( TopDUContext::Features )(features & (~Recursive)); //Remove the "Recursive" flag since that's only for searching
    features = ( TopDUContext::Features )(features & (~ForceUpdateRecursive)); //Remove the update flags
    features = ( TopDUContext::Features )(features & (~AST)); //Remove the AST flag, it's only used while updating
    d_func_dynamic()->m_features = features;

    //Replicate features to ParsingEnvironmentFile
    if (parsingEnvironmentFile())
        parsingEnvironmentFile()->setFeatures(this->features());
}

void TopDUContext::setAst(const QExplicitlySharedDataPointer<IAstContainer>& ast)
{
    ENSURE_CAN_WRITE
    m_local->m_ast = ast;

    if (parsingEnvironmentFile())
        parsingEnvironmentFile()->setFeatures(features());
}

void TopDUContext::setParsingEnvironmentFile(ParsingEnvironmentFile* file)
{
    if (m_local->m_file) //Clear the "feature satisfaction" cache
        m_local->m_file->setFeatures(Empty);

    //We do not enforce a duchain lock here, since this is also used while loading a top-context
    m_local->m_file = QExplicitlySharedDataPointer<ParsingEnvironmentFile>(file);

    //Replicate features to ParsingEnvironmentFile
    if (file) {
        file->setTopContext(IndexedTopDUContext(ownIndex()));
        Q_ASSERT(file->indexedTopContext().isValid());
        file->setFeatures(d_func()->m_features);

        file->setImportsCache(d_func()->m_importsCache);
    }
}

struct TopDUContext::FindDeclarationsAcceptor
{
    FindDeclarationsAcceptor(const TopDUContext* _top, DeclarationList& _target, const DeclarationChecker& _check,
                             SearchFlags _flags) : top(_top)
        , target(_target)
        , check(_check)
    {
        flags = _flags;
    }

    bool operator()(const QualifiedIdentifier& id)
    {
#ifdef DEBUG_SEARCH
        qCDebug(LANGUAGE) << "accepting" << id.toString();
#endif

        PersistentSymbolTable::Declarations allDecls;

        //This iterator efficiently filters the visible declarations out of all declarations
        PersistentSymbolTable::FilteredDeclarationIterator filter;

        //This is used if filtering is disabled
        PersistentSymbolTable::Declarations::Iterator unchecked;
        if (check.flags & DUContext::NoImportsCheck) {
            allDecls = PersistentSymbolTable::self().declarations(id);
            unchecked = allDecls.iterator();
        } else
            filter = PersistentSymbolTable::self().filteredDeclarations(id, top->recursiveImportIndices());

        while (filter || unchecked) {
            IndexedDeclaration iDecl;
            if (filter) {
                iDecl = *filter;
                ++filter;
            } else {
                iDecl = *unchecked;
                ++unchecked;
            }
            Declaration* decl = iDecl.data();

            if (!decl)
                continue;

            if (!check(decl))
                continue;

            if (!(flags & DontResolveAliases) && decl->kind() == Declaration::Alias) {
                //Apply alias declarations
                auto* alias = static_cast<AliasDeclaration*>(decl);
                if (alias->aliasedDeclaration().isValid()) {
                    decl = alias->aliasedDeclaration().declaration();
                } else {
                    qCDebug(LANGUAGE) << "lost aliased declaration";
                }
            }

            target.append(decl);
        }

        check.createVisibleCache = nullptr;

        return !top->foundEnough(target, flags);
    }

    const TopDUContext* top;
    DeclarationList& target;
    const DeclarationChecker& check;
    QFlags<KDevelop::DUContext::SearchFlag> flags;
};

bool TopDUContext::findDeclarationsInternal(const SearchItem::PtrList& identifiers, const CursorInRevision& position,
                                            const AbstractType::Ptr& dataType, DeclarationList& ret,
                                            const TopDUContext* /*source*/, SearchFlags flags, uint /*depth*/) const
{
    ENSURE_CAN_READ

#ifdef DEBUG_SEARCH
    for (const SearchItem::Ptr& idTree : identifiers) {
        const auto ids = idTree->toList();
        for (const QualifiedIdentifier& id : ids) {
            qCDebug(LANGUAGE) << "searching item" << id.toString();
        }
    }

#endif

    DeclarationChecker check(this, position, dataType, flags);
    FindDeclarationsAcceptor storer(this, ret, check, flags);

    ///The actual scopes are found within applyAliases, and each complete qualified identifier is given to FindDeclarationsAcceptor.
    ///That stores the found declaration to the output.
    applyAliases(identifiers, storer, position, false);

    return true;
}

//This is used to prevent endless recursion due to "using namespace .." declarations, by storing all imports that are already being used.
struct TopDUContext::ApplyAliasesBuddyInfo
{
    ApplyAliasesBuddyInfo(uint importChainType, ApplyAliasesBuddyInfo* predecessor,
                          const IndexedQualifiedIdentifier& importId) : m_importChainType(importChainType)
        , m_predecessor(predecessor)
        , m_importId(importId)
    {
        if (m_predecessor && m_predecessor->m_importChainType != importChainType)
            m_predecessor = nullptr;
    }

    bool alreadyImporting(const IndexedQualifiedIdentifier& id)
    {
        ApplyAliasesBuddyInfo* current = this;
        while (current) {
            if (current->m_importId == id)
                return true;
            current = current->m_predecessor;
        }
        return false;
    }

    uint m_importChainType;
    ApplyAliasesBuddyInfo* m_predecessor;
    IndexedQualifiedIdentifier m_importId;
};

///@todo Implement a cache so at least the global import checks don't need to be done repeatedly. The cache should be thread-local, using DUChainPointer for the hashed items, and when an item was deleted, it should be discarded
template <class Acceptor>
bool TopDUContext::applyAliases(const QualifiedIdentifier& previous, const SearchItem::Ptr& identifier,
                                Acceptor& accept, const CursorInRevision& position, bool canBeNamespace,
                                ApplyAliasesBuddyInfo* buddy, uint recursionDepth) const
{
    if (recursionDepth > maxApplyAliasesRecursion) {
        const auto searches = identifier->toList();
        QualifiedIdentifier id;
        if (!searches.isEmpty())
            id = searches.first();

        qCDebug(LANGUAGE) << "maximum apply-aliases recursion reached while searching" << id;
    }
    bool foundAlias = false;

    QualifiedIdentifier id(previous);
    id.push(identifier->identifier);

    if (!id.inRepository())
        return true; //If the qualified identifier is not in the identifier repository, it cannot be registered anywhere, so there's nothing we need to do

    if (!identifier->next.isEmpty() || canBeNamespace) { //If it cannot be a namespace, the last part of the scope will be ignored
        //Search for namespace-aliases, by using globalAliasIdentifier, which is inserted into the symbol-table by NamespaceAliasDeclaration
        QualifiedIdentifier aliasId(id);
        aliasId.push(globalIndexedAliasIdentifier());

#ifdef DEBUG_SEARCH
        qCDebug(LANGUAGE) << "checking" << id.toString();
#endif

        if (aliasId.inRepository()) {
            //This iterator efficiently filters the visible declarations out of all declarations
            PersistentSymbolTable::FilteredDeclarationIterator filter =
                PersistentSymbolTable::self().filteredDeclarations(aliasId, recursiveImportIndices());

            if (filter) {
                DeclarationChecker check(this, position, AbstractType::Ptr(), NoSearchFlags, nullptr);

                //The first part of the identifier has been found as a namespace-alias.
                //In c++, we only need the first alias. However, just to be correct, follow them all for now.
                for (; filter; ++filter) {
                    Declaration* aliasDecl = filter->data();
                    if (!aliasDecl)
                        continue;

                    if (!check(aliasDecl))
                        continue;

                    if (aliasDecl->kind() != Declaration::NamespaceAlias)
                        continue;

                    if (foundAlias)
                        break;

                    Q_ASSERT(dynamic_cast<NamespaceAliasDeclaration*>(aliasDecl));

                    auto* alias = static_cast<NamespaceAliasDeclaration*>(aliasDecl);

                    foundAlias = true;

                    QualifiedIdentifier importIdentifier = alias->importIdentifier();

                    if (importIdentifier.isEmpty()) {
                        qCDebug(LANGUAGE) << "found empty import";
                        continue;
                    }

                    if (buddy && buddy->alreadyImporting(importIdentifier))
                        continue; //This import has already been applied to this search

                    ApplyAliasesBuddyInfo info(1, buddy, importIdentifier);

                    if (identifier->next.isEmpty()) {
                        //Just insert the aliased namespace identifier
                        if (!accept(importIdentifier))
                            return false;
                    } else {
                        //Create an identifiers where namespace-alias part is replaced with the alias target
                        for (const SearchItem::Ptr& item : qAsConst(identifier->next)) {
                            if (!applyAliases(importIdentifier, item, accept, position, canBeNamespace, &info,
                                              recursionDepth + 1))
                                return false;
                        }
                    }
                }
            }
        }
    }

    if (!foundAlias) { //If we haven't found an alias, put the current versions into the result list. Additionally we will compute the identifiers transformed through "using".
        if (identifier->next.isEmpty()) {
            if (!accept(id)) //We're at the end of a qualified identifier, accept it
                return false;
        } else {
            for (const SearchItem::Ptr& next : qAsConst(identifier->next)) {
                if (!applyAliases(id, next, accept, position, canBeNamespace, nullptr, recursionDepth + 1))
                    return false;
            }
        }
    }

    /*if( !prefix.explicitlyGlobal() || !prefix.isEmpty() ) {*/ ///@todo check iso c++ if using-directives should be respected on top-level when explicitly global
    ///@todo this is bad for a very big repository(the chains should be walked for the top-context instead)

    //Find all namespace-imports at given scope

    {
        QualifiedIdentifier importId(previous);
        importId.push(globalIndexedImportIdentifier());

#ifdef DEBUG_SEARCH
//   qCDebug(LANGUAGE) << "checking imports in" << (backPointer ? id.toString() : QStringLiteral("global"));
#endif

        if (importId.inRepository()) {
            //This iterator efficiently filters the visible declarations out of all declarations
            PersistentSymbolTable::FilteredDeclarationIterator filter =
                PersistentSymbolTable::self().filteredDeclarations(importId, recursiveImportIndices());

            if (filter) {
                DeclarationChecker check(this, position, AbstractType::Ptr(), NoSearchFlags, nullptr);

                for (; filter; ++filter) {
                    Declaration* importDecl = filter->data();
                    if (!importDecl)
                        continue;

                    //We must never break or return from this loop, because else we might be creating a bad cache
                    if (!check(importDecl))
                        continue;

                    //Search for the identifier with the import-identifier prepended
                    Q_ASSERT(dynamic_cast<NamespaceAliasDeclaration*>(importDecl));
                    auto* alias = static_cast<NamespaceAliasDeclaration*>(importDecl);

  #ifdef DEBUG_SEARCH
                    qCDebug(LANGUAGE) << "found import of" << alias->importIdentifier().toString();
  #endif

                    QualifiedIdentifier importIdentifier = alias->importIdentifier();

                    if (importIdentifier.isEmpty()) {
                        qCDebug(LANGUAGE) << "found empty import";
                        continue;
                    }

                    if (buddy && buddy->alreadyImporting(importIdentifier))
                        continue; //This import has already been applied to this search

                    ApplyAliasesBuddyInfo info(2, buddy, importIdentifier);

                    if (previous != importIdentifier)
                        if (!applyAliases(importIdentifier, identifier, accept,
                                          importDecl->topContext() == this ? importDecl->range().start : position,
                                          canBeNamespace,
                                          &info, recursionDepth + 1))
                            return false;
                }
            }
        }
    }
    return true;
}

template <class Acceptor>
void TopDUContext::applyAliases(const SearchItem::PtrList& identifiers, Acceptor& acceptor,
                                const CursorInRevision& position, bool canBeNamespace) const
{
    QualifiedIdentifier emptyId;

    for (const SearchItem::Ptr& item : identifiers)
        applyAliases(emptyId, item, acceptor, position, canBeNamespace, nullptr, 0);
}

TopDUContext* TopDUContext::topContext() const
{
    return const_cast<TopDUContext*>(this);
}

bool TopDUContext::deleting() const
{
    return m_dynamicData->m_deleting;
}

QList<ProblemPointer> TopDUContext::problems() const
{
    ENSURE_CAN_READ

    const auto data = d_func();
    QList<ProblemPointer> ret;
    ret.reserve(data->m_problemsSize());
    for (uint i = 0; i < data->m_problemsSize(); ++i) {
        ret << ProblemPointer(data->m_problems()[i].data(this));
    }

    return ret;
}

void TopDUContext::setProblems(const QList<ProblemPointer>& problems)
{
    ENSURE_CAN_WRITE
        clearProblems();
    for (const auto& problem : problems) {
        addProblem(problem);
    }
}

void TopDUContext::addProblem(const ProblemPointer& problem)
{
    ENSURE_CAN_WRITE

        Q_ASSERT(problem);

    auto data = d_func_dynamic();
    // store for indexing
    LocalIndexedProblem indexedProblem(problem, this);
    Q_ASSERT(indexedProblem.isValid());
    data->m_problemsList().append(indexedProblem);
    Q_ASSERT(indexedProblem.data(this));
}

void TopDUContext::clearProblems()
{
    ENSURE_CAN_WRITE
        d_func_dynamic()->m_problemsList().clear();
    m_dynamicData->clearProblems();
}

QVector<DUContext*> TopDUContext::importers() const
{
    ENSURE_CAN_READ
#if QT_VERSION >= QT_VERSION_CHECK(5, 14, 0)
    const QSet<DUContext*>& directImporters = m_local->m_directImporters;
    return QVector<DUContext*>(directImporters.begin(), directImporters.end());
#else
    return QVector<DUContext*>::fromList(m_local->m_directImporters.values());
#endif
}

QList<DUContext*> TopDUContext::loadedImporters() const
{
    ENSURE_CAN_READ
    return m_local->m_directImporters.values();
}

QVector<DUContext::Import> TopDUContext::importedParentContexts() const
{
    ENSURE_CAN_READ
    return DUContext::importedParentContexts();
}

bool TopDUContext::imports(const DUContext* origin, const CursorInRevision& position) const
{
    return importsPrivate(origin, position);
}

bool TopDUContext::importsPrivate(const DUContext* origin, const CursorInRevision& position) const
{
    Q_UNUSED(position);

    if (const auto* top = dynamic_cast<const TopDUContext*>(origin)) {
        QMutexLocker lock(&importStructureMutex);
        bool ret = recursiveImportIndices().contains(IndexedTopDUContext(const_cast<TopDUContext*>(top)));
        if (top == this)
            Q_ASSERT(ret);
        return ret;
    } else {
        //Cannot import a non top-context
        return false;
    }
}

void TopDUContext::clearImportedParentContexts()
{
    if (usingImportsCache()) {
        d_func_dynamic()->m_importsCache = IndexedRecursiveImports();
        d_func_dynamic()->m_importsCache.insert(IndexedTopDUContext(this));
    }

    DUContext::clearImportedParentContexts();

    m_local->clearImportedContextsRecursively();

    Q_ASSERT(m_local->m_recursiveImports.count() == 0);

    Q_ASSERT(m_local->m_indexedRecursiveImports.count() == 1);

    Q_ASSERT(imports(this, CursorInRevision::invalid()));
}

void TopDUContext::addImportedParentContext(DUContext* context, const CursorInRevision& position, bool anonymous,
                                            bool temporary)
{
    if (context == this)
        return;

    if (!dynamic_cast<TopDUContext*>(context)) {
        //We cannot do this, because of the extended way we treat top-context imports.
        qCDebug(LANGUAGE) << "tried to import a non top-context into a top-context. This is not possible.";
        return;
    }

    //Always make the contexts anonymous, because we care about importers in TopDUContextLocalPrivate
    DUContext::addImportedParentContext(context, position, anonymous, temporary);

    m_local->addImportedContextRecursively(static_cast<TopDUContext*>(context), temporary, true);
}

void TopDUContext::removeImportedParentContext(DUContext* context)
{
    DUContext::removeImportedParentContext(context);

    m_local->removeImportedContextRecursively(static_cast<TopDUContext*>(context), true);
}

void TopDUContext::addImportedParentContexts(const QVector<QPair<TopDUContext*, CursorInRevision>>& contexts,
                                             bool temporary)
{
    using Pair = QPair<TopDUContext*, CursorInRevision>;

    for (const Pair pair : contexts) {
        addImportedParentContext(pair.first, pair.second, false, temporary);
    }
}

void TopDUContext::removeImportedParentContexts(const QList<TopDUContext*>& contexts)
{
    for (TopDUContext* context : contexts) {
        DUContext::removeImportedParentContext(context);
    }

    m_local->removeImportedContextsRecursively(contexts, true);
}

/// Returns true if this object is registered in the du-chain. If it is not, all sub-objects(context, declarations, etc.)
bool TopDUContext::inDUChain() const
{
    return m_local->m_inDuChain;
}

/// This flag is only used by DUChain, never change it from outside.
void TopDUContext::setInDuChain(bool b)
{
    m_local->m_inDuChain = b;
}

bool TopDUContext::isOnDisk() const
{
    ///@todo Change this to releasingToDisk, and only enable it while saving a top-context to disk.
    return m_dynamicData->isOnDisk();
}

void TopDUContext::clearUsedDeclarationIndices()
{
    ENSURE_CAN_WRITE
    for (unsigned int a = 0; a < d_func()->m_usedDeclarationIdsSize(); ++a)
        DUChain::uses()->removeUse(d_func()->m_usedDeclarationIds()[a], this);

    d_func_dynamic()->m_usedDeclarationIdsList().clear();
}

void TopDUContext::deleteUsesRecursively()
{
    clearUsedDeclarationIndices();
    KDevelop::DUContext::deleteUsesRecursively();
}

Declaration* TopDUContext::usedDeclarationForIndex(unsigned int declarationIndex) const
{
    ENSURE_CAN_READ
    if (declarationIndex & (1 << 31)) {
        //We use the highest bit to mark direct indices into the local declarations
        declarationIndex &= ~(1 << 31); //unset the highest bit
        return m_dynamicData->declarationForIndex(declarationIndex);
    } else if (declarationIndex < d_func()->m_usedDeclarationIdsSize())
        return d_func()->m_usedDeclarationIds()[declarationIndex].declaration(this);
    else
        return nullptr;
}

int TopDUContext::indexForUsedDeclaration(Declaration* declaration, bool create)
{
    if (create) {
        ENSURE_CAN_WRITE
    } else {
        ENSURE_CAN_READ
    }

    if (!declaration) {
        return std::numeric_limits<int>::max();
    }

    if (declaration->topContext() == this && !declaration->inSymbolTable() &&
        !m_dynamicData->isTemporaryDeclarationIndex(declaration->ownIndex())) {
        uint index = declaration->ownIndex();
        Q_ASSERT(!(index & (1 << 31)));
        return ( int )(index | (1 << 31)); //We don't put context-local declarations into the list, that's a waste. We just use the mark them with the highest bit.
    }

    // if the declaration can not be found from this top-context, we create a direct
    // reference by index, to ensure that the use can be resolved in
    // usedDeclarationForIndex
    bool useDirectId = !recursiveImportIndices().contains(declaration->topContext());
    DeclarationId id(declaration->id(useDirectId));

    int index = -1;

    uint size = d_func()->m_usedDeclarationIdsSize();
    const DeclarationId* ids = d_func()->m_usedDeclarationIds();

    ///@todo Make m_usedDeclarationIds sorted, and find the decl. using binary search
    for (unsigned int a = 0; a < size; ++a)
        if (ids[a] == id) {
            index = a;
            break;
        }

    if (index != -1)
        return index;
    if (!create)
        return std::numeric_limits<int>::max();

    d_func_dynamic()->m_usedDeclarationIdsList().append(id);

    if (declaration->topContext() != this)
        DUChain::uses()->addUse(id, this);

    return d_func()->m_usedDeclarationIdsSize() - 1;
}

QVector<RangeInRevision> allUses(TopDUContext* context, Declaration* declaration, bool noEmptyRanges)
{
    QVector<RangeInRevision> ret;
    int declarationIndex = context->indexForUsedDeclaration(declaration, false);
    if (declarationIndex == std::numeric_limits<int>::max())
        return ret;
    return allUses(context, declarationIndex, noEmptyRanges);
}

QExplicitlySharedDataPointer<IAstContainer> TopDUContext::ast() const
{
    return m_local->m_ast;
}

void TopDUContext::clearAst()
{
    setAst(QExplicitlySharedDataPointer<IAstContainer>(nullptr));
}

IndexedString TopDUContext::url() const
{
    return d_func()->m_url;
}
}