-
Notifications
You must be signed in to change notification settings - Fork 2.7k
Expand file tree
/
Copy pathast_visitor.cc
More file actions
1773 lines (1628 loc) · 70.1 KB
/
ast_visitor.cc
File metadata and controls
1773 lines (1628 loc) · 70.1 KB
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 2025 Google LLC.
//
// 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 "indexer/frontend/ast_visitor.h"
#include <cassert>
#include <list>
#include <optional>
#include <string>
#include <vector>
#include "indexer/frontend/common.h"
#include "indexer/index/types.h"
#include "absl/log/check.h"
#include "absl/log/log.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/str_join.h"
#include "clang/AST/Attr.h"
#include "clang/AST/Decl.h"
#include "clang/AST/DeclCXX.h"
#include "clang/AST/DeclTemplate.h"
#include "clang/AST/DeclarationName.h"
#include "clang/AST/Expr.h"
#include "clang/AST/ExprCXX.h"
#include "clang/AST/PrettyPrinter.h"
#include "clang/AST/TemplateBase.h"
#include "clang/AST/Type.h"
#include "clang/Basic/FileEntry.h"
#include "clang/Basic/OperatorKinds.h"
#include "clang/Basic/SourceLocation.h"
#include "clang/Basic/Specifiers.h"
#include "clang/Basic/TypeTraits.h"
#include "clang/Sema/Lookup.h"
#include "clang/Sema/Sema.h"
#include "llvm/ADT/APSInt.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/MapVector.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/SmallSet.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/Support/Casting.h"
#include "llvm/Support/raw_ostream.h"
namespace oss_fuzz {
namespace indexer {
namespace {
const clang::PrintingPolicy& GetPrintingPolicy() {
static clang::PrintingPolicy static_policy = ([] {
clang::PrintingPolicy policy({});
policy.adjustForCPlusPlus();
policy.SplitTemplateClosers = false;
policy.SuppressTemplateArgsInCXXConstructors = true;
return policy;
})();
return static_policy;
}
// Helper functions used to distinguish between declarations and definitions, so
// that we can mark declarations as incomplete and resolve them at a later
// stage.
bool IsADefinition(const clang::Decl* decl) {
if (llvm::isa<clang::RecordDecl>(decl)) {
const auto* record_decl = llvm::cast<clang::RecordDecl>(decl);
if (!record_decl->isThisDeclarationADefinition() &&
!llvm::isa<clang::ClassTemplateSpecializationDecl>(decl)) {
return false;
}
} else if (llvm::isa<clang::FunctionDecl>(decl)) {
const auto* function_decl = llvm::cast<clang::FunctionDecl>(decl);
if (llvm::isa<clang::CXXMethodDecl>(function_decl)) {
const auto* cxx_method_decl =
llvm::cast<clang::CXXMethodDecl>(function_decl);
if (cxx_method_decl->getParent()->isLambda()) {
return true;
}
}
if (!function_decl->isThisDeclarationADefinition()) {
return false;
}
}
return true;
}
bool IsParentADefinition(const clang::Decl* decl) {
const auto* parent_context = decl->getNonTransparentDeclContext();
if (llvm::isa<clang::Decl>(parent_context)) {
const auto* parent = llvm::cast<clang::Decl>(parent_context);
return IsADefinition(parent);
} else {
return true;
}
}
const clang::ClassTemplateDecl* GetClassTemplateDefinition(
const clang::ClassTemplateDecl* class_template_decl) {
if (class_template_decl->getTemplatedDecl()->getDefinition()) {
class_template_decl = class_template_decl->getTemplatedDecl()
->getDefinition()
->getDescribedClassTemplate();
}
return class_template_decl;
}
const clang::ClassTemplateSpecializationDecl* FindSpecialization(
const clang::ClassTemplateDecl* class_template_decl,
const llvm::ArrayRef<clang::TemplateArgument> args,
const clang::ASTContext& context) {
// Without this, sugared types can lead to lookup misses.
llvm::SmallVector<clang::TemplateArgument, 4> canonical_args;
for (const clang::TemplateArgument& arg : args) {
canonical_args.push_back(context.getCanonicalTemplateArgument(arg));
}
// XXX(kartynnik): `findSpecialization` is a non-`const` method because it can
// lead to loading external specializations. Arguably this could have been
// handled through `mutable` fields because logically this doesn't affect the
// forthcoming behavior of the object.
void* insert_pos = nullptr;
return const_cast<clang::ClassTemplateDecl*>(class_template_decl)
->findSpecialization(canonical_args, insert_pos);
}
// Helper functions to find the closest explicit template specialization that
// matches the provided template arguments.
const clang::Decl* GetSpecializationDecl(
const clang::ClassTemplateDecl* class_template_decl,
const llvm::ArrayRef<clang::TemplateArgument> template_arguments,
const clang::ASTContext& context) {
class_template_decl = GetClassTemplateDefinition(class_template_decl);
const clang::Decl* decl = class_template_decl;
const auto* specialization_decl =
FindSpecialization(class_template_decl, template_arguments, context);
while (specialization_decl) {
// This happens when we have a forward declaration of a template class,
// followed by an explicit instantiation, followed by the definition. In
// that case, when we look for the correct specialization of the template
// class definition, we get a ClassTemplateSpecializationDecl which is of
// type TSK_Undeclared and which references the forward declaration of the
// template class instead of the correct definition. Calling
// getInstantiatedFrom on such a ClassTemplateSpecializationDecl will return
// null.
//
// FrontendTest.UsingSpecialization tests the handling of this case.
if (specialization_decl->getSpecializationKind() ==
clang::TemplateSpecializationKind::TSK_Undeclared) {
return class_template_decl;
}
// Otherwise we should be able to continue walking the chain of
// specialisations until we find the best match.
const auto instantiated_from = specialization_decl->getInstantiatedFrom();
if (instantiated_from.isNull()) {
// Includes the case of `specialization_decl->isExplicitSpecialization()`.
decl = specialization_decl;
break;
} else if (llvm::isa<clang::ClassTemplateDecl*>(instantiated_from)) {
decl = llvm::cast<clang::ClassTemplateDecl*>(instantiated_from);
break;
} else {
specialization_decl =
llvm::cast<clang::ClassTemplatePartialSpecializationDecl*>(
instantiated_from);
}
}
if (llvm::isa<clang::ClassTemplateDecl>(decl)) {
decl =
GetClassTemplateDefinition(llvm::cast<clang::ClassTemplateDecl>(decl));
}
return decl;
}
const clang::Decl* GetSpecializationDecl(
const clang::TemplateSpecializationType* type,
const clang::ASTContext& context) {
// There's no direct link to the clang::Type for the template type being
// specialized, so this gets us a reference to the underlying template.
//
// Note that template_decl can be nullptr in the case of template template
// parameters that are still instantiation dependent in this specialization.
// Those are not "real" types, so we don't want to add references to them.
const auto* template_decl = type->getTemplateName().getAsTemplateDecl();
const clang::Decl* decl = template_decl;
if (template_decl) {
if (llvm::isa<clang::ClassTemplateDecl>(template_decl)) {
auto* class_template_decl =
llvm::cast<clang::ClassTemplateDecl>(template_decl);
decl = GetSpecializationDecl(class_template_decl,
type->template_arguments(), context);
} else if (llvm::isa<clang::TypeAliasTemplateDecl>(template_decl)) {
return llvm::cast<clang::TypeAliasTemplateDecl>(template_decl)
->getTemplatedDecl();
}
}
return decl;
}
const clang::Decl* GetSpecializationDecl(
const clang::ClassTemplateSpecializationDecl* decl,
const clang::ASTContext& context) {
// If this is an explicit specialization, then there's no need to look for
// the best matching specialization.
if (decl->isExplicitSpecialization()) {
return decl;
}
return GetSpecializationDecl(decl->getSpecializedTemplate(),
decl->getTemplateArgs().asArray(), context);
}
const clang::CXXRecordDecl* GetTemplatePrototypeRecordDecl(
const clang::ClassTemplateSpecializationDecl* decl,
const clang::ASTContext& context) {
const clang::Decl* specialization_decl = GetSpecializationDecl(decl, context);
if (const auto* class_template_decl =
llvm::dyn_cast<clang::ClassTemplateDecl>(specialization_decl)) {
return class_template_decl->getTemplatedDecl();
}
const clang::CXXRecordDecl* record_decl =
llvm::dyn_cast<clang::ClassTemplateSpecializationDecl>(
specialization_decl);
CHECK_NE(record_decl, nullptr);
return record_decl;
}
bool IsIncompleteFunction(const clang::FunctionDecl* function_decl) {
return !function_decl->hasBody() && !function_decl->isDefaulted() &&
!function_decl->isPureVirtual() &&
!function_decl->getBuiltinID(true) &&
!function_decl->hasDefiningAttr();
}
// `decl` is required to be a `clang::NamedDecl`.
// If it is inside a template instantiation, finds the context where it is
// instantiated from and finds the corresponding entity by name.
const clang::NamedDecl* GetTemplatePrototypeNamedDecl(
const clang::Decl* decl, const clang::ASTContext& context) {
const clang::NamedDecl* named_decl = llvm::dyn_cast<clang::NamedDecl>(decl);
CHECK_NE(named_decl, nullptr);
clang::DeclarationName field_name = named_decl->getDeclName();
if (field_name.getAsString().empty()) {
// E.g. for a `DecompositionDecl`.
return nullptr;
}
const clang::DeclContext* template_context = nullptr;
const clang::TemplateDecl* template_decl = nullptr;
if (const auto* class_specialization_decl =
llvm::dyn_cast<clang::ClassTemplateSpecializationDecl>(
named_decl->getDeclContext())) {
if (class_specialization_decl->isExplicitSpecialization()) {
return nullptr;
}
if (const clang::CXXRecordDecl* template_definition =
GetTemplatePrototypeRecordDecl(class_specialization_decl,
context)) {
template_context = template_definition;
template_decl = template_definition->getDescribedClassTemplate();
} else {
return nullptr;
}
} else if (const auto* function_decl = llvm::dyn_cast<clang::FunctionDecl>(
named_decl->getDeclContext())) {
if (const clang::FunctionDecl* instantiation_pattern =
function_decl->getTemplateInstantiationPattern()) {
template_context = instantiation_pattern;
template_decl = instantiation_pattern->getDescribedFunctionTemplate();
} else if (function_decl->getDescribedFunctionTemplate() &&
function_decl->getDescribedFunctionTemplate()
->getInstantiatedFromMemberTemplate()) {
template_decl = function_decl->getDescribedFunctionTemplate()
->getInstantiatedFromMemberTemplate();
template_context = llvm::dyn_cast<clang::FunctionDecl>(
template_decl->getTemplatedDecl());
} else {
return nullptr;
}
} else {
return nullptr;
}
if (template_context) {
// We are using `decls` instead of `fields` to also account for statics.
for (const clang::Decl* inner_decl : template_context->decls()) {
if (const auto* inner_named_decl =
llvm::dyn_cast<clang::NamedDecl>(inner_decl)) {
if (inner_named_decl->getDeclName() == field_name) {
if (llvm::isa<clang::BindingDecl>(inner_named_decl)) {
// TODO: Figure out if we can support these.
return nullptr;
}
return inner_named_decl;
}
}
}
}
if (template_decl) {
// Look up template parameters as well.
for (const clang::NamedDecl* template_parameter :
*template_decl->getTemplateParameters()) {
if (template_parameter->getDeclName() == field_name) {
return template_parameter;
}
}
}
return nullptr;
}
// Helper functions used to print template parameters for template declarations
// and specializations, since this code can be shared between class and function
// templates.
std::string FormatTemplateParameters(
const clang::TemplateParameterList* params) {
llvm::SmallString<128> string;
llvm::raw_svector_ostream stream(string);
stream << "<";
for (int i = 0; i < params->size(); ++i) {
if (i != 0) {
stream << ", ";
}
const auto* param = params->getParam(i);
if (llvm::isa<clang::NonTypeTemplateParmDecl>(param)) {
const auto* value_param =
llvm::cast<clang::NonTypeTemplateParmDecl>(param);
auto value_type = value_param->getType();
stream << value_type.getAsString(GetPrintingPolicy());
} else {
param->getNameForDiagnostic(stream, GetPrintingPolicy(), false);
if (param->isParameterPack()) {
stream << "...";
}
}
}
stream << ">";
return stream.str().str();
}
template <class TemplateArgumentType>
std::string FormatTemplateArguments(const clang::TemplateParameterList* params,
llvm::ArrayRef<TemplateArgumentType> args) {
llvm::SmallString<128> string;
llvm::raw_svector_ostream stream(string);
clang::printTemplateArgumentList(stream, args, GetPrintingPolicy(), params);
return stream.str().str();
}
// Helper functions to generate the `<typename T, int S>` suffixes when handling
// templates.
std::string GetTemplateParameterSuffix(const clang::TemplateDecl* decl) {
return FormatTemplateParameters(decl->getTemplateParameters());
}
std::string GetTemplateParameterSuffix(
const clang::ClassTemplateSpecializationDecl* decl) {
const clang::TemplateParameterList* params =
decl->getSpecializedTemplate()->getTemplateParameters();
if (const auto* partial_spec_decl =
llvm::dyn_cast<clang::ClassTemplatePartialSpecializationDecl>(decl)) {
if (const clang::ASTTemplateArgumentListInfo* args_as_written =
partial_spec_decl->getTemplateArgsAsWritten()) {
return FormatTemplateArguments(params, args_as_written->arguments());
}
}
return FormatTemplateArguments(params, decl->getTemplateArgs().asArray());
}
std::string GetTemplateParameterSuffix(
const clang::TemplateSpecializationType* type,
const clang::ASTContext& context) {
const auto* template_decl = type->getTemplateName().getAsTemplateDecl();
if (llvm::isa<clang::ClassTemplateDecl>(template_decl)) {
const auto* class_template_decl =
llvm::cast<clang::ClassTemplateDecl>(template_decl);
return GetTemplateParameterSuffix(FindSpecialization(
class_template_decl, type->template_arguments(), context));
} else {
CHECK(llvm::isa<clang::TypeAliasTemplateDecl>(template_decl));
const auto* type_alias_template_decl =
llvm::cast<clang::TypeAliasTemplateDecl>(template_decl);
return FormatTemplateArguments(
type_alias_template_decl->getTemplateParameters(),
type->template_arguments());
}
}
std::string GetTemplateParameterSuffix(
const clang::FunctionTemplateSpecializationInfo* info) {
return FormatTemplateArguments(info->getTemplate()->getTemplateParameters(),
info->TemplateArguments->asArray());
}
std::string GetTemplateParameterSuffix(
const clang::VarTemplateSpecializationDecl* decl,
const clang::ASTContext& context) {
const clang::TemplateParameterList* params =
decl->getSpecializedTemplate()->getTemplateParameters();
if (const auto* partial_spec_decl =
llvm::dyn_cast<clang::VarTemplatePartialSpecializationDecl>(decl)) {
if (const clang::ASTTemplateArgumentListInfo* args_as_written =
partial_spec_decl->getTemplateArgsAsWritten()) {
return FormatTemplateArguments(params, args_as_written->arguments());
}
}
return FormatTemplateArguments(params, decl->getTemplateArgs().asArray());
}
std::string GetName(const clang::Decl* decl) {
std::string name = "";
if (auto field_decl = llvm::dyn_cast<clang::FieldDecl>(decl);
field_decl && field_decl->isAnonymousStructOrUnion()) {
// Implicit unnamed fields for anonymous structs/unions are named after the
// latter. We ignore them elsewhere; this is only for tests to assert
// they're absent (the name contains the source file path otherwise).
decl = field_decl->getType()->getAsRecordDecl();
CHECK_NE(decl, nullptr);
}
if (llvm::isa<clang::RecordDecl>(decl)) {
const auto* record_decl = llvm::cast<clang::RecordDecl>(decl);
name = record_decl->getName().str();
if (name.empty() && record_decl->isStruct()) {
return "(anonymous struct)";
} else if (name.empty() && record_decl->isUnion()) {
return "(anonymous union)";
}
} else if (llvm::isa<clang::NamedDecl>(decl)) {
// Lambda function handling is a little bit tricky, since we want to use
// the implicit operator() definition, but that doesn't track whether we are
// in a lambda function, so we need to check whether the parent decl is an
// implicit lambda class.
if (llvm::isa<clang::CXXMethodDecl>(decl)) {
auto* cxx_method_decl = llvm::cast<clang::CXXMethodDecl>(decl);
if (cxx_method_decl->getParent()->isLambda()) {
return "lambda";
}
}
const auto* named_decl = llvm::cast<clang::NamedDecl>(decl);
llvm::SmallString<32> string;
llvm::raw_svector_ostream stream(string);
named_decl->printName(stream, GetPrintingPolicy());
name = string.str().str();
}
return name;
}
std::string GetNameSuffix(const clang::Decl* decl,
const clang::ASTContext& context) {
std::string name_suffix = "";
if (llvm::isa<clang::CXXRecordDecl>(decl)) {
const auto* cxx_record_decl = llvm::cast<clang::CXXRecordDecl>(decl);
if (llvm::isa<clang::ClassTemplateSpecializationDecl>(decl)) {
const auto* class_template_specialization_decl =
llvm::cast<clang::ClassTemplateSpecializationDecl>(decl);
name_suffix =
GetTemplateParameterSuffix(class_template_specialization_decl);
} else if (cxx_record_decl->getDescribedClassTemplate()) {
name_suffix = GetTemplateParameterSuffix(
cxx_record_decl->getDescribedClassTemplate());
}
} else if (llvm::isa<clang::FunctionDecl>(decl)) {
const auto* function_decl = llvm::cast<clang::FunctionDecl>(decl);
std::string template_param_suffix = "";
if (function_decl->getTemplateSpecializationInfo()) {
template_param_suffix = GetTemplateParameterSuffix(
function_decl->getTemplateSpecializationInfo());
} else if (function_decl->getDescribedFunctionTemplate()) {
template_param_suffix = GetTemplateParameterSuffix(
function_decl->getDescribedFunctionTemplate());
}
std::vector<std::string> param_types;
param_types.reserve(function_decl->getNumParams());
for (int i = 0; i < function_decl->getNumParams(); ++i) {
const clang::ParmVarDecl* parm_decl = function_decl->getParamDecl(i);
param_types.emplace_back(
parm_decl->getType().getAsString(GetPrintingPolicy()));
}
if (function_decl->isVariadic()) {
param_types.emplace_back("...");
}
name_suffix = absl::StrCat(template_param_suffix, "(",
absl::StrJoin(param_types, ", "), ")");
if (llvm::isa<clang::CXXMethodDecl>(decl)) {
const auto* cxx_method_decl = llvm::cast<clang::CXXMethodDecl>(decl);
if (!cxx_method_decl->getParent()->isLambda()) {
if (cxx_method_decl->isConst()) {
absl::StrAppend(&name_suffix, " const");
}
if (cxx_method_decl->isVolatile()) {
absl::StrAppend(&name_suffix, " volatile");
}
switch (cxx_method_decl->getRefQualifier()) {
case clang::RQ_None:
break;
case clang::RQ_LValue:
absl::StrAppend(&name_suffix, " &");
break;
case clang::RQ_RValue:
absl::StrAppend(&name_suffix, " &&");
break;
}
}
}
} else if (llvm::isa<clang::VarDecl>(decl)) {
const auto* var_decl = llvm::cast<clang::VarDecl>(decl);
if (const auto* var_template_decl = var_decl->getDescribedVarTemplate()) {
name_suffix = GetTemplateParameterSuffix(var_template_decl);
} else if (const auto* var_template_specialization_decl =
llvm::dyn_cast<clang::VarTemplateSpecializationDecl>(decl)) {
name_suffix =
GetTemplateParameterSuffix(var_template_specialization_decl, context);
}
} else if (llvm::isa<clang::TypeAliasDecl>(decl)) {
const auto* type_alias_decl = llvm::cast<clang::TypeAliasDecl>(decl);
const auto* type_alias_template_decl =
type_alias_decl->getDescribedAliasTemplate();
if (type_alias_template_decl) {
name_suffix = GetTemplateParameterSuffix(type_alias_template_decl);
}
}
return name_suffix;
}
std::string GetNamePrefixForDeclContext(const clang::DeclContext* decl_context,
const clang::ASTContext& ast_context,
bool include_function_scope = true) {
std::list<std::string> parts = {""};
while (decl_context) {
if (llvm::isa<clang::FunctionDecl>(decl_context)) {
if (!include_function_scope) {
// If we're not including function scopes, then we can stop when we
// reach the first containing function.
break;
}
const auto* parent_decl = llvm::cast<clang::Decl>(decl_context);
parts.push_front(absl::StrCat(GetName(parent_decl),
GetNameSuffix(parent_decl, ast_context)));
} else if (llvm::isa<clang::NamespaceDecl>(decl_context)) {
// namespace name should always appear in our name prefix.
const auto* namespace_decl =
llvm::cast<clang::NamespaceDecl>(decl_context);
if (namespace_decl->isAnonymousNamespace()) {
parts.push_front("(anonymous namespace)");
} else {
parts.push_front(namespace_decl->getName().str());
}
} else if (llvm::isa<clang::RecordDecl>(decl_context)) {
bool is_lambda = false;
if (llvm::isa<clang::CXXRecordDecl>(decl_context)) {
const auto* cxx_record_decl =
llvm::cast<clang::CXXRecordDecl>(decl_context);
is_lambda = cxx_record_decl->isLambda();
}
// class / union / struct name should always appear in our name prefix,
// unless it's the implicit class for a lambda function.
if (!is_lambda) {
const auto* parent_decl = llvm::cast<clang::Decl>(decl_context);
parts.push_front(absl::StrCat(GetName(parent_decl),
GetNameSuffix(parent_decl, ast_context)));
}
} else if (llvm::isa<clang::EnumDecl>(decl_context)) {
const auto* enum_decl = llvm::cast<clang::EnumDecl>(decl_context);
// The only time that an enum should appear in our name prefix is when it
// is a c++11 scoped enum / enum class.
if (enum_decl->isScoped() || enum_decl->isScopedUsingClassTag()) {
const auto* parent_decl = llvm::cast<clang::Decl>(decl_context);
parts.push_front(absl::StrCat(GetName(parent_decl),
GetNameSuffix(parent_decl, ast_context)));
}
}
decl_context = decl_context->getParent();
}
return absl::StrJoin(parts, "::");
}
std::string GetNamePrefix(const clang::Decl* decl,
const clang::ASTContext& ast_context) {
if (llvm::isa<clang::ParmVarDecl>(decl)) {
return {};
}
// Function names should only appear in the name prefix in specific cases.
//
// 1. Declaration of a template parameter for a function or member function
// template:
// ```
// template <typename T>
// void foo(T bar);
// ```
// In this case, the Type entity for `T` should be qualified as
// `foo<typename T>()::T`
//
// 2. Declaration of a nested type/class/enum or a nested function:
// ```
// int foo() {
// class Bar {
// };
// }
// ```
// In this case, the Class entity for `Bar` should be qualified as
// `foo()::Bar`
//
// Technically, I think the return type should be included when functions are
// used as qualifiers, but since return type overloading is not allowed I
// don't think that this is necessary, so it is omitted at present.
//
// In practice this means that we want to include functions in fully qualified
// names for anything other than variable declarations.
bool include_function_scope = !llvm::isa<clang::VarDecl>(decl);
const auto* decl_context = decl->getNonTransparentDeclContext();
return GetNamePrefixForDeclContext(decl_context, ast_context,
include_function_scope);
}
bool IsIgnoredImplicitDecl(const clang::Decl* decl) {
// Don't index unreferenced implicit entities except implicit methods.
// (We opt to declare all the implicit methods with a preference to report
// e.g. an "implicitly defined" destructor over reporting it missing.)
return decl->isImplicit() && !llvm::isa<clang::CXXMethodDecl>(decl);
}
bool IsNotInherited(const clang::Decl* decl) {
if (decl->isImplicit() || llvm::isa<clang::CXXConstructorDecl>(decl) ||
llvm::isa<clang::CXXDestructorDecl>(decl)) {
return true;
}
// Assignment operators are not inherited.
if (const auto* function_decl = llvm::dyn_cast<clang::FunctionDecl>(decl)) {
if (function_decl->isOverloadedOperator() &&
function_decl->getOverloadedOperator() == clang::OO_Equal) {
return true;
}
}
return false;
}
using SeenNames = llvm::SmallSet<clang::DeclarationName, 32>;
void CollectPotentialMemberNamesFromAncestors(
const clang::CXXRecordDecl* class_decl, SeenNames& seen_names) {
class_decl = class_decl->getDefinition();
if (!class_decl) {
return;
}
for (const auto& base_spec : class_decl->bases()) {
if (const clang::CXXRecordDecl* base_decl =
base_spec.getType()->getAsCXXRecordDecl();
base_decl && (base_decl = base_decl->getDefinition())) {
// We are using `decls` instead of `fields` to also account for statics.
for (const auto* decl : base_decl->decls()) {
if (const auto* named_decl = llvm::dyn_cast<clang::NamedDecl>(decl)) {
const clang::DeclarationName& decl_name = named_decl->getDeclName();
if (decl_name.getAsString().empty()) {
continue;
}
if (!seen_names.contains(decl_name)) {
// Process all the members with this name (e.g. method overloads).
auto result = base_decl->lookup(named_decl->getDeclName());
for (const auto* found_decl : result) {
if (!IsNotInherited(found_decl)) {
seen_names.insert(decl_name);
break;
}
}
}
}
}
CollectPotentialMemberNamesFromAncestors(base_decl, seen_names);
}
}
}
bool IsCompleteClass(const clang::CXXRecordDecl* class_decl) {
// According to `Sema::LookupQualifiedName` constraints for a `TagDecl`.
return class_decl->isDependentContext() ||
class_decl->isCompleteDefinition() || class_decl->isBeingDefined();
}
template <typename Action>
void ForAllInheritedMembers(clang::Sema& sema,
const clang::CXXRecordDecl* class_decl,
Action&& action) {
CHECK_NE(class_decl, nullptr);
if (!IsCompleteClass(class_decl)) {
return;
}
SeenNames seen_names;
CollectPotentialMemberNamesFromAncestors(class_decl, seen_names);
for (const clang::DeclarationName& decl_name : seen_names) {
clang::LookupResult lookup_result(
sema, decl_name, {}, clang::Sema::LookupNameKind::LookupMemberName);
lookup_result.suppressDiagnostics();
// `LookupQualifiedName` requires a mutable context - in particular,
// implicit methods can be lazily defined in the process.
// However, the pattern of `const` usage there is awkward - at the time of
// writing, `LookupDirect` takes it as a `const` pointer, then passed to
// `DeclareImplicitMemberFunctionsWithName` which casts the `const` away...
auto* mutable_class_decl = const_cast<clang::CXXRecordDecl*>(class_decl);
sema.LookupQualifiedName(lookup_result, mutable_class_decl,
/*InUnqualifiedLookup=*/false);
if (!lookup_result.isSingleResult() &&
!lookup_result.isOverloadedResult()) {
// Ambiguous lookups that require qualification are not instantiated.
// However, qualified accesses (`A().B::x`) do count as references.
continue;
}
for (const auto decl : lookup_result) {
// Check that it is an inherited member and not one from the class itself.
if (decl->getNonTransparentDeclContext()->getPrimaryContext() ==
class_decl->getPrimaryContext()) {
continue;
}
action(decl);
}
}
}
void ReportTranslationUnit(llvm::raw_string_ostream& stream,
const clang::ASTContext& context) {
const clang::SourceManager& source_manager = context.getSourceManager();
clang::FileID main_file_id = source_manager.getMainFileID();
const clang::FileEntry* main_file_entry =
source_manager.getFileEntryForID(main_file_id);
if (main_file_entry) {
llvm::StringRef main_file_path = main_file_entry->tryGetRealPathName();
stream << "Translation unit: '" << main_file_path << "'\n";
}
}
std::string GetEnumValue(const clang::EnumConstantDecl* decl) {
const llvm::APSInt& value = decl->getInitVal();
std::string string_value;
llvm::raw_string_ostream stream(string_value);
stream << value;
return string_value;
}
// The mapping from (not necessarily immediate) base classes defining a method
// to their definitions thereof.
using DefiningSuperBasesToMethods =
llvm::SmallMapVector<const clang::CXXRecordDecl*,
const clang::CXXMethodDecl*, 16>;
template <typename EntityIdByDecl>
void AddVirtualMethodLinksImpl(
const clang::CXXMethodDecl* prototype_method_decl,
const clang::CXXRecordDecl* child_class_decl,
const DefiningSuperBasesToMethods& defining_super_bases_to_methods,
EntityId child_id, InMemoryIndex& index,
EntityIdByDecl&& get_entity_id_for_decl, const clang::ASTContext& context) {
llvm::SmallPtrSet<const clang::CXXRecordDecl*, 32> seen;
llvm::SmallVector<const clang::CXXRecordDecl*, 32> to_visit;
auto add_bases_to_visit = [&to_visit,
&seen](const clang::CXXRecordDecl* class_decl) {
for (const auto& base : class_decl->bases()) {
auto* base_cxx_record = base.getType()->getAsCXXRecordDecl();
if (!base_cxx_record) {
continue;
}
base_cxx_record = base_cxx_record->getDefinition();
if (!base_cxx_record) {
continue;
}
if (!seen.contains(base_cxx_record)) {
to_visit.push_back(base_cxx_record);
seen.insert(base_cxx_record);
}
}
};
add_bases_to_visit(child_class_decl);
while (!to_visit.empty()) {
const clang::CXXRecordDecl* base_cxx_record = to_visit.pop_back_val();
const auto it = defining_super_bases_to_methods.find(base_cxx_record);
if (it != defining_super_bases_to_methods.end()) {
// There is a definition in `base_cxx_record` we can link to.
const clang::CXXMethodDecl* overridden_method_decl = it->second;
EntityId parent_id = get_entity_id_for_decl(overridden_method_decl);
if (parent_id != kInvalidEntityId) {
(void)index.GetVirtualMethodLinkId({parent_id, child_id});
} else {
LOG(DFATAL) << "Parent of virtual method "
<< index.GetEntityById(child_id).full_name() << " in class "
<< base_cxx_record->getQualifiedNameAsString()
<< " is an invalid entity";
}
continue;
}
// `base_cxx_record` doesn't define this method directly.
for (const auto [defining_super_base, overridden_method_decl] :
defining_super_bases_to_methods) {
if (!base_cxx_record->isDerivedFrom(defining_super_base)) {
continue;
}
// Because it can be present in `base_cxx_record` only through inheritance
// (see above), check if it was synthesized there from
// `overridden_method_decl` in `defining_super_base`.
const EntityId inherited_id =
get_entity_id_for_decl(overridden_method_decl);
if (inherited_id == kInvalidEntityId) {
LOG(DFATAL) << "Parent of virtual method "
<< index.GetEntityById(child_id).full_name() << " in class "
<< defining_super_base->getQualifiedNameAsString()
<< " is an invalid entity";
continue;
}
const Entity& inherited_entity = index.GetEntityById(inherited_id);
const std::string new_name_prefix =
GetNamePrefixForDeclContext(base_cxx_record, context);
// Re-synthesize it to get the ID of the synthetic entity.
const EntityId parent_id = index.GetExistingEntityId(
Entity(inherited_entity, /*new_name_prefix=*/new_name_prefix,
/*inherited_entity_id=*/inherited_id));
if (parent_id == kInvalidEntityId) {
// No such synthetic entity, likely due to name resolution ambiguity in
// the base. Skip it and consider its immediate super-bases.
add_bases_to_visit(base_cxx_record);
} else {
(void)index.GetVirtualMethodLinkId({parent_id, child_id});
}
// We can't break here - can have multiple bases with this virtual method.
}
}
}
const clang::CXXRecordDecl* GetCXXRecordForType(const clang::QualType& type) {
clang::QualType derived_type = type;
if (const auto* pointer_type = type->getAs<clang::PointerType>()) {
derived_type = pointer_type->getPointeeType();
}
if (derived_type->isDependentType()) {
return nullptr;
}
const auto* record_type = derived_type->castAs<clang::RecordType>();
CHECK(record_type != nullptr);
const clang::RecordDecl* decl = record_type->getOriginalDecl();
CHECK(decl != nullptr);
return llvm::dyn_cast<clang::CXXRecordDecl>(decl);
}
} // namespace
bool AstVisitor::VisitCallExpr(const clang::CallExpr* expr) {
AddReferencesForExpr(expr);
return true;
}
bool AstVisitor::VisitCXXConstructExpr(const clang::CXXConstructExpr* expr) {
AddReferencesForExpr(expr);
return true;
}
bool AstVisitor::VisitCXXDeleteExpr(const clang::CXXDeleteExpr* expr) {
AddReferencesForExpr(expr);
return true;
}
bool AstVisitor::VisitCXXNewExpr(const clang::CXXNewExpr* expr) {
AddReferencesForExpr(expr);
return true;
}
bool AstVisitor::VisitDeclRefExpr(const clang::DeclRefExpr* expr) {
AddReferencesForExpr(expr);
return true;
}
bool AstVisitor::VisitEnumDecl(const clang::EnumDecl* decl) {
GetEntityIdForDecl(decl);
return true;
}
bool AstVisitor::VisitEnumConstantDecl(const clang::EnumConstantDecl* decl) {
GetEntityIdForDecl(decl);
return true;
}
bool AstVisitor::VisitFieldDecl(const clang::FieldDecl* decl) {
GetEntityIdForDecl(decl);
AddReferencesForDecl(decl);
return true;
}
bool AstVisitor::VisitFunctionDecl(const clang::FunctionDecl* decl) {
// We only need to add an entity for a FunctionDecl that is the definition,
// or if there is no definition in this translation unit, and we never add an
// entity for a deleted function.
if (decl->isDeleted()) {
return true;
}
if (IsADefinition(decl) || !decl->getDefinition()) {
GetEntityIdForDecl(decl);
AddReferencesForDecl(decl);
}
return true;
}
bool AstVisitor::VisitLambdaExpr(const clang::LambdaExpr* expr) {
GetEntityIdForDecl(expr->getCallOperator());
return true;
}
bool AstVisitor::VisitMemberExpr(const clang::MemberExpr* expr) {
AddReferencesForExpr(expr);
return true;
}
bool AstVisitor::VisitNonTypeTemplateParmDecl(
const clang::NonTypeTemplateParmDecl* decl) {
if (IsParentADefinition(decl)) {
GetEntityIdForDecl(decl);
}
return true;
}
bool AstVisitor::VisitRecordDecl(clang::RecordDecl* decl) {
if (auto* record_decl = llvm::dyn_cast<clang::CXXRecordDecl>(decl)) {
if (record_decl->isInjectedClassName()) {
// struct C {
// // C is implicitly declared here as a synonym for the class name.
// };
// C::C c; // same as "C c;"
// Only index `C` in this case, and don't index `C::C`.
return true;
}
if (IsADefinition(record_decl)) {
SynthesizeInheritedMemberEntities(record_decl);
}
// We opt to declare all the implicit members with a preference to report
// e.g. an "implicitly defined" destructor over reporting it missing.
sema_.ForceDeclarationOfImplicitMembers(record_decl);
}
// As for FunctionDecl, we only need to add an entity for a RecordDecl if this
// is the definition, or if there is no definition in this translation unit.
if (IsADefinition(decl) || !decl->getDefinition()) {
GetEntityIdForDecl(decl);
AddReferencesForDecl(decl);
}
return true;
}
void AstVisitor::SynthesizeInheritedMemberEntities(
const clang::CXXRecordDecl* class_decl) {
CHECK(IsADefinition(class_decl));
const std::string new_name_prefix = GetNamePrefixForDeclContext(
/*decl_context=*/class_decl, /*ast_context=*/context_);
ForAllInheritedMembers(sema_, class_decl, [&](const clang::Decl* decl) {
const EntityId inherited_id = GetEntityIdForDecl(decl);
if (inherited_id == kInvalidEntityId) {
return;
}
const Entity& inherited_entity = index_.GetEntityById(inherited_id);
const Entity synth_entity(inherited_entity,
/*new_name_prefix=*/new_name_prefix,
/*inherited_entity_id=*/inherited_id);
const EntityId synth_id = index_.GetEntityId(synth_entity);
if (inherited_entity.is_virtual_method()) {
AddSynthesizedVirtualMethodLinks(llvm::cast<clang::CXXMethodDecl>(decl),
class_decl, synth_id);
}
});
}
bool AstVisitor::VisitTemplateTypeParmDecl(