-
Notifications
You must be signed in to change notification settings - Fork 12.2k
/
CIndex.cpp
9052 lines (7720 loc) · 304 KB
/
CIndex.cpp
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
//===- CIndex.cpp - Clang-C Source Indexing Library -----------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This file implements the main API hooks in the Clang-C Source Indexing
// library.
//
//===----------------------------------------------------------------------===//
#include "CIndexDiagnostic.h"
#include "CIndexer.h"
#include "CLog.h"
#include "CXCursor.h"
#include "CXSourceLocation.h"
#include "CXString.h"
#include "CXTranslationUnit.h"
#include "CXType.h"
#include "CursorVisitor.h"
#include "clang-c/FatalErrorHandler.h"
#include "clang/AST/Attr.h"
#include "clang/AST/Mangle.h"
#include "clang/AST/StmtVisitor.h"
#include "clang/Basic/Diagnostic.h"
#include "clang/Basic/DiagnosticCategories.h"
#include "clang/Basic/DiagnosticIDs.h"
#include "clang/Basic/Stack.h"
#include "clang/Basic/TargetInfo.h"
#include "clang/Basic/Version.h"
#include "clang/Frontend/ASTUnit.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Index/CommentToXML.h"
#include "clang/Lex/HeaderSearch.h"
#include "clang/Lex/Lexer.h"
#include "clang/Lex/PreprocessingRecord.h"
#include "clang/Lex/Preprocessor.h"
#include "llvm/ADT/Optional.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/StringSwitch.h"
#include "llvm/Config/llvm-config.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Support/CrashRecoveryContext.h"
#include "llvm/Support/Format.h"
#include "llvm/Support/ManagedStatic.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/Program.h"
#include "llvm/Support/SaveAndRestore.h"
#include "llvm/Support/Signals.h"
#include "llvm/Support/TargetSelect.h"
#include "llvm/Support/Threading.h"
#include "llvm/Support/Timer.h"
#include "llvm/Support/raw_ostream.h"
#include <mutex>
#if LLVM_ENABLE_THREADS != 0 && defined(__APPLE__)
#define USE_DARWIN_THREADS
#endif
#ifdef USE_DARWIN_THREADS
#include <pthread.h>
#endif
using namespace clang;
using namespace clang::cxcursor;
using namespace clang::cxtu;
using namespace clang::cxindex;
CXTranslationUnit cxtu::MakeCXTranslationUnit(CIndexer *CIdx,
std::unique_ptr<ASTUnit> AU) {
if (!AU)
return nullptr;
assert(CIdx);
CXTranslationUnit D = new CXTranslationUnitImpl();
D->CIdx = CIdx;
D->TheASTUnit = AU.release();
D->StringPool = new cxstring::CXStringPool();
D->Diagnostics = nullptr;
D->OverridenCursorsPool = createOverridenCXCursorsPool();
D->CommentToXML = nullptr;
D->ParsingOptions = 0;
D->Arguments = {};
return D;
}
bool cxtu::isASTReadError(ASTUnit *AU) {
for (ASTUnit::stored_diag_iterator D = AU->stored_diag_begin(),
DEnd = AU->stored_diag_end();
D != DEnd; ++D) {
if (D->getLevel() >= DiagnosticsEngine::Error &&
DiagnosticIDs::getCategoryNumberForDiag(D->getID()) ==
diag::DiagCat_AST_Deserialization_Issue)
return true;
}
return false;
}
cxtu::CXTUOwner::~CXTUOwner() {
if (TU)
clang_disposeTranslationUnit(TU);
}
/// Compare two source ranges to determine their relative position in
/// the translation unit.
static RangeComparisonResult RangeCompare(SourceManager &SM,
SourceRange R1,
SourceRange R2) {
assert(R1.isValid() && "First range is invalid?");
assert(R2.isValid() && "Second range is invalid?");
if (R1.getEnd() != R2.getBegin() &&
SM.isBeforeInTranslationUnit(R1.getEnd(), R2.getBegin()))
return RangeBefore;
if (R2.getEnd() != R1.getBegin() &&
SM.isBeforeInTranslationUnit(R2.getEnd(), R1.getBegin()))
return RangeAfter;
return RangeOverlap;
}
/// Determine if a source location falls within, before, or after a
/// a given source range.
static RangeComparisonResult LocationCompare(SourceManager &SM,
SourceLocation L, SourceRange R) {
assert(R.isValid() && "First range is invalid?");
assert(L.isValid() && "Second range is invalid?");
if (L == R.getBegin() || L == R.getEnd())
return RangeOverlap;
if (SM.isBeforeInTranslationUnit(L, R.getBegin()))
return RangeBefore;
if (SM.isBeforeInTranslationUnit(R.getEnd(), L))
return RangeAfter;
return RangeOverlap;
}
/// Translate a Clang source range into a CIndex source range.
///
/// Clang internally represents ranges where the end location points to the
/// start of the token at the end. However, for external clients it is more
/// useful to have a CXSourceRange be a proper half-open interval. This routine
/// does the appropriate translation.
CXSourceRange cxloc::translateSourceRange(const SourceManager &SM,
const LangOptions &LangOpts,
const CharSourceRange &R) {
// We want the last character in this location, so we will adjust the
// location accordingly.
SourceLocation EndLoc = R.getEnd();
bool IsTokenRange = R.isTokenRange();
if (EndLoc.isValid() && EndLoc.isMacroID() && !SM.isMacroArgExpansion(EndLoc)) {
CharSourceRange Expansion = SM.getExpansionRange(EndLoc);
EndLoc = Expansion.getEnd();
IsTokenRange = Expansion.isTokenRange();
}
if (IsTokenRange && EndLoc.isValid()) {
unsigned Length = Lexer::MeasureTokenLength(SM.getSpellingLoc(EndLoc),
SM, LangOpts);
EndLoc = EndLoc.getLocWithOffset(Length);
}
CXSourceRange Result = {
{ &SM, &LangOpts },
R.getBegin().getRawEncoding(),
EndLoc.getRawEncoding()
};
return Result;
}
//===----------------------------------------------------------------------===//
// Cursor visitor.
//===----------------------------------------------------------------------===//
static SourceRange getRawCursorExtent(CXCursor C);
static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr);
RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
return RangeCompare(AU->getSourceManager(), R, RegionOfInterest);
}
/// Visit the given cursor and, if requested by the visitor,
/// its children.
///
/// \param Cursor the cursor to visit.
///
/// \param CheckedRegionOfInterest if true, then the caller already checked
/// that this cursor is within the region of interest.
///
/// \returns true if the visitation should be aborted, false if it
/// should continue.
bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
if (clang_isInvalid(Cursor.kind))
return false;
if (clang_isDeclaration(Cursor.kind)) {
const Decl *D = getCursorDecl(Cursor);
if (!D) {
assert(0 && "Invalid declaration cursor");
return true; // abort.
}
// Ignore implicit declarations, unless it's an objc method because
// currently we should report implicit methods for properties when indexing.
if (D->isImplicit() && !isa<ObjCMethodDecl>(D))
return false;
}
// If we have a range of interest, and this cursor doesn't intersect with it,
// we're done.
if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
SourceRange Range = getRawCursorExtent(Cursor);
if (Range.isInvalid() || CompareRegionOfInterest(Range))
return false;
}
switch (Visitor(Cursor, Parent, ClientData)) {
case CXChildVisit_Break:
return true;
case CXChildVisit_Continue:
return false;
case CXChildVisit_Recurse: {
bool ret = VisitChildren(Cursor);
if (PostChildrenVisitor)
if (PostChildrenVisitor(Cursor, ClientData))
return true;
return ret;
}
}
llvm_unreachable("Invalid CXChildVisitResult!");
}
static bool visitPreprocessedEntitiesInRange(SourceRange R,
PreprocessingRecord &PPRec,
CursorVisitor &Visitor) {
SourceManager &SM = Visitor.getASTUnit()->getSourceManager();
FileID FID;
if (!Visitor.shouldVisitIncludedEntities()) {
// If the begin/end of the range lie in the same FileID, do the optimization
// where we skip preprocessed entities that do not come from the same FileID.
FID = SM.getFileID(SM.getFileLoc(R.getBegin()));
if (FID != SM.getFileID(SM.getFileLoc(R.getEnd())))
FID = FileID();
}
const auto &Entities = PPRec.getPreprocessedEntitiesInRange(R);
return Visitor.visitPreprocessedEntities(Entities.begin(), Entities.end(),
PPRec, FID);
}
bool CursorVisitor::visitFileRegion() {
if (RegionOfInterest.isInvalid())
return false;
ASTUnit *Unit = cxtu::getASTUnit(TU);
SourceManager &SM = Unit->getSourceManager();
std::pair<FileID, unsigned>
Begin = SM.getDecomposedLoc(SM.getFileLoc(RegionOfInterest.getBegin())),
End = SM.getDecomposedLoc(SM.getFileLoc(RegionOfInterest.getEnd()));
if (End.first != Begin.first) {
// If the end does not reside in the same file, try to recover by
// picking the end of the file of begin location.
End.first = Begin.first;
End.second = SM.getFileIDSize(Begin.first);
}
assert(Begin.first == End.first);
if (Begin.second > End.second)
return false;
FileID File = Begin.first;
unsigned Offset = Begin.second;
unsigned Length = End.second - Begin.second;
if (!VisitDeclsOnly && !VisitPreprocessorLast)
if (visitPreprocessedEntitiesInRegion())
return true; // visitation break.
if (visitDeclsFromFileRegion(File, Offset, Length))
return true; // visitation break.
if (!VisitDeclsOnly && VisitPreprocessorLast)
return visitPreprocessedEntitiesInRegion();
return false;
}
static bool isInLexicalContext(Decl *D, DeclContext *DC) {
if (!DC)
return false;
for (DeclContext *DeclDC = D->getLexicalDeclContext();
DeclDC; DeclDC = DeclDC->getLexicalParent()) {
if (DeclDC == DC)
return true;
}
return false;
}
bool CursorVisitor::visitDeclsFromFileRegion(FileID File,
unsigned Offset, unsigned Length) {
ASTUnit *Unit = cxtu::getASTUnit(TU);
SourceManager &SM = Unit->getSourceManager();
SourceRange Range = RegionOfInterest;
SmallVector<Decl *, 16> Decls;
Unit->findFileRegionDecls(File, Offset, Length, Decls);
// If we didn't find any file level decls for the file, try looking at the
// file that it was included from.
while (Decls.empty() || Decls.front()->isTopLevelDeclInObjCContainer()) {
bool Invalid = false;
const SrcMgr::SLocEntry &SLEntry = SM.getSLocEntry(File, &Invalid);
if (Invalid)
return false;
SourceLocation Outer;
if (SLEntry.isFile())
Outer = SLEntry.getFile().getIncludeLoc();
else
Outer = SLEntry.getExpansion().getExpansionLocStart();
if (Outer.isInvalid())
return false;
std::tie(File, Offset) = SM.getDecomposedExpansionLoc(Outer);
Length = 0;
Unit->findFileRegionDecls(File, Offset, Length, Decls);
}
assert(!Decls.empty());
bool VisitedAtLeastOnce = false;
DeclContext *CurDC = nullptr;
SmallVectorImpl<Decl *>::iterator DIt = Decls.begin();
for (SmallVectorImpl<Decl *>::iterator DE = Decls.end(); DIt != DE; ++DIt) {
Decl *D = *DIt;
if (D->getSourceRange().isInvalid())
continue;
if (isInLexicalContext(D, CurDC))
continue;
CurDC = dyn_cast<DeclContext>(D);
if (TagDecl *TD = dyn_cast<TagDecl>(D))
if (!TD->isFreeStanding())
continue;
RangeComparisonResult CompRes = RangeCompare(SM, D->getSourceRange(),Range);
if (CompRes == RangeBefore)
continue;
if (CompRes == RangeAfter)
break;
assert(CompRes == RangeOverlap);
VisitedAtLeastOnce = true;
if (isa<ObjCContainerDecl>(D)) {
FileDI_current = &DIt;
FileDE_current = DE;
} else {
FileDI_current = nullptr;
}
if (Visit(MakeCXCursor(D, TU, Range), /*CheckedRegionOfInterest=*/true))
return true; // visitation break.
}
if (VisitedAtLeastOnce)
return false;
// No Decls overlapped with the range. Move up the lexical context until there
// is a context that contains the range or we reach the translation unit
// level.
DeclContext *DC = DIt == Decls.begin() ? (*DIt)->getLexicalDeclContext()
: (*(DIt-1))->getLexicalDeclContext();
while (DC && !DC->isTranslationUnit()) {
Decl *D = cast<Decl>(DC);
SourceRange CurDeclRange = D->getSourceRange();
if (CurDeclRange.isInvalid())
break;
if (RangeCompare(SM, CurDeclRange, Range) == RangeOverlap) {
if (Visit(MakeCXCursor(D, TU, Range), /*CheckedRegionOfInterest=*/true))
return true; // visitation break.
}
DC = D->getLexicalDeclContext();
}
return false;
}
bool CursorVisitor::visitPreprocessedEntitiesInRegion() {
if (!AU->getPreprocessor().getPreprocessingRecord())
return false;
PreprocessingRecord &PPRec
= *AU->getPreprocessor().getPreprocessingRecord();
SourceManager &SM = AU->getSourceManager();
if (RegionOfInterest.isValid()) {
SourceRange MappedRange = AU->mapRangeToPreamble(RegionOfInterest);
SourceLocation B = MappedRange.getBegin();
SourceLocation E = MappedRange.getEnd();
if (AU->isInPreambleFileID(B)) {
if (SM.isLoadedSourceLocation(E))
return visitPreprocessedEntitiesInRange(SourceRange(B, E),
PPRec, *this);
// Beginning of range lies in the preamble but it also extends beyond
// it into the main file. Split the range into 2 parts, one covering
// the preamble and another covering the main file. This allows subsequent
// calls to visitPreprocessedEntitiesInRange to accept a source range that
// lies in the same FileID, allowing it to skip preprocessed entities that
// do not come from the same FileID.
bool breaked =
visitPreprocessedEntitiesInRange(
SourceRange(B, AU->getEndOfPreambleFileID()),
PPRec, *this);
if (breaked) return true;
return visitPreprocessedEntitiesInRange(
SourceRange(AU->getStartOfMainFileID(), E),
PPRec, *this);
}
return visitPreprocessedEntitiesInRange(SourceRange(B, E), PPRec, *this);
}
bool OnlyLocalDecls
= !AU->isMainFileAST() && AU->getOnlyLocalDecls();
if (OnlyLocalDecls)
return visitPreprocessedEntities(PPRec.local_begin(), PPRec.local_end(),
PPRec);
return visitPreprocessedEntities(PPRec.begin(), PPRec.end(), PPRec);
}
template<typename InputIterator>
bool CursorVisitor::visitPreprocessedEntities(InputIterator First,
InputIterator Last,
PreprocessingRecord &PPRec,
FileID FID) {
for (; First != Last; ++First) {
if (!FID.isInvalid() && !PPRec.isEntityInFileID(First, FID))
continue;
PreprocessedEntity *PPE = *First;
if (!PPE)
continue;
if (MacroExpansion *ME = dyn_cast<MacroExpansion>(PPE)) {
if (Visit(MakeMacroExpansionCursor(ME, TU)))
return true;
continue;
}
if (MacroDefinitionRecord *MD = dyn_cast<MacroDefinitionRecord>(PPE)) {
if (Visit(MakeMacroDefinitionCursor(MD, TU)))
return true;
continue;
}
if (InclusionDirective *ID = dyn_cast<InclusionDirective>(PPE)) {
if (Visit(MakeInclusionDirectiveCursor(ID, TU)))
return true;
continue;
}
}
return false;
}
/// Visit the children of the given cursor.
///
/// \returns true if the visitation should be aborted, false if it
/// should continue.
bool CursorVisitor::VisitChildren(CXCursor Cursor) {
if (clang_isReference(Cursor.kind) &&
Cursor.kind != CXCursor_CXXBaseSpecifier) {
// By definition, references have no children.
return false;
}
// Set the Parent field to Cursor, then back to its old value once we're
// done.
SetParentRAII SetParent(Parent, StmtParent, Cursor);
if (clang_isDeclaration(Cursor.kind)) {
Decl *D = const_cast<Decl *>(getCursorDecl(Cursor));
if (!D)
return false;
return VisitAttributes(D) || Visit(D);
}
if (clang_isStatement(Cursor.kind)) {
if (const Stmt *S = getCursorStmt(Cursor))
return Visit(S);
return false;
}
if (clang_isExpression(Cursor.kind)) {
if (const Expr *E = getCursorExpr(Cursor))
return Visit(E);
return false;
}
if (clang_isTranslationUnit(Cursor.kind)) {
CXTranslationUnit TU = getCursorTU(Cursor);
ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
int VisitOrder[2] = { VisitPreprocessorLast, !VisitPreprocessorLast };
for (unsigned I = 0; I != 2; ++I) {
if (VisitOrder[I]) {
if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
RegionOfInterest.isInvalid()) {
for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(),
TLEnd = CXXUnit->top_level_end();
TL != TLEnd; ++TL) {
const Optional<bool> V = handleDeclForVisitation(*TL);
if (!V.hasValue())
continue;
return V.getValue();
}
} else if (VisitDeclContext(
CXXUnit->getASTContext().getTranslationUnitDecl()))
return true;
continue;
}
// Walk the preprocessing record.
if (CXXUnit->getPreprocessor().getPreprocessingRecord())
visitPreprocessedEntitiesInRegion();
}
return false;
}
if (Cursor.kind == CXCursor_CXXBaseSpecifier) {
if (const CXXBaseSpecifier *Base = getCursorCXXBaseSpecifier(Cursor)) {
if (TypeSourceInfo *BaseTSInfo = Base->getTypeSourceInfo()) {
return Visit(BaseTSInfo->getTypeLoc());
}
}
}
if (Cursor.kind == CXCursor_IBOutletCollectionAttr) {
const IBOutletCollectionAttr *A =
cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(Cursor));
if (const ObjCObjectType *ObjT = A->getInterface()->getAs<ObjCObjectType>())
return Visit(cxcursor::MakeCursorObjCClassRef(
ObjT->getInterface(),
A->getInterfaceLoc()->getTypeLoc().getBeginLoc(), TU));
}
// If pointing inside a macro definition, check if the token is an identifier
// that was ever defined as a macro. In such a case, create a "pseudo" macro
// expansion cursor for that token.
SourceLocation BeginLoc = RegionOfInterest.getBegin();
if (Cursor.kind == CXCursor_MacroDefinition &&
BeginLoc == RegionOfInterest.getEnd()) {
SourceLocation Loc = AU->mapLocationToPreamble(BeginLoc);
const MacroInfo *MI =
getMacroInfo(cxcursor::getCursorMacroDefinition(Cursor), TU);
if (MacroDefinitionRecord *MacroDef =
checkForMacroInMacroDefinition(MI, Loc, TU))
return Visit(cxcursor::MakeMacroExpansionCursor(MacroDef, BeginLoc, TU));
}
// Nothing to visit at the moment.
return false;
}
bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
if (TypeSourceInfo *TSInfo = B->getSignatureAsWritten())
if (Visit(TSInfo->getTypeLoc()))
return true;
if (Stmt *Body = B->getBody())
return Visit(MakeCXCursor(Body, StmtParent, TU, RegionOfInterest));
return false;
}
Optional<bool> CursorVisitor::shouldVisitCursor(CXCursor Cursor) {
if (RegionOfInterest.isValid()) {
SourceRange Range = getFullCursorExtent(Cursor, AU->getSourceManager());
if (Range.isInvalid())
return None;
switch (CompareRegionOfInterest(Range)) {
case RangeBefore:
// This declaration comes before the region of interest; skip it.
return None;
case RangeAfter:
// This declaration comes after the region of interest; we're done.
return false;
case RangeOverlap:
// This declaration overlaps the region of interest; visit it.
break;
}
}
return true;
}
bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
DeclContext::decl_iterator I = DC->decls_begin(), E = DC->decls_end();
// FIXME: Eventually remove. This part of a hack to support proper
// iteration over all Decls contained lexically within an ObjC container.
SaveAndRestore<DeclContext::decl_iterator*> DI_saved(DI_current, &I);
SaveAndRestore<DeclContext::decl_iterator> DE_saved(DE_current, E);
for ( ; I != E; ++I) {
Decl *D = *I;
if (D->getLexicalDeclContext() != DC)
continue;
// Filter out synthesized property accessor redeclarations.
if (isa<ObjCImplDecl>(DC))
if (auto *OMD = dyn_cast<ObjCMethodDecl>(D))
if (OMD->isSynthesizedAccessorStub())
continue;
const Optional<bool> V = handleDeclForVisitation(D);
if (!V.hasValue())
continue;
return V.getValue();
}
return false;
}
Optional<bool> CursorVisitor::handleDeclForVisitation(const Decl *D) {
CXCursor Cursor = MakeCXCursor(D, TU, RegionOfInterest);
// Ignore synthesized ivars here, otherwise if we have something like:
// @synthesize prop = _prop;
// and '_prop' is not declared, we will encounter a '_prop' ivar before
// encountering the 'prop' synthesize declaration and we will think that
// we passed the region-of-interest.
if (auto *ivarD = dyn_cast<ObjCIvarDecl>(D)) {
if (ivarD->getSynthesize())
return None;
}
// FIXME: ObjCClassRef/ObjCProtocolRef for forward class/protocol
// declarations is a mismatch with the compiler semantics.
if (Cursor.kind == CXCursor_ObjCInterfaceDecl) {
auto *ID = cast<ObjCInterfaceDecl>(D);
if (!ID->isThisDeclarationADefinition())
Cursor = MakeCursorObjCClassRef(ID, ID->getLocation(), TU);
} else if (Cursor.kind == CXCursor_ObjCProtocolDecl) {
auto *PD = cast<ObjCProtocolDecl>(D);
if (!PD->isThisDeclarationADefinition())
Cursor = MakeCursorObjCProtocolRef(PD, PD->getLocation(), TU);
}
const Optional<bool> V = shouldVisitCursor(Cursor);
if (!V.hasValue())
return None;
if (!V.getValue())
return false;
if (Visit(Cursor, true))
return true;
return None;
}
bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
llvm_unreachable("Translation units are visited directly by Visit()");
}
bool CursorVisitor::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) {
if (VisitTemplateParameters(D->getTemplateParameters()))
return true;
return Visit(MakeCXCursor(D->getTemplatedDecl(), TU, RegionOfInterest));
}
bool CursorVisitor::VisitTypeAliasDecl(TypeAliasDecl *D) {
if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
return Visit(TSInfo->getTypeLoc());
return false;
}
bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
return Visit(TSInfo->getTypeLoc());
return false;
}
bool CursorVisitor::VisitTagDecl(TagDecl *D) {
return VisitDeclContext(D);
}
bool CursorVisitor::VisitClassTemplateSpecializationDecl(
ClassTemplateSpecializationDecl *D) {
bool ShouldVisitBody = false;
switch (D->getSpecializationKind()) {
case TSK_Undeclared:
case TSK_ImplicitInstantiation:
// Nothing to visit
return false;
case TSK_ExplicitInstantiationDeclaration:
case TSK_ExplicitInstantiationDefinition:
break;
case TSK_ExplicitSpecialization:
ShouldVisitBody = true;
break;
}
// Visit the template arguments used in the specialization.
if (TypeSourceInfo *SpecType = D->getTypeAsWritten()) {
TypeLoc TL = SpecType->getTypeLoc();
if (TemplateSpecializationTypeLoc TSTLoc =
TL.getAs<TemplateSpecializationTypeLoc>()) {
for (unsigned I = 0, N = TSTLoc.getNumArgs(); I != N; ++I)
if (VisitTemplateArgumentLoc(TSTLoc.getArgLoc(I)))
return true;
}
}
return ShouldVisitBody && VisitCXXRecordDecl(D);
}
bool CursorVisitor::VisitClassTemplatePartialSpecializationDecl(
ClassTemplatePartialSpecializationDecl *D) {
// FIXME: Visit the "outer" template parameter lists on the TagDecl
// before visiting these template parameters.
if (VisitTemplateParameters(D->getTemplateParameters()))
return true;
// Visit the partial specialization arguments.
const ASTTemplateArgumentListInfo *Info = D->getTemplateArgsAsWritten();
const TemplateArgumentLoc *TemplateArgs = Info->getTemplateArgs();
for (unsigned I = 0, N = Info->NumTemplateArgs; I != N; ++I)
if (VisitTemplateArgumentLoc(TemplateArgs[I]))
return true;
return VisitCXXRecordDecl(D);
}
bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
if (const auto *TC = D->getTypeConstraint())
if (Visit(MakeCXCursor(TC->getImmediatelyDeclaredConstraint(), StmtParent,
TU, RegionOfInterest)))
return true;
// Visit the default argument.
if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
if (TypeSourceInfo *DefArg = D->getDefaultArgumentInfo())
if (Visit(DefArg->getTypeLoc()))
return true;
return false;
}
bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
if (Expr *Init = D->getInitExpr())
return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
return false;
}
bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
unsigned NumParamList = DD->getNumTemplateParameterLists();
for (unsigned i = 0; i < NumParamList; i++) {
TemplateParameterList* Params = DD->getTemplateParameterList(i);
if (VisitTemplateParameters(Params))
return true;
}
if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
if (Visit(TSInfo->getTypeLoc()))
return true;
// Visit the nested-name-specifier, if present.
if (NestedNameSpecifierLoc QualifierLoc = DD->getQualifierLoc())
if (VisitNestedNameSpecifierLoc(QualifierLoc))
return true;
return false;
}
static bool HasTrailingReturnType(FunctionDecl *ND) {
const QualType Ty = ND->getType();
if (const FunctionType *AFT = Ty->getAs<FunctionType>()) {
if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(AFT))
return FT->hasTrailingReturn();
}
return false;
}
/// Compare two base or member initializers based on their source order.
static int CompareCXXCtorInitializers(CXXCtorInitializer *const *X,
CXXCtorInitializer *const *Y) {
return (*X)->getSourceOrder() - (*Y)->getSourceOrder();
}
bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
unsigned NumParamList = ND->getNumTemplateParameterLists();
for (unsigned i = 0; i < NumParamList; i++) {
TemplateParameterList* Params = ND->getTemplateParameterList(i);
if (VisitTemplateParameters(Params))
return true;
}
if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) {
// Visit the function declaration's syntactic components in the order
// written. This requires a bit of work.
TypeLoc TL = TSInfo->getTypeLoc().IgnoreParens();
FunctionTypeLoc FTL = TL.getAs<FunctionTypeLoc>();
const bool HasTrailingRT = HasTrailingReturnType(ND);
// If we have a function declared directly (without the use of a typedef),
// visit just the return type. Otherwise, just visit the function's type
// now.
if ((FTL && !isa<CXXConversionDecl>(ND) && !HasTrailingRT &&
Visit(FTL.getReturnLoc())) ||
(!FTL && Visit(TL)))
return true;
// Visit the nested-name-specifier, if present.
if (NestedNameSpecifierLoc QualifierLoc = ND->getQualifierLoc())
if (VisitNestedNameSpecifierLoc(QualifierLoc))
return true;
// Visit the declaration name.
if (!isa<CXXDestructorDecl>(ND))
if (VisitDeclarationNameInfo(ND->getNameInfo()))
return true;
// FIXME: Visit explicitly-specified template arguments!
// Visit the function parameters, if we have a function type.
if (FTL && VisitFunctionTypeLoc(FTL, true))
return true;
// Visit the function's trailing return type.
if (FTL && HasTrailingRT && Visit(FTL.getReturnLoc()))
return true;
// FIXME: Attributes?
}
if (ND->doesThisDeclarationHaveABody() && !ND->isLateTemplateParsed()) {
if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ND)) {
// Find the initializers that were written in the source.
SmallVector<CXXCtorInitializer *, 4> WrittenInits;
for (auto *I : Constructor->inits()) {
if (!I->isWritten())
continue;
WrittenInits.push_back(I);
}
// Sort the initializers in source order
llvm::array_pod_sort(WrittenInits.begin(), WrittenInits.end(),
&CompareCXXCtorInitializers);
// Visit the initializers in source order
for (unsigned I = 0, N = WrittenInits.size(); I != N; ++I) {
CXXCtorInitializer *Init = WrittenInits[I];
if (Init->isAnyMemberInitializer()) {
if (Visit(MakeCursorMemberRef(Init->getAnyMember(),
Init->getMemberLocation(), TU)))
return true;
} else if (TypeSourceInfo *TInfo = Init->getTypeSourceInfo()) {
if (Visit(TInfo->getTypeLoc()))
return true;
}
// Visit the initializer value.
if (Expr *Initializer = Init->getInit())
if (Visit(MakeCXCursor(Initializer, ND, TU, RegionOfInterest)))
return true;
}
}
if (Visit(MakeCXCursor(ND->getBody(), StmtParent, TU, RegionOfInterest)))
return true;
}
return false;
}
bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
if (VisitDeclaratorDecl(D))
return true;
if (Expr *BitWidth = D->getBitWidth())
return Visit(MakeCXCursor(BitWidth, StmtParent, TU, RegionOfInterest));
if (Expr *Init = D->getInClassInitializer())
return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
return false;
}
bool CursorVisitor::VisitVarDecl(VarDecl *D) {
if (VisitDeclaratorDecl(D))
return true;
if (Expr *Init = D->getInit())
return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
return false;
}
bool CursorVisitor::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
if (VisitDeclaratorDecl(D))
return true;
if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
if (Expr *DefArg = D->getDefaultArgument())
return Visit(MakeCXCursor(DefArg, StmtParent, TU, RegionOfInterest));
return false;
}
bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
// FIXME: Visit the "outer" template parameter lists on the FunctionDecl
// before visiting these template parameters.
if (VisitTemplateParameters(D->getTemplateParameters()))
return true;
auto* FD = D->getTemplatedDecl();
return VisitAttributes(FD) || VisitFunctionDecl(FD);
}
bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) {
// FIXME: Visit the "outer" template parameter lists on the TagDecl
// before visiting these template parameters.
if (VisitTemplateParameters(D->getTemplateParameters()))
return true;
auto* CD = D->getTemplatedDecl();
return VisitAttributes(CD) || VisitCXXRecordDecl(CD);
}
bool CursorVisitor::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
if (VisitTemplateParameters(D->getTemplateParameters()))
return true;
if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited() &&
VisitTemplateArgumentLoc(D->getDefaultArgument()))
return true;
return false;
}
bool CursorVisitor::VisitObjCTypeParamDecl(ObjCTypeParamDecl *D) {
// Visit the bound, if it's explicit.
if (D->hasExplicitBound()) {
if (auto TInfo = D->getTypeSourceInfo()) {
if (Visit(TInfo->getTypeLoc()))
return true;
}
}
return false;
}
bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
if (TypeSourceInfo *TSInfo = ND->getReturnTypeSourceInfo())
if (Visit(TSInfo->getTypeLoc()))
return true;
for (const auto *P : ND->parameters()) {
if (Visit(MakeCXCursor(P, TU, RegionOfInterest)))
return true;
}
return ND->isThisDeclarationADefinition() &&
Visit(MakeCXCursor(ND->getBody(), StmtParent, TU, RegionOfInterest));
}
template <typename DeclIt>
static void addRangedDeclsInContainer(DeclIt *DI_current, DeclIt DE_current,
SourceManager &SM, SourceLocation EndLoc,
SmallVectorImpl<Decl *> &Decls) {
DeclIt next = *DI_current;
while (++next != DE_current) {
Decl *D_next = *next;