clang 17.0.0git
IndexingContext.cpp
Go to the documentation of this file.
1//===- IndexingContext.cpp - Indexing context data ------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
9#include "IndexingContext.h"
11#include "clang/AST/Attr.h"
12#include "clang/AST/DeclObjC.h"
17
18using namespace clang;
19using namespace index;
20
21static bool isGeneratedDecl(const Decl *D) {
22 if (auto *attr = D->getAttr<ExternalSourceSymbolAttr>()) {
23 return attr->getGeneratedDeclaration();
24 }
25 return false;
26}
27
29 return !isGeneratedDecl(D);
30}
31
33 return Ctx->getLangOpts();
34}
35
37 return IndexOpts.IndexFunctionLocals;
38}
39
41 return IndexOpts.IndexImplicitInstantiation;
42}
43
45 return IndexOpts.IndexParametersInDeclarations;
46}
47
49 return IndexOpts.IndexTemplateParameters;
50}
51
53 SymbolRoleSet Roles,
54 ArrayRef<SymbolRelation> Relations) {
55 return handleDecl(D, D->getLocation(), Roles, Relations);
56}
57
59 SymbolRoleSet Roles,
61 const DeclContext *DC) {
62 if (!DC)
63 DC = D->getDeclContext();
64
65 const Decl *OrigD = D;
66 if (isa<ObjCPropertyImplDecl>(D)) {
67 D = cast<ObjCPropertyImplDecl>(D)->getPropertyDecl();
68 }
69 return handleDeclOccurrence(D, Loc, /*IsRef=*/false, cast<Decl>(DC),
70 Roles, Relations,
71 nullptr, OrigD, DC);
72}
73
75 const NamedDecl *Parent,
76 const DeclContext *DC,
77 SymbolRoleSet Roles,
79 const Expr *RefE,
80 const Decl *RefD) {
82 return true;
83
85 (isa<NonTypeTemplateParmDecl>(D) || isa<TemplateTypeParmDecl>(D) ||
86 isa<TemplateTemplateParmDecl>(D))) {
87 return true;
88 }
89 return handleDeclOccurrence(D, Loc, /*IsRef=*/true, Parent, Roles, Relations,
90 RefE, RefD, DC);
91}
92
93static void reportModuleReferences(const Module *Mod,
95 const ImportDecl *ImportD,
96 IndexDataConsumer &DataConsumer) {
97 if (!Mod)
98 return;
99 reportModuleReferences(Mod->Parent, IdLocs.drop_back(), ImportD,
100 DataConsumer);
101 DataConsumer.handleModuleOccurrence(
102 ImportD, Mod, (SymbolRoleSet)SymbolRole::Reference, IdLocs.back());
103}
104
106 if (ImportD->isInvalidDecl())
107 return true;
108
109 SourceLocation Loc;
110 auto IdLocs = ImportD->getIdentifierLocs();
111 if (!IdLocs.empty())
112 Loc = IdLocs.back();
113 else
114 Loc = ImportD->getLocation();
115
117 FileID FID = SM.getFileID(SM.getFileLoc(Loc));
118 if (FID.isInvalid())
119 return true;
120
121 bool Invalid = false;
122 const SrcMgr::SLocEntry &SEntry = SM.getSLocEntry(FID, &Invalid);
123 if (Invalid || !SEntry.isFile())
124 return true;
125
126 if (SEntry.getFile().getFileCharacteristic() != SrcMgr::C_User) {
127 switch (IndexOpts.SystemSymbolFilter) {
129 return true;
132 break;
133 }
134 }
135
136 const Module *Mod = ImportD->getImportedModule();
137 if (!ImportD->isImplicit() && Mod->Parent && !IdLocs.empty()) {
138 reportModuleReferences(Mod->Parent, IdLocs.drop_back(), ImportD,
139 DataConsumer);
140 }
141
143 if (ImportD->isImplicit())
144 Roles |= (unsigned)SymbolRole::Implicit;
145
146 return DataConsumer.handleModuleOccurrence(ImportD, Mod, Roles, Loc);
147}
148
152 SD = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
153 TKind = SD->getSpecializationKind();
154 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
155 TKind = FD->getTemplateSpecializationKind();
156 } else if (auto *VD = dyn_cast<VarDecl>(D)) {
157 TKind = VD->getTemplateSpecializationKind();
158 } else if (const auto *RD = dyn_cast<CXXRecordDecl>(D)) {
159 if (RD->getInstantiatedFromMemberClass())
160 TKind = RD->getTemplateSpecializationKind();
161 } else if (const auto *ED = dyn_cast<EnumDecl>(D)) {
162 if (ED->getInstantiatedFromMemberEnum())
163 TKind = ED->getTemplateSpecializationKind();
164 } else if (isa<FieldDecl>(D) || isa<TypedefNameDecl>(D) ||
165 isa<EnumConstantDecl>(D)) {
166 if (const auto *Parent = dyn_cast<Decl>(D->getDeclContext()))
168 }
169 switch (TKind) {
170 case TSK_Undeclared:
171 // Instantiation maybe not happen yet when we see a SpecializationDecl,
172 // e.g. when the type doesn't need to be complete, we still treat it as an
173 // instantiation as we'd like to keep the canonicalized result consistent.
174 return isa<ClassTemplateSpecializationDecl>(D);
176 return false;
180 return true;
181 }
182 llvm_unreachable("invalid TemplateSpecializationKind");
183}
184
185bool IndexingContext::shouldIgnoreIfImplicit(const Decl *D) {
186 if (isa<ObjCInterfaceDecl>(D))
187 return false;
188 if (isa<ObjCCategoryDecl>(D))
189 return false;
190 if (isa<ObjCIvarDecl>(D))
191 return false;
192 if (isa<ObjCMethodDecl>(D))
193 return false;
194 if (isa<ImportDecl>(D))
195 return false;
196 return true;
197}
198
199static const CXXRecordDecl *
201 if (const auto *CTSD =
202 dyn_cast<ClassTemplateSpecializationDecl>(D->getDeclContext()))
203 return CTSD->getTemplateInstantiationPattern();
204 else if (const auto *RD = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
206 return nullptr;
207}
208
211 SD = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
212 const auto *Template = SD->getTemplateInstantiationPattern();
213 if (Template)
214 return Template;
215 // Fallback to primary template if no instantiation is available yet (e.g.
216 // the type doesn't need to be complete).
217 return SD->getSpecializedTemplate()->getTemplatedDecl();
218 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
219 return FD->getTemplateInstantiationPattern();
220 } else if (auto *VD = dyn_cast<VarDecl>(D)) {
221 return VD->getTemplateInstantiationPattern();
222 } else if (const auto *RD = dyn_cast<CXXRecordDecl>(D)) {
223 return RD->getInstantiatedFromMemberClass();
224 } else if (const auto *ED = dyn_cast<EnumDecl>(D)) {
225 return ED->getInstantiatedFromMemberEnum();
226 } else if (isa<FieldDecl>(D) || isa<TypedefNameDecl>(D)) {
227 const auto *ND = cast<NamedDecl>(D);
228 if (const CXXRecordDecl *Pattern =
230 for (const NamedDecl *BaseND : Pattern->lookup(ND->getDeclName())) {
231 if (BaseND->isImplicit())
232 continue;
233 if (BaseND->getKind() == ND->getKind())
234 return BaseND;
235 }
236 }
237 } else if (const auto *ECD = dyn_cast<EnumConstantDecl>(D)) {
238 if (const auto *ED = dyn_cast<EnumDecl>(ECD->getDeclContext())) {
239 if (const EnumDecl *Pattern = ED->getInstantiatedFromMemberEnum()) {
240 for (const NamedDecl *BaseECD : Pattern->lookup(ECD->getDeclName()))
241 return BaseECD;
242 }
243 }
244 }
245 return nullptr;
246}
247
248static bool isDeclADefinition(const Decl *D, const DeclContext *ContainerDC, ASTContext &Ctx) {
249 if (auto VD = dyn_cast<VarDecl>(D))
250 return VD->isThisDeclarationADefinition(Ctx);
251
252 if (auto FD = dyn_cast<FunctionDecl>(D))
253 return FD->isThisDeclarationADefinition();
254
255 if (auto TD = dyn_cast<TagDecl>(D))
256 return TD->isThisDeclarationADefinition();
257
258 if (auto MD = dyn_cast<ObjCMethodDecl>(D))
259 return MD->isThisDeclarationADefinition() || isa<ObjCImplDecl>(ContainerDC);
260
261 if (isa<TypedefNameDecl>(D) || isa<EnumConstantDecl>(D) ||
262 isa<FieldDecl>(D) || isa<MSPropertyDecl>(D) || isa<ObjCImplDecl>(D) ||
263 isa<ObjCPropertyImplDecl>(D) || isa<ConceptDecl>(D))
264 return true;
265
266 return false;
267}
268
269/// Whether the given NamedDecl should be skipped because it has no name.
270static bool shouldSkipNamelessDecl(const NamedDecl *ND) {
271 return (ND->getDeclName().isEmpty() && !isa<TagDecl>(ND) &&
272 !isa<ObjCCategoryDecl>(ND)) || isa<CXXDeductionGuideDecl>(ND);
273}
274
275static const Decl *adjustParent(const Decl *Parent) {
276 if (!Parent)
277 return nullptr;
278 for (;; Parent = cast<Decl>(Parent->getDeclContext())) {
279 if (isa<TranslationUnitDecl>(Parent))
280 return nullptr;
281 if (isa<LinkageSpecDecl>(Parent) || isa<BlockDecl>(Parent))
282 continue;
283 if (auto NS = dyn_cast<NamespaceDecl>(Parent)) {
284 if (NS->isAnonymousNamespace())
285 continue;
286 } else if (auto RD = dyn_cast<RecordDecl>(Parent)) {
287 if (RD->isAnonymousStructOrUnion())
288 continue;
289 } else if (auto ND = dyn_cast<NamedDecl>(Parent)) {
291 continue;
292 }
293 return Parent;
294 }
295}
296
297static const Decl *getCanonicalDecl(const Decl *D) {
298 D = D->getCanonicalDecl();
299 if (auto TD = dyn_cast<TemplateDecl>(D)) {
300 if (auto TTD = TD->getTemplatedDecl()) {
301 D = TTD;
302 assert(D->isCanonicalDecl());
303 }
304 }
305
306 return D;
307}
308
310 bool IsRef, SymbolRoleSet Roles, ArrayRef<SymbolRelation> Relations) {
311 if (!IsRef)
312 return true;
313
314 auto acceptForRelation = [](SymbolRoleSet roles) -> bool {
315 bool accept = false;
316 applyForEachSymbolRoleInterruptible(roles, [&accept](SymbolRole r) -> bool {
317 switch (r) {
324 accept = true;
325 return false;
329 case SymbolRole::Read:
331 case SymbolRole::Call:
341 return true;
342 }
343 llvm_unreachable("Unsupported SymbolRole value!");
344 });
345 return accept;
346 };
347
348 for (auto &Rel : Relations) {
349 if (acceptForRelation(Rel.Roles))
350 return true;
351 }
352
353 return false;
354}
355
356bool IndexingContext::handleDeclOccurrence(const Decl *D, SourceLocation Loc,
357 bool IsRef, const Decl *Parent,
358 SymbolRoleSet Roles,
359 ArrayRef<SymbolRelation> Relations,
360 const Expr *OrigE,
361 const Decl *OrigD,
362 const DeclContext *ContainerDC) {
363 if (D->isImplicit() && !isa<ObjCMethodDecl>(D))
364 return true;
365 if (!isa<NamedDecl>(D) || shouldSkipNamelessDecl(cast<NamedDecl>(D)))
366 return true;
367
369 FileID FID = SM.getFileID(SM.getFileLoc(Loc));
370 if (FID.isInvalid())
371 return true;
372
373 bool Invalid = false;
374 const SrcMgr::SLocEntry &SEntry = SM.getSLocEntry(FID, &Invalid);
375 if (Invalid || !SEntry.isFile())
376 return true;
377
378 if (SEntry.getFile().getFileCharacteristic() != SrcMgr::C_User) {
379 switch (IndexOpts.SystemSymbolFilter) {
381 return true;
383 if (!shouldReportOccurrenceForSystemDeclOnlyMode(IsRef, Roles, Relations))
384 return true;
385 break;
387 break;
388 }
389 }
390
391 if (!OrigD)
392 OrigD = D;
393
395 if (!IsRef)
396 return true;
398 if (!D)
399 return true;
401 }
402
403 if (IsRef)
405 else if (isDeclADefinition(OrigD, ContainerDC, *Ctx))
406 Roles |= (unsigned)SymbolRole::Definition;
407 else
409
410 D = getCanonicalDecl(D);
412 if (Parent)
414
415 SmallVector<SymbolRelation, 6> FinalRelations;
416 FinalRelations.reserve(Relations.size()+1);
417
418 auto addRelation = [&](SymbolRelation Rel) {
419 auto It = llvm::find_if(FinalRelations, [&](SymbolRelation Elem) -> bool {
420 return Elem.RelatedSymbol == Rel.RelatedSymbol;
421 });
422 if (It != FinalRelations.end()) {
423 It->Roles |= Rel.Roles;
424 } else {
425 FinalRelations.push_back(Rel);
426 }
427 Roles |= Rel.Roles;
428 };
429
430 if (Parent) {
431 if (IsRef || (!isa<ParmVarDecl>(D) && isFunctionLocalSymbol(D))) {
432 addRelation(SymbolRelation{
434 Parent
435 });
436 } else {
437 addRelation(SymbolRelation{
439 Parent
440 });
441 }
442 }
443
444 for (auto &Rel : Relations) {
445 addRelation(SymbolRelation(Rel.Roles,
446 Rel.RelatedSymbol->getCanonicalDecl()));
447 }
448
449 IndexDataConsumer::ASTNodeInfo Node{OrigE, OrigD, Parent, ContainerDC};
450 return DataConsumer.handleDeclOccurrence(D, Roles, FinalRelations, Loc, Node);
451}
452
454 SourceLocation Loc,
455 const MacroInfo &MI) {
456 if (!shouldIndexMacroOccurrence(/*IsRef=*/false, Loc))
457 return;
459 DataConsumer.handleMacroOccurrence(&Name, &MI, Roles, Loc);
460}
461
463 SourceLocation Loc,
464 const MacroInfo &MI) {
465 if (!shouldIndexMacroOccurrence(/*IsRef=*/false, Loc))
466 return;
468 DataConsumer.handleMacroOccurrence(&Name, &MI, Roles, Loc);
469}
470
472 SourceLocation Loc,
473 const MacroInfo &MI) {
474 if (!shouldIndexMacroOccurrence(/*IsRef=*/true, Loc))
475 return;
477 DataConsumer.handleMacroOccurrence(&Name, &MI, Roles, Loc);
478}
479
480bool IndexingContext::shouldIndexMacroOccurrence(bool IsRef,
481 SourceLocation Loc) {
482 if (!IndexOpts.IndexMacros)
483 return false;
484
485 switch (IndexOpts.SystemSymbolFilter) {
487 break;
489 if (!IsRef)
490 return true;
491 break;
493 return true;
494 }
495
497 FileID FID = SM.getFileID(SM.getFileLoc(Loc));
498 if (FID.isInvalid())
499 return false;
500
501 bool Invalid = false;
502 const SrcMgr::SLocEntry &SEntry = SM.getSLocEntry(FID, &Invalid);
503 if (Invalid || !SEntry.isFile())
504 return false;
505
506 return SEntry.getFile().getFileCharacteristic() == SrcMgr::C_User;
507}
Defines the clang::ASTContext interface.
NodeId Parent
Definition: ASTDiff.cpp:191
DynTypedNode Node
#define SM(sm)
Definition: Cuda.cpp:78
Defines the C++ template declaration subclasses.
static bool shouldSkipNamelessDecl(const NamedDecl *ND)
Whether the given NamedDecl should be skipped because it has no name.
static const Decl * adjustParent(const Decl *Parent)
static void reportModuleReferences(const Module *Mod, ArrayRef< SourceLocation > IdLocs, const ImportDecl *ImportD, IndexDataConsumer &DataConsumer)
static bool isGeneratedDecl(const Decl *D)
static bool isDeclADefinition(const Decl *D, const DeclContext *ContainerDC, ASTContext &Ctx)
static bool shouldReportOccurrenceForSystemDeclOnlyMode(bool IsRef, SymbolRoleSet Roles, ArrayRef< SymbolRelation > Relations)
static const Decl * adjustTemplateImplicitInstantiation(const Decl *D)
static const CXXRecordDecl * getDeclContextForTemplateInstationPattern(const Decl *D)
static const Decl * getCanonicalDecl(const Decl *D)
Defines the clang::SourceLocation class and associated facilities.
Defines the SourceManager interface.
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:182
SourceManager & getSourceManager()
Definition: ASTContext.h:692
const LangOptions & getLangOpts() const
Definition: ASTContext.h:762
Represents a C++ struct/union/class.
Definition: DeclCXX.h:254
CXXRecordDecl * getInstantiatedFromMemberClass() const
If this record is an instantiation of a member class, retrieves the member class from which it was in...
Definition: DeclCXX.cpp:1832
const CXXRecordDecl * getTemplateInstantiationPattern() const
Retrieve the record declaration from which this record could be instantiated.
Definition: DeclCXX.cpp:1886
Represents a class template specialization, which refers to a class template with a given set of temp...
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1393
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:83
T * getAttr() const
Definition: DeclBase.h:556
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition: DeclBase.h:576
bool isCanonicalDecl() const
Whether this particular Decl is a canonical one.
Definition: DeclBase.h:949
bool isInvalidDecl() const
Definition: DeclBase.h:571
SourceLocation getLocation() const
Definition: DeclBase.h:432
DeclContext * getDeclContext()
Definition: DeclBase.h:441
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclBase.h:943
bool isEmpty() const
Evaluates true when this declaration name is empty.
Represents an enum.
Definition: Decl.h:3720
EnumDecl * getInstantiatedFromMemberEnum() const
Returns the enumeration (declared within the template) from which this enumeration type was instantia...
Definition: Decl.cpp:4653
This represents one expression.
Definition: Expr.h:110
An opaque identifier used by SourceManager which refers to a source file (MemoryBuffer) along with it...
bool isInvalid() const
Represents a function declaration or definition.
Definition: Decl.h:1917
One of these records is kept for each identifier that is lexed.
Describes a module import declaration, which makes the contents of the named module visible in the cu...
Definition: Decl.h:4639
ArrayRef< SourceLocation > getIdentifierLocs() const
Retrieves the locations of each of the identifiers that make up the complete module name in the impor...
Definition: Decl.cpp:5409
Module * getImportedModule() const
Retrieve the module that was imported by the import declaration.
Definition: Decl.h:4697
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:82
Encapsulates the data about a macro definition (e.g.
Definition: MacroInfo.h:39
Describes a module or submodule.
Definition: Module.h:98
Module * Parent
The parent of this module.
Definition: Module.h:147
This represents a decl that may have a name.
Definition: Decl.h:247
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition: Decl.h:313
Encodes a location in the source.
This class handles loading and caching of source files into memory.
CharacteristicKind getFileCharacteristic() const
Return whether this is a system header or not.
This is a discriminated union of FileInfo and ExpansionInfo.
const FileInfo & getFile() const
virtual bool handleDeclOccurrence(const Decl *D, SymbolRoleSet Roles, ArrayRef< SymbolRelation > Relations, SourceLocation Loc, ASTNodeInfo ASTNode)
virtual bool handleMacroOccurrence(const IdentifierInfo *Name, const MacroInfo *MI, SymbolRoleSet Roles, SourceLocation Loc)
virtual bool handleModuleOccurrence(const ImportDecl *ImportD, const Module *Mod, SymbolRoleSet Roles, SourceLocation Loc)
bool shouldIndexImplicitInstantiation() const
bool importedModule(const ImportDecl *ImportD)
bool shouldIndex(const Decl *D)
bool shouldIndexFunctionLocalSymbols() const
void handleMacroReference(const IdentifierInfo &Name, SourceLocation Loc, const MacroInfo &MD)
bool shouldIndexParametersInDeclarations() const
void handleMacroUndefined(const IdentifierInfo &Name, SourceLocation Loc, const MacroInfo &MI)
static bool isTemplateImplicitInstantiation(const Decl *D)
const LangOptions & getLangOpts() const
void handleMacroDefined(const IdentifierInfo &Name, SourceLocation Loc, const MacroInfo &MI)
bool handleReference(const NamedDecl *D, SourceLocation Loc, const NamedDecl *Parent, const DeclContext *DC, SymbolRoleSet Roles=SymbolRoleSet(), ArrayRef< SymbolRelation > Relations=std::nullopt, const Expr *RefE=nullptr, const Decl *RefD=nullptr)
bool handleDecl(const Decl *D, SymbolRoleSet Roles=SymbolRoleSet(), ArrayRef< SymbolRelation > Relations=std::nullopt)
const internal::VariadicAllOfMatcher< Attr > attr
Matches attributes.
SymbolRole
Set of roles that are attributed to symbol occurrences.
Definition: IndexSymbol.h:102
bool isFunctionLocalSymbol(const Decl *D)
Definition: IndexSymbol.cpp:53
bool applyForEachSymbolRoleInterruptible(SymbolRoleSet Roles, llvm::function_ref< bool(SymbolRole)> Fn)
TemplateSpecializationKind
Describes the kind of template specialization that a particular template specialization declaration r...
Definition: Specifiers.h:176
@ TSK_ExplicitInstantiationDefinition
This template specialization was instantiated from a template due to an explicit instantiation defini...
Definition: Specifiers.h:194
@ TSK_ExplicitInstantiationDeclaration
This template specialization was instantiated from a template due to an explicit instantiation declar...
Definition: Specifiers.h:190
@ TSK_ExplicitSpecialization
This template specialization was declared or defined by an explicit specialization (C++ [temp....
Definition: Specifiers.h:186
@ TSK_ImplicitInstantiation
This template specialization was implicitly instantiated from a template.
Definition: Specifiers.h:182
@ TSK_Undeclared
This template specialization was formed from a template-id but has not yet been declared,...
Definition: Specifiers.h:179
SystemSymbolFilterKind SystemSymbolFilter
Represents a relation to another symbol for a symbol occurrence.
Definition: IndexSymbol.h:136