-
Notifications
You must be signed in to change notification settings - Fork 243
/
IndexerASTHooks.cc
6009 lines (5631 loc) · 235 KB
/
IndexerASTHooks.cc
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
/*
* Copyright 2014 The Kythe Authors. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "IndexerASTHooks.h"
#include <algorithm>
#include <tuple>
#include "GraphObserver.h"
#include "absl/flags/flag.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/str_join.h"
#include "absl/strings/string_view.h"
#include "absl/types/optional.h"
#include "clang/AST/Attr.h"
#include "clang/AST/AttrVisitor.h"
#include "clang/AST/CommentLexer.h"
#include "clang/AST/Decl.h"
#include "clang/AST/DeclCXX.h"
#include "clang/AST/DeclObjC.h"
#include "clang/AST/DeclTemplate.h"
#include "clang/AST/DeclVisitor.h"
#include "clang/AST/Expr.h"
#include "clang/AST/ExprCXX.h"
#include "clang/AST/ExprObjC.h"
#include "clang/AST/NestedNameSpecifier.h"
#include "clang/AST/Stmt.h"
#include "clang/AST/TemplateBase.h"
#include "clang/AST/TemplateName.h"
#include "clang/AST/Type.h"
#include "clang/AST/TypeLoc.h"
#include "clang/Basic/Builtins.h"
#include "clang/Index/USRGeneration.h"
#include "clang/Lex/Lexer.h"
#include "clang/Sema/Lookup.h"
#include "indexed_parent_iterator.h"
#include "kythe/cxx/common/scope_guard.h"
#include "kythe/cxx/indexer/cxx/clang_range_finder.h"
#include "kythe/cxx/indexer/cxx/clang_utils.h"
#include "kythe/cxx/indexer/cxx/marked_source.h"
#include "kythe/cxx/indexer/cxx/node_set.h"
#include "kythe/cxx/indexer/cxx/stream_adapter.h"
#include "llvm/Support/raw_ostream.h"
ABSL_FLAG(bool, experimental_alias_template_instantiations, false,
"Ignore template instantation information when generating IDs.");
ABSL_FLAG(bool, experimental_threaded_claiming, false,
"Defer answering claims and submit them in bulk when possible.");
ABSL_FLAG(bool, emit_anchors_on_builtins, true,
"Emit anchors on builtin types like int and float.");
namespace kythe {
using ::clang::dyn_cast;
using ::clang::dyn_cast_or_null;
using ::clang::FileID;
using ::clang::isa;
using ::clang::SourceLocation;
using ::clang::SourceRange;
using Claimability = GraphObserver::Claimability;
using NodeId = GraphObserver::NodeId;
void* NullGraphObserver::NullClaimToken::NullClaimTokenClass = nullptr;
namespace {
/// Decides whether `Tok` can be used to quote an identifier.
bool TokenQuotesIdentifier(const clang::SourceManager& SM,
const clang::Token& Tok) {
switch (Tok.getKind()) {
case clang::tok::TokenKind::pipe:
return true;
case clang::tok::TokenKind::unknown: {
bool Invalid = false;
if (const char* TokChar =
SM.getCharacterData(Tok.getLocation(), &Invalid)) {
if (!Invalid && Tok.getLength() > 0) {
return *TokChar == '`';
}
}
return false;
}
default:
return false;
}
}
absl::optional<llvm::StringRef> GetDeclarationName(
const clang::DeclarationName& Name, bool IgnoreUnimplemented) {
switch (Name.getNameKind()) {
case clang::DeclarationName::Identifier:
return Name.getAsIdentifierInfo()->getName();
case clang::DeclarationName::CXXConstructorName:
return "#ctor";
case clang::DeclarationName::CXXDestructorName:
return "#dtor";
// TODO(zarko): Fill in the remaining relevant DeclarationName cases.
#define UNEXPECTED_DECLARATION_NAME_KIND(kind) \
case clang::DeclarationName::kind: \
CHECK(IgnoreUnimplemented) << "Unexpected DeclaraionName::" #kind; \
return absl::nullopt;
UNEXPECTED_DECLARATION_NAME_KIND(ObjCZeroArgSelector);
UNEXPECTED_DECLARATION_NAME_KIND(ObjCOneArgSelector);
UNEXPECTED_DECLARATION_NAME_KIND(ObjCMultiArgSelector);
UNEXPECTED_DECLARATION_NAME_KIND(CXXConversionFunctionName);
UNEXPECTED_DECLARATION_NAME_KIND(CXXOperatorName);
UNEXPECTED_DECLARATION_NAME_KIND(CXXLiteralOperatorName);
UNEXPECTED_DECLARATION_NAME_KIND(CXXUsingDirective);
UNEXPECTED_DECLARATION_NAME_KIND(CXXDeductionGuideName);
#undef UNEXPECTED_DECLARATION_NAME_KIND
}
return absl::nullopt;
}
/// \brief Finds the first CXXConstructExpr child of the given
/// CXXFunctionalCastExpr.
const clang::CXXConstructExpr* FindConstructExpr(
const clang::CXXFunctionalCastExpr* E) {
for (const auto* Child : E->children()) {
if (isa<clang::CXXConstructExpr>(Child)) {
return dyn_cast<clang::CXXConstructExpr>(Child);
}
}
return nullptr;
}
template <typename F>
void MapOverrideRoots(const clang::CXXMethodDecl* M, const F& Fn) {
if (M->size_overridden_methods() == 0) {
Fn(M);
} else {
for (const auto& PM : M->overridden_methods()) {
MapOverrideRoots(PM, Fn);
}
}
}
template <typename F>
void MapOverrideRoots(const clang::ObjCMethodDecl* M, const F& Fn) {
if (!M->isOverriding()) {
Fn(M);
} else {
llvm::SmallVector<const clang::ObjCMethodDecl*, 4> overrides;
M->getOverriddenMethods(overrides);
for (const auto& PM : overrides) {
MapOverrideRoots(PM, Fn);
}
}
}
clang::QualType FollowAliasChain(const clang::TypedefNameDecl* TND) {
clang::Qualifiers Qs;
clang::QualType QT;
for (;;) {
// We'll assume that the alias chain stops as soon as we hit a non-alias.
// This does not attempt to dereference aliases in template parameters
// (or even aliases underneath pointers, etc).
QT = TND->getUnderlyingType();
Qs.addQualifiers(QT.getQualifiers());
if (auto* TTD = dyn_cast<clang::TypedefType>(QT.getTypePtr())) {
TND = TTD->getDecl();
} else if (auto* ET = dyn_cast<clang::ElaboratedType>(QT.getTypePtr())) {
if (auto* TDT =
dyn_cast<clang::TypedefType>(ET->getNamedType().getTypePtr())) {
TND = TDT->getDecl();
Qs.addQualifiers(ET->getNamedType().getQualifiers());
} else {
return clang::QualType(QT.getTypePtr(), Qs.getFastQualifiers());
}
} else {
// We lose fidelity with getFastQualifiers.
return clang::QualType(QT.getTypePtr(), Qs.getFastQualifiers());
}
}
}
/// \brief Attempt to find the template parameters bound immediately by `DC`.
/// \return null if no parameters could be found.
clang::TemplateParameterList* GetTypeParameters(const clang::DeclContext* DC) {
if (!DC) {
return nullptr;
}
if (const auto* TemplateContext = dyn_cast<clang::TemplateDecl>(DC)) {
return TemplateContext->getTemplateParameters();
} else if (const auto* CTPSD =
dyn_cast<clang::ClassTemplatePartialSpecializationDecl>(DC)) {
return CTPSD->getTemplateParameters();
} else if (const auto* RD = dyn_cast<clang::CXXRecordDecl>(DC)) {
if (const auto* TD = RD->getDescribedClassTemplate()) {
return TD->getTemplateParameters();
}
} else if (const auto* VTPSD =
dyn_cast<clang::VarTemplatePartialSpecializationDecl>(DC)) {
return VTPSD->getTemplateParameters();
} else if (const auto* VD = dyn_cast<clang::VarDecl>(DC)) {
if (const auto* TD = VD->getDescribedVarTemplate()) {
return TD->getTemplateParameters();
}
} else if (const auto* AD = dyn_cast<clang::TypeAliasDecl>(DC)) {
if (const auto* TD = AD->getDescribedAliasTemplate()) {
return TD->getTemplateParameters();
}
}
return nullptr;
}
/// Make sure `DC` won't cause Sema::LookupQualifiedName to fail an assertion.
bool IsContextSafeForLookup(const clang::DeclContext* DC) {
if (const auto* TD = dyn_cast<clang::TagDecl>(DC)) {
return TD->isCompleteDefinition() || TD->isBeingDefined();
}
return DC->isDependentContext() || !isa<clang::LinkageSpecDecl>(DC);
}
/// \brief Returns whether `Ctor` would override the in-class initializer for
/// `Field`.
bool ConstructorOverridesInitializer(const clang::CXXConstructorDecl* Ctor,
const clang::FieldDecl* Field) {
const clang::FunctionDecl* CtorDefn = nullptr;
if (Ctor->isDefined(CtorDefn) &&
(Ctor = dyn_cast_or_null<clang::CXXConstructorDecl>(CtorDefn))) {
for (const auto* Init : Ctor->inits()) {
if (Init->getMember() == Field && !Init->isInClassMemberInitializer()) {
return true;
}
}
}
return false;
}
/// \return true if `D` should not be visited because its name will never be
/// uttered due to aliasing rules.
bool SkipAliasedDecl(const clang::Decl* D) {
return absl::GetFlag(FLAGS_experimental_alias_template_instantiations) &&
(FindSpecializedTemplate(D) != D);
}
bool IsObjCForwardDecl(const clang::ObjCInterfaceDecl* decl) {
return !decl->isThisDeclarationADefinition();
}
const clang::Decl* FindImplicitDeclForStmt(
const IndexedParentMap* AllParents, const clang::Stmt* Stmt,
llvm::SmallVector<unsigned, 16>* StmtPath) {
for (const auto& Current : RootTraversal(AllParents, Stmt)) {
if (Current.decl && Current.decl->isImplicit() &&
!isa<clang::VarDecl>(Current.decl) &&
!(isa<clang::CXXRecordDecl>(Current.decl) &&
dyn_cast<clang::CXXRecordDecl>(Current.decl)->isLambda())) {
// If this is an implicit variable declaration, we assume that it is one
// of the implicit declarations attached to a range for loop. We ignore
// its implicitness, which lets us associate a source location with the
// implicit references to 'begin', 'end' and operators. We also skip
// the implicit CXXRecordDecl that's created for lambda expressions,
// since it may include interesting non-implicit nodes.
return Current.decl;
}
if (Current.indexed_parent && StmtPath) {
StmtPath->push_back(Current.indexed_parent->index);
}
}
return nullptr;
}
bool IsCompleteAggregateType(clang::QualType Type) {
if (Type.isNull()) {
return false;
}
Type = Type.getCanonicalType();
return !Type->isIncompleteType() && Type->isAggregateType();
}
llvm::SmallVector<const clang::Decl*, 5> GetInitExprDecls(
const clang::InitListExpr* ILE) {
CHECK(ILE->isSemanticForm());
clang::QualType Type = ILE->getType();
// Ignore non-aggregate and copy initialization.
if (!IsCompleteAggregateType(Type) || ILE->isTransparent()) {
return {};
}
if (const clang::FieldDecl* Field = ILE->getInitializedFieldInUnion()) {
return {Field};
}
llvm::SmallVector<const clang::Decl*, 5> result;
if (const auto* Decl = Type->getAsCXXRecordDecl();
Decl && (Decl = Decl->getDefinition())) {
for (const auto& Base : Decl->bases()) {
result.push_back(CHECK_NOTNULL(Base.getType()->getAsTagDecl()));
}
}
if (const auto* Decl = Type->getAsRecordDecl();
Decl && (Decl = Decl->getDefinition())) {
for (const auto* Field : Decl->fields()) {
if (!Field->isUnnamedBitfield()) {
result.push_back(Field);
}
}
}
return result;
}
clang::InitListExpr* GetSemanticForm(clang::InitListExpr* ILE) {
return (ILE->isSemanticForm() ? ILE : ILE->getSemanticForm());
}
clang::InitListExpr* GetSyntacticForm(clang::InitListExpr* ILE) {
return (ILE->isSyntacticForm() ? ILE : ILE->getSyntacticForm());
}
const clang::InitListExpr* GetSyntacticForm(const clang::InitListExpr* ILE) {
return (ILE->isSyntacticForm() ? ILE : ILE->getSyntacticForm());
}
class KytheAttributeVisitor
: public clang::ConstAttrVisitor<KytheAttributeVisitor> {
public:
explicit KytheAttributeVisitor(
GraphObserver& Observer ABSL_ATTRIBUTE_LIFETIME_BOUND,
const GraphObserver::NodeId& TargetNode ABSL_ATTRIBUTE_LIFETIME_BOUND)
: Observer(Observer), TargetNode(TargetNode) {}
KytheAttributeVisitor(const KytheAttributeVisitor&) = delete;
KytheAttributeVisitor& operator=(const KytheAttributeVisitor&) = delete;
void VisitDeprecatedAttr(const clang::DeprecatedAttr* Attr) {
Observer.recordDeprecated(TargetNode, Attr->getMessage());
}
void VisitAvailabilityAttr(const clang::AvailabilityAttr* Attr) {
if (auto Version = Attr->getDeprecated(); !Version.empty()) {
Observer.recordDeprecated(TargetNode, Version.getAsString());
}
}
private:
GraphObserver& Observer;
const GraphObserver::NodeId& TargetNode;
};
class NameEqClassDeclVisitor
: public clang::ConstDeclVisitor<NameEqClassDeclVisitor,
GraphObserver::NameId::NameEqClass> {
using NameEqClass = GraphObserver::NameId::NameEqClass;
public:
NameEqClassDeclVisitor() = default;
NameEqClass Visit(const clang::Decl* decl) {
CHECK(decl != nullptr);
return ConstDeclVisitor::Visit(decl);
}
NameEqClass VisitTagDecl(const clang::TagDecl* decl) {
switch (decl->getTagKind()) {
case clang::TTK_Struct:
return NameEqClass::Class;
case clang::TTK_Class:
return NameEqClass::Class;
case clang::TTK_Union:
return NameEqClass::Union;
default:
// TODO(zarko): Add classes for other tag kinds, like enums.
return NameEqClass::None;
}
}
NameEqClass VisitClassTemplateDecl(const clang::ClassTemplateDecl* decl) {
// Eqclasses should see through templates.
return Visit(decl->getTemplatedDecl());
}
NameEqClass VisitObjCContainerDecl(const clang::ObjCContainerDecl* decl) {
// In the future we might want to do something different for each of the
// important subclasses: clang::ObjCInterfaceDecl,
// clang::ObjCImplementationDecl, clang::ObjCProtocolDecl,
// clang::ObjCCategoryDecl, and clang::ObjCCategoryImplDecl.
return NameEqClass::Class;
}
NameEqClass VisitDecl(const clang::Decl* decl) { return NameEqClass::None; }
};
/// \brief Categorizes the name of `Decl` according to the equivalence classes
/// defined by `GraphObserver::NameId::NameEqClass`.
GraphObserver::NameId::NameEqClass BuildNameEqClassForDecl(
const clang::Decl* decl) {
return NameEqClassDeclVisitor().Visit(decl);
}
bool IsBindingExpr(const clang::ASTContext& Context, const clang::Expr* Expr) {
clang::Expr::EvalResult Unused;
if (!Expr->isValueDependent() && Expr->EvaluateAsRValue(Unused, Context)) {
return false;
}
return true;
}
std::string ExpressionString(const clang::Expr* Expr,
const clang::PrintingPolicy& Policy) {
std::string Text;
llvm::raw_string_ostream Out(Text);
Expr->printPretty(Out, nullptr, Policy);
return Text;
}
} // anonymous namespace
bool IsClaimableForTraverse(const clang::Decl* decl) {
// Operationally, we'll define this as any decl that causes
// Job->UnderneathImplicitTemplateInstantiation to be set.
if (auto* VTSD = dyn_cast<const clang::VarTemplateSpecializationDecl>(decl)) {
return !VTSD->isExplicitInstantiationOrSpecialization();
}
if (auto* CTSD =
dyn_cast<const clang::ClassTemplateSpecializationDecl>(decl)) {
return !CTSD->isExplicitInstantiationOrSpecialization();
}
if (auto* FD = dyn_cast<const clang::FunctionDecl>(decl)) {
if (const auto* MSI = FD->getMemberSpecializationInfo()) {
// The definitions of class template member functions are not necessarily
// dominated by the class template definition.
if (!MSI->isExplicitSpecialization()) {
return true;
}
} else if (const auto* FSI = FD->getTemplateSpecializationInfo()) {
if (!FSI->isExplicitInstantiationOrSpecialization()) {
return true;
}
}
}
return false;
}
enum class Prunability {
kNone,
kImmediate,
kDeferIncompleteFunctions,
kDeferred
};
/// \brief RAII class used to pair claimImplicitNode/finishImplicitNode
/// when pruning AST traversal.
class PruneCheck {
public:
PruneCheck(IndexerASTVisitor* visitor, const clang::Decl* decl)
: visitor_(visitor) {
if (!visitor_->Job->UnderneathImplicitTemplateInstantiation &&
visitor_->declDominatesPrunableSubtree(decl)) {
// This node in the AST dominates a subtree that can be pruned.
if (!visitor_->Observer.claimLocation(decl->getLocation())) {
can_prune_ = Prunability::kImmediate;
}
return;
}
if (llvm::isa<clang::FunctionDecl>(decl)) {
// We make the assumption that we can stop traversal at function
// declarations, which means that we always expect the subtree rooted
// at a particular FunctionDecl under a particular type context will
// look the same. If this isn't a function declaration, the tree we
// see depends on external use sites. This assumption is reasonable
// for code that doesn't rely on making different sets of decls
// visible for ADL in different places (for example). (The core
// difference between a function body and, say, a class body is that
// function bodies are "closed*" and can't span files**, nor can they
// leak local template declarations in a way that would allow
// clients outside the function body to instantiate those declarations
// at different types.)
//
// * modulo ADL, dependent lookup, different overloads/specializations
// in context; code that makes these a problem is arguably not
// reasonable code
// ** modulo wacky macros
//
GenerateCleanupId(decl);
if (absl::GetFlag(FLAGS_experimental_threaded_claiming) ||
!visitor_->Observer.claimImplicitNode(cleanup_id_)) {
can_prune_ = Prunability::kDeferred;
}
} else if (llvm::isa<clang::ClassTemplateSpecializationDecl>(decl)) {
GenerateCleanupId(decl);
if (absl::GetFlag(FLAGS_experimental_threaded_claiming) ||
!visitor_->Observer.claimImplicitNode(cleanup_id_)) {
can_prune_ = Prunability::kDeferIncompleteFunctions;
}
}
}
~PruneCheck() {
if (!absl::GetFlag(FLAGS_experimental_threaded_claiming) &&
!cleanup_id_.empty()) {
visitor_->Observer.finishImplicitNode(cleanup_id_);
}
}
/// \return true if the decl supplied during construction doesn't need
/// traversed.
Prunability can_prune() const { return can_prune_; }
const std::string& cleanup_id() { return cleanup_id_; }
private:
void GenerateCleanupId(const clang::Decl* decl) {
// TODO(zarko): Check to see if non-function members of a class
// can be traversed once per argument set.
cleanup_id_ =
absl::StrCat(visitor_->BuildNodeIdForDecl(decl).getRawIdentity(), "#",
visitor_->getGraphObserver().getBuildConfig());
// It's critical that we distinguish between different argument lists
// here even if aliasing is turned on; otherwise we will drop data.
// If aliasing is off, the NodeId already contains this information.
if (absl::GetFlag(FLAGS_experimental_alias_template_instantiations)) {
llvm::raw_string_ostream ostream(cleanup_id_);
for (const auto& Current :
RootTraversal(visitor_->getAllParents(), decl)) {
if (!(Current.decl && Current.indexed_parent)) continue;
if (const auto* czdecl =
dyn_cast<clang::ClassTemplateSpecializationDecl>(
Current.decl)) {
ostream << "#"
<< HashToString(visitor_->Hash(
&czdecl->getTemplateInstantiationArgs()));
} else if (const auto* fdecl =
dyn_cast<clang::FunctionDecl>(Current.decl)) {
if (const auto* template_args =
fdecl->getTemplateSpecializationArgs()) {
ostream << "#" << HashToString(visitor_->Hash(template_args));
}
} else if (const auto* vdecl =
dyn_cast<clang::VarTemplateSpecializationDecl>(
Current.decl)) {
ostream << "#"
<< HashToString(visitor_->Hash(
&vdecl->getTemplateInstantiationArgs()));
}
}
}
cleanup_id_ = visitor_->Observer.CompressString(cleanup_id_);
}
Prunability can_prune_ = Prunability::kNone;
std::string cleanup_id_;
IndexerASTVisitor* visitor_;
};
IndexedParentMap IndexerASTVisitor::BuildIndexedParentMap() const {
// We always need to run over the whole translation unit, as
// hasAncestor can escape any subtree.
// TODO(zarko): Is this relavant for naming?
ProfileBlock block(Observer.getProfilingCallback(), "build_parent_map");
return IndexedParentMap::Build(Context.getTranslationUnitDecl());
}
const IndexedParentMap* IndexerASTVisitor::getAllParents() const {
return &AllParents.get();
}
bool IndexerASTVisitor::declDominatesPrunableSubtree(const clang::Decl* Decl) {
return getAllParents()->DeclDominatesPrunableSubtree(Decl);
}
const clang::Decl* IndexerASTVisitor::GetInfluencedDeclFromLValueHead(
const clang::Expr* head) {
if (head == nullptr) return nullptr;
head = SkipTrivialAliasing(head).head;
if (auto* expr = llvm::dyn_cast_or_null<clang::DeclRefExpr>(head);
expr != nullptr && expr->getFoundDecl() != nullptr &&
(expr->getFoundDecl()->getKind() == clang::Decl::Kind::Var ||
expr->getFoundDecl()->getKind() == clang::Decl::Kind::ParmVar)) {
return expr->getFoundDecl();
}
if (auto* expr = llvm::dyn_cast_or_null<clang::MemberExpr>(head);
expr != nullptr) {
if (auto* member = expr->getMemberDecl(); member != nullptr) {
return member;
}
}
return nullptr;
}
IndexerASTVisitor::TargetExpr IndexerASTVisitor::SkipTrivialAliasing(
const clang::Expr* expr) {
// TODO(zarko): calls with alternate semantics
if (expr == nullptr) return {nullptr, std::nullopt};
if (const auto* star =
llvm::dyn_cast_or_null<clang::UnaryOperator>(expr->IgnoreParens());
star != nullptr && star->getOpcode() == clang::UO_Deref &&
star->getSubExpr() != nullptr) {
// star := *body
const auto* body = star->getSubExpr()->IgnoreParens();
if (const auto* amp = llvm::dyn_cast_or_null<clang::UnaryOperator>(body);
amp != nullptr && amp->getOpcode() == clang::UO_AddrOf &&
amp->getSubExpr() != nullptr) {
// star := *&var
const auto* var = amp->getSubExpr()->IgnoreParens();
if (const auto* dre = llvm::dyn_cast_or_null<clang::DeclRefExpr>(var)) {
return {dre, std::nullopt};
}
}
if (const auto* call = llvm::dyn_cast_or_null<clang::CallExpr>(body);
call != nullptr && call->getCallee() != nullptr &&
call->getCalleeDecl() != nullptr) {
// star := *foo() || *x->foo()
// TODO(zarko): here and above: trace down deref/call chains?
// we don't currently handle x.y.z->mutable_foo()
if (const auto* as = AlternateSemanticForDecl(call->getCalleeDecl());
as != nullptr && as->use_kind == GraphObserver::UseKind::kTakeAlias) {
return {call->getCallee(), as->node};
}
}
}
return {expr, std::nullopt};
}
bool IndexerASTVisitor::IsDefinition(const clang::VarDecl* VD) {
if (const auto* PVD = dyn_cast<clang::ParmVarDecl>(VD)) {
// For parameters, we want to report them as definitions iff they're
// part of a function definition. Current (2013-02-14) Clang appears
// to report all function parameter declarations as definitions.
if (const auto* FD = dyn_cast<clang::FunctionDecl>(PVD->getDeclContext())) {
return IsDefinition(FD);
}
}
// This one's a little quirky. It would actually work to just return
// implicit_cast<bool>(VD->isThisDeclarationADefinition()), because
// VarDecl::DeclarationOnly is zero, but this is more explicit.
return VD->isThisDeclarationADefinition() != clang::VarDecl::DeclarationOnly;
}
SourceRange IndexerASTVisitor::RangeForNameOfDeclaration(
const clang::NamedDecl* Decl) const {
return ClangRangeFinder(Observer.getSourceManager(),
Observer.getLangOptions())
.RangeForNameOf(Decl);
}
void IndexerASTVisitor::MaybeRecordDefinitionRange(
const absl::optional<GraphObserver::Range>& R,
const GraphObserver::NodeId& Id,
const absl::optional<GraphObserver::NodeId>& DeclId) {
if (R) {
Observer.recordDefinitionBindingRange(R.value(), Id, DeclId);
}
}
void IndexerASTVisitor::MaybeRecordFullDefinitionRange(
const absl::optional<GraphObserver::Range>& R,
const GraphObserver::NodeId& Id,
const absl::optional<GraphObserver::NodeId>& DeclId) {
if (R) {
Observer.recordFullDefinitionRange(R.value(), Id, DeclId);
}
}
GraphObserver::Implicit IndexerASTVisitor::IsImplicit(
const GraphObserver::Range& Range) {
return (Job->UnderneathImplicitTemplateInstantiation ||
Range.Kind != GraphObserver::Range::RangeKind::Physical)
? GraphObserver::Implicit::Yes
: GraphObserver::Implicit::No;
}
void IndexerASTVisitor::RecordCallEdges(const GraphObserver::Range& Range,
const GraphObserver::NodeId& Callee,
GraphObserver::CallDispatch D) {
if (!options_.RecordCallDirectness) D = GraphObserver::CallDispatch::kDefault;
if (Job->BlameStack.empty()) {
if (auto FileId = Observer.recordFileInitializer(Range)) {
Observer.recordCallEdge(Range, FileId.value(), Callee, IsImplicit(Range),
D);
}
} else {
for (const auto& Caller : Job->BlameStack.back()) {
Observer.recordCallEdge(Range, Caller, Callee, IsImplicit(Range), D);
}
}
}
void IndexerASTVisitor::RecordBlame(const clang::Decl* Decl,
const GraphObserver::Range& Range) {
if (ShouldHaveBlameContext(Decl)) {
if (Job->BlameStack.empty()) {
if (auto FileId = Observer.recordFileInitializer(Range)) {
Observer.recordBlameLocation(Range, *FileId,
GraphObserver::Claimability::Unclaimable,
this->IsImplicit(Range));
}
} else {
for (const auto& Context : Job->BlameStack.back()) {
Observer.recordBlameLocation(Range, Context,
GraphObserver::Claimability::Unclaimable,
this->IsImplicit(Range));
}
}
}
}
/// An in-flight possible lookup result used to approximate qualified lookup.
struct PossibleLookup {
clang::LookupResult Result;
const clang::DeclContext* Context;
};
/// Greedily consumes tokens to try and find the longest qualified name that
/// results in a nonempty lookup result.
class PossibleLookups {
public:
/// \param RC The most specific context to start searching in.
/// \param TC The translation unit context.
PossibleLookups(clang::ASTContext& C, clang::Sema& S,
const clang::DeclContext* RC, const clang::DeclContext* TC)
: Context(C), Sema(S), RootContext(RC), TUContext(TC) {
StartIdentifier();
}
/// Describes what happened after we added the last token to the lookup state.
enum class LookupResult {
Done, ///< Lookup is terminated; don't add any more tokens.
Updated, ///< The last token narrowed down the lookup.
Progress ///< The last token didn't narrow anything down.
};
/// Try to use `Tok` to narrow down the lookup.
LookupResult AdvanceLookup(const clang::Token& Tok) {
if (Tok.is(clang::tok::coloncolon)) {
// This flag only matters if the possible lookup list is empty.
// Just drop ::s on the floor otherwise.
ForceTUContext = true;
return LookupResult::Progress;
} else if (Tok.is(clang::tok::raw_identifier)) {
bool Invalid = false;
const char* TokChar = Context.getSourceManager().getCharacterData(
Tok.getLocation(), &Invalid);
if (Invalid || !TokChar) {
return LookupResult::Done;
}
llvm::StringRef TokText(TokChar, Tok.getLength());
const auto& Id = Context.Idents.get(TokText);
clang::DeclarationNameInfo DeclName(
Context.DeclarationNames.getIdentifier(&Id), Tok.getLocation());
if (Lookups.empty()) {
return StartLookups(DeclName);
} else {
return AdvanceLookups(DeclName);
}
}
return LookupResult::Done;
}
/// Start a new identifier.
void StartIdentifier() {
Lookups.clear();
ForceTUContext = false;
}
/// Retrieve a vector of plausible lookup results with the most specific
/// ones first.
const std::vector<PossibleLookup>& LookupState() { return Lookups; }
private:
/// Start a new lookup from `DeclName`.
LookupResult StartLookups(const clang::DeclarationNameInfo& DeclName) {
CHECK(Lookups.empty());
for (const clang::DeclContext* Context = ForceTUContext ? TUContext
: RootContext;
Context != nullptr; Context = Context->getParent()) {
clang::LookupResult FirstLookup(
Sema, DeclName, clang::Sema::LookupNameKind::LookupAnyName);
FirstLookup.suppressDiagnostics();
if (IsContextSafeForLookup(Context) &&
Sema.LookupQualifiedName(
FirstLookup, const_cast<clang::DeclContext*>(Context), false)) {
Lookups.push_back({std::move(FirstLookup), Context});
} else {
CHECK(FirstLookup.empty());
// We could be looking at a (type) parameter here. Note that this
// may still be part of a qualified (dependent) name.
if (const auto* FunctionContext =
dyn_cast_or_null<clang::FunctionDecl>(Context)) {
for (const auto& Param : FunctionContext->parameters()) {
if (Param->getDeclName() == DeclName.getName()) {
clang::LookupResult DerivedResult(clang::LookupResult::Temporary,
FirstLookup);
DerivedResult.suppressDiagnostics();
DerivedResult.addDecl(Param);
Lookups.push_back({std::move(DerivedResult), Context});
}
}
} else if (const auto* TemplateParams = GetTypeParameters(Context)) {
for (const auto& TParam : *TemplateParams) {
if (TParam->getDeclName() == DeclName.getName()) {
clang::LookupResult DerivedResult(clang::LookupResult::Temporary,
FirstLookup);
DerivedResult.suppressDiagnostics();
DerivedResult.addDecl(TParam);
Lookups.push_back({std::move(DerivedResult), Context});
}
}
}
}
}
return Lookups.empty() ? LookupResult::Done : LookupResult::Updated;
}
/// Continue each in-flight lookup using `DeclName`.
LookupResult AdvanceLookups(const clang::DeclarationNameInfo& DeclName) {
// Try to advance each lookup we have stored.
std::vector<PossibleLookup> ResultLookups;
for (auto& Lookup : Lookups) {
for (const clang::NamedDecl* Result : Lookup.Result) {
const auto* Context = dyn_cast<clang::DeclContext>(Result);
if (!Context) {
Context = Lookup.Context;
}
clang::LookupResult NextResult(
Sema, DeclName, clang::Sema::LookupNameKind::LookupAnyName);
NextResult.suppressDiagnostics();
if (IsContextSafeForLookup(Context) &&
Sema.LookupQualifiedName(
NextResult, const_cast<clang::DeclContext*>(Context), false)) {
ResultLookups.push_back({std::move(NextResult), Context});
}
}
}
if (!ResultLookups.empty()) {
Lookups = std::move(ResultLookups);
return LookupResult::Updated;
} else {
return LookupResult::Done;
}
}
/// All the plausible lookup results so far. This is sorted with the most
/// specific results first (i.e., the ones that came from the closest
/// DeclContext).
std::vector<PossibleLookup> Lookups;
/// The ASTContext we're under.
clang::ASTContext& Context;
/// The Sema instance we're using.
clang::Sema& Sema;
/// The nearest declaration context.
const clang::DeclContext* RootContext;
/// The translation unit's declaration context.
const clang::DeclContext* TUContext;
/// Set if the current lookup is unambiguously in TUContext.
bool ForceTUContext = false;
};
/// The state for heuristic parsing of identifiers in comment bodies.
enum class RefParserState {
WaitingForMark, ///< We're waiting for something that might denote an
///< embedded identifier.
SawCommand ///< We saw something Clang identifies as a comment command.
};
/// Adds markup to Text to define anchor locations and sorts Anchors
/// accordingly.
void InsertAnchorMarks(std::string& Text, std::vector<MiniAnchor>& Anchors) {
// Drop empty or negative-length anchors.
Anchors.erase(
std::remove_if(Anchors.begin(), Anchors.end(),
[](const MiniAnchor& A) { return A.Begin >= A.End; }),
Anchors.end());
std::sort(Anchors.begin(), Anchors.end(),
[](const MiniAnchor& A, const MiniAnchor& B) {
return std::tie(A.Begin, B.End) < std::tie(B.Begin, A.End);
});
std::string NewText;
NewText.reserve(Text.size() + Anchors.size() * 2);
auto NextAnchor = Anchors.begin();
std::multiset<size_t> EndLocations;
for (size_t C = 0; C < Text.size(); ++C) {
while (!EndLocations.empty() && *(EndLocations.begin()) == C) {
NewText.push_back(']');
EndLocations.erase(EndLocations.begin());
}
for (; NextAnchor != Anchors.end() && C == NextAnchor->Begin;
++NextAnchor) {
NewText.push_back('[');
EndLocations.insert(NextAnchor->End);
}
if (Text[C] == '[' || Text[C] == ']' || Text[C] == '\\') {
// Escape [, ], and \.
NewText.push_back('\\');
}
NewText.push_back(Text[C]);
}
NewText.resize(NewText.size() + EndLocations.size(), ']');
Text.swap(NewText);
}
void IndexerASTVisitor::HandleFileLevelComments(
FileID Id, const GraphObserver::NodeId& FileNode) {
const auto& RCL = Context.Comments;
// Find the block of comments for the given file. This behavior is not well-
// defined by Clang, which commits only to the RawComments being
// "sorted in order of appearance in the translation unit".
const std::map<unsigned, clang::RawComment*>* FileComments =
RCL.getCommentsInFile(Id);
if (FileComments == nullptr || FileComments->empty()) {
return;
}
// Find the first RawComment whose start location is greater or equal to
// the start of the file whose FileID is Id.
clang::RawComment* C = FileComments->begin()->second;
// Walk through the comments in Id starting with the one at the top. If we
// ever leave Id, then we're done. (The first time around the loop, if C isn't
// already in Id, this check will immediately break;.)
//
// Here's a simple heuristic: the first comment in a file is the file-level
// comment. This is bad for files with (e.g.) license blocks, but we can
// gradually refine as necessary.
if (VisitedComments.find(C) == VisitedComments.end()) {
VisitComment(C, Context.getTranslationUnitDecl(), FileNode);
}
}
void IndexerASTVisitor::VisitComment(
const clang::RawComment* Comment, const clang::DeclContext* DC,
const GraphObserver::NodeId& DocumentedNode) {
VisitedComments.insert(Comment);
const auto& SM = *Observer.getSourceManager();
std::string Text = Comment->getRawText(SM).str();
std::string StrippedRawText;
std::map<SourceLocation, size_t> OffsetsInStrippedRawText;
std::vector<MiniAnchor> StrippedRawTextAnchors;
clang::comments::Lexer Lexer(Context.getAllocator(), Context.getDiagnostics(),
Context.getCommentCommandTraits(),
Comment->getSourceRange().getBegin(),
Text.data(), Text.data() + Text.size());
clang::comments::Token Tok;
std::vector<clang::Token> IdentifierTokens;
PossibleLookups Lookups(Context, Sema, DC, Context.getTranslationUnitDecl());
auto RecordDocDeclUse = [&](const SourceRange& Range,
const GraphObserver::NodeId& ResultId) {
if (auto RCC = ExplicitRangeInCurrentContext(Range)) {
Observer.recordDeclUseLocationInDocumentation(RCC.value(), ResultId);
}
auto RawLoc = OffsetsInStrippedRawText.lower_bound(Range.getBegin());
if (RawLoc != OffsetsInStrippedRawText.end()) {
// This is a single token (so we won't span multiple stripped ranges).
size_t StrippedBegin = RawLoc->second +
Range.getBegin().getRawEncoding() -
RawLoc->first.getRawEncoding();
size_t StrippedLength =
Range.getEnd().getRawEncoding() - Range.getBegin().getRawEncoding();
if (StrippedLength != 0) {
StrippedRawTextAnchors.emplace_back(MiniAnchor{
StrippedBegin, StrippedBegin + StrippedLength, ResultId});
}
}
};
// Attribute all tokens on [FirstToken,LastToken] to every possible lookup
// result inside PossibleLookups.
auto HandleLookupResult = [&](int FirstToken, int LastToken) {
for (const auto& Results : Lookups.LookupState()) {
for (auto Result : Results.Result) {
auto ResultId = BuildNodeIdForRefToDecl(Result);
for (int Token = FirstToken; Token <= LastToken; ++Token) {
RecordDocDeclUse(SourceRange(IdentifierTokens[Token].getLocation(),
IdentifierTokens[Token].getEndLoc()),
ResultId);
}
}
}
};
auto State = RefParserState::WaitingForMark;
// FoundEndingDelimiter will be called whenever we're sure that no more
// tokens can be added to IdentifierTokens that could be related to the same
// identifier. (IdentifierTokens might still contain multiple identifiers,
// as in the doc text "`foo`, `bar`, or `baz`".)
// TODO(zarko): Deal with template arguments (`foo<int>::bar`), balanced
// delimiters (`foo::bar(int, c<int>)`), and dtors (which are troubling
// because they have ~s out in front). The goal here is not to completely
// reimplement a C/C++ parser, but instead to build just enough to make good
// guesses.
auto FoundEndingDelimiter = [&]() {
int IdentifierStart = -1;
int CurrentIndex = 0;
if (State == RefParserState::SawCommand) {
// Start as though we've seen a quote and consume tokens until we're not
// making progress.
IdentifierStart = 0;
Lookups.StartIdentifier();
}
for (const auto& Tok : IdentifierTokens) {
if (IdentifierStart >= 0) {
if (Lookups.AdvanceLookup(Tok) == PossibleLookups::LookupResult::Done) {
// We can't match an identifier using this token. Either it's the
// matching close-quote or it's some other weirdness.
if (IdentifierStart != CurrentIndex) {
HandleLookupResult(IdentifierStart, CurrentIndex - 1);