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"
10 #include "clang/AST/ASTContext.h"
11 #include "clang/AST/Attr.h"
12 #include "clang/AST/DeclObjC.h"
13 #include "clang/AST/DeclTemplate.h"
14 #include "clang/Basic/SourceLocation.h"
15 #include "clang/Basic/SourceManager.h"
16 #include "clang/Index/IndexDataConsumer.h"
17 
18 using namespace clang;
19 using namespace index;
20 
21 static bool isGeneratedDecl(const Decl *D) {
22   if (auto *attr = D->getAttr<ExternalSourceSymbolAttr>()) {
23     return attr->getGeneratedDeclaration();
24   }
25   return false;
26 }
27 
28 bool IndexingContext::shouldIndex(const Decl *D) {
29   return !isGeneratedDecl(D);
30 }
31 
32 const LangOptions &IndexingContext::getLangOpts() const {
33   return Ctx->getLangOpts();
34 }
35 
36 bool IndexingContext::shouldIndexFunctionLocalSymbols() const {
37   return IndexOpts.IndexFunctionLocals;
38 }
39 
40 bool IndexingContext::shouldIndexImplicitInstantiation() const {
41   return IndexOpts.IndexImplicitInstantiation;
42 }
43 
44 bool IndexingContext::shouldIndexParametersInDeclarations() const {
45   return IndexOpts.IndexParametersInDeclarations;
46 }
47 
48 bool IndexingContext::shouldIndexTemplateParameters() const {
49   return IndexOpts.IndexTemplateParameters;
50 }
51 
52 bool IndexingContext::handleDecl(const Decl *D,
53                                  SymbolRoleSet Roles,
54                                  ArrayRef<SymbolRelation> Relations) {
55   return handleDecl(D, D->getLocation(), Roles, Relations);
56 }
57 
58 bool IndexingContext::handleDecl(const Decl *D, SourceLocation Loc,
59                                  SymbolRoleSet Roles,
60                                  ArrayRef<SymbolRelation> Relations,
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 
74 bool IndexingContext::handleReference(const NamedDecl *D, SourceLocation Loc,
75                                       const NamedDecl *Parent,
76                                       const DeclContext *DC,
77                                       SymbolRoleSet Roles,
78                                       ArrayRef<SymbolRelation> Relations,
79                                       const Expr *RefE,
80                                       const Decl *RefD) {
81   if (!shouldIndexFunctionLocalSymbols() && isFunctionLocalSymbol(D))
82     return true;
83 
84   if (!shouldIndexTemplateParameters() &&
85       (isa<NonTypeTemplateParmDecl>(D) || isa<TemplateTypeParmDecl>(D) ||
86        isa<TemplateTemplateParmDecl>(D))) {
87     return true;
88   }
89 
90   return handleDeclOccurrence(D, Loc, /*IsRef=*/true, Parent, Roles, Relations,
91                               RefE, RefD, DC);
92 }
93 
94 static void reportModuleReferences(const Module *Mod,
95                                    ArrayRef<SourceLocation> IdLocs,
96                                    const ImportDecl *ImportD,
97                                    IndexDataConsumer &DataConsumer) {
98   if (!Mod)
99     return;
100   reportModuleReferences(Mod->Parent, IdLocs.drop_back(), ImportD,
101                          DataConsumer);
102   DataConsumer.handleModuleOccurence(ImportD, Mod,
103                                      (SymbolRoleSet)SymbolRole::Reference,
104                                      IdLocs.back());
105 }
106 
107 bool IndexingContext::importedModule(const ImportDecl *ImportD) {
108   if (ImportD->isInvalidDecl())
109     return true;
110 
111   SourceLocation Loc;
112   auto IdLocs = ImportD->getIdentifierLocs();
113   if (!IdLocs.empty())
114     Loc = IdLocs.back();
115   else
116     Loc = ImportD->getLocation();
117 
118   SourceManager &SM = Ctx->getSourceManager();
119   FileID FID = SM.getFileID(SM.getFileLoc(Loc));
120   if (FID.isInvalid())
121     return true;
122 
123   bool Invalid = false;
124   const SrcMgr::SLocEntry &SEntry = SM.getSLocEntry(FID, &Invalid);
125   if (Invalid || !SEntry.isFile())
126     return true;
127 
128   if (SEntry.getFile().getFileCharacteristic() != SrcMgr::C_User) {
129     switch (IndexOpts.SystemSymbolFilter) {
130     case IndexingOptions::SystemSymbolFilterKind::None:
131       return true;
132     case IndexingOptions::SystemSymbolFilterKind::DeclarationsOnly:
133     case IndexingOptions::SystemSymbolFilterKind::All:
134       break;
135     }
136   }
137 
138   const Module *Mod = ImportD->getImportedModule();
139   if (!ImportD->isImplicit() && Mod->Parent && !IdLocs.empty()) {
140     reportModuleReferences(Mod->Parent, IdLocs.drop_back(), ImportD,
141                            DataConsumer);
142   }
143 
144   SymbolRoleSet Roles = (unsigned)SymbolRole::Declaration;
145   if (ImportD->isImplicit())
146     Roles |= (unsigned)SymbolRole::Implicit;
147 
148   return DataConsumer.handleModuleOccurence(ImportD, Mod, Roles, Loc);
149 }
150 
151 bool IndexingContext::isTemplateImplicitInstantiation(const Decl *D) {
152   TemplateSpecializationKind TKind = TSK_Undeclared;
153   if (const ClassTemplateSpecializationDecl *
154       SD = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
155     TKind = SD->getSpecializationKind();
156   } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
157     TKind = FD->getTemplateSpecializationKind();
158   } else if (auto *VD = dyn_cast<VarDecl>(D)) {
159     TKind = VD->getTemplateSpecializationKind();
160   } else if (const auto *RD = dyn_cast<CXXRecordDecl>(D)) {
161     if (RD->getInstantiatedFromMemberClass())
162       TKind = RD->getTemplateSpecializationKind();
163   } else if (const auto *ED = dyn_cast<EnumDecl>(D)) {
164     if (ED->getInstantiatedFromMemberEnum())
165       TKind = ED->getTemplateSpecializationKind();
166   } else if (isa<FieldDecl>(D) || isa<TypedefNameDecl>(D) ||
167              isa<EnumConstantDecl>(D)) {
168     if (const auto *Parent = dyn_cast<Decl>(D->getDeclContext()))
169       return isTemplateImplicitInstantiation(Parent);
170   }
171   switch (TKind) {
172     case TSK_Undeclared:
173     case TSK_ExplicitSpecialization:
174       return false;
175     case TSK_ImplicitInstantiation:
176     case TSK_ExplicitInstantiationDeclaration:
177     case TSK_ExplicitInstantiationDefinition:
178       return true;
179   }
180   llvm_unreachable("invalid TemplateSpecializationKind");
181 }
182 
183 bool IndexingContext::shouldIgnoreIfImplicit(const Decl *D) {
184   if (isa<ObjCInterfaceDecl>(D))
185     return false;
186   if (isa<ObjCCategoryDecl>(D))
187     return false;
188   if (isa<ObjCIvarDecl>(D))
189     return false;
190   if (isa<ObjCMethodDecl>(D))
191     return false;
192   if (isa<ImportDecl>(D))
193     return false;
194   return true;
195 }
196 
197 static const CXXRecordDecl *
198 getDeclContextForTemplateInstationPattern(const Decl *D) {
199   if (const auto *CTSD =
200           dyn_cast<ClassTemplateSpecializationDecl>(D->getDeclContext()))
201     return CTSD->getTemplateInstantiationPattern();
202   else if (const auto *RD = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
203     return RD->getInstantiatedFromMemberClass();
204   return nullptr;
205 }
206 
207 static const Decl *adjustTemplateImplicitInstantiation(const Decl *D) {
208   if (const ClassTemplateSpecializationDecl *
209       SD = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
210     return SD->getTemplateInstantiationPattern();
211   } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
212     return FD->getTemplateInstantiationPattern();
213   } else if (auto *VD = dyn_cast<VarDecl>(D)) {
214     return VD->getTemplateInstantiationPattern();
215   } else if (const auto *RD = dyn_cast<CXXRecordDecl>(D)) {
216     return RD->getInstantiatedFromMemberClass();
217   } else if (const auto *ED = dyn_cast<EnumDecl>(D)) {
218     return ED->getInstantiatedFromMemberEnum();
219   } else if (isa<FieldDecl>(D) || isa<TypedefNameDecl>(D)) {
220     const auto *ND = cast<NamedDecl>(D);
221     if (const CXXRecordDecl *Pattern =
222             getDeclContextForTemplateInstationPattern(ND)) {
223       for (const NamedDecl *BaseND : Pattern->lookup(ND->getDeclName())) {
224         if (BaseND->isImplicit())
225           continue;
226         if (BaseND->getKind() == ND->getKind())
227           return BaseND;
228       }
229     }
230   } else if (const auto *ECD = dyn_cast<EnumConstantDecl>(D)) {
231     if (const auto *ED = dyn_cast<EnumDecl>(ECD->getDeclContext())) {
232       if (const EnumDecl *Pattern = ED->getInstantiatedFromMemberEnum()) {
233         for (const NamedDecl *BaseECD : Pattern->lookup(ECD->getDeclName()))
234           return BaseECD;
235       }
236     }
237   }
238   return nullptr;
239 }
240 
241 static bool isDeclADefinition(const Decl *D, const DeclContext *ContainerDC, ASTContext &Ctx) {
242   if (auto VD = dyn_cast<VarDecl>(D))
243     return VD->isThisDeclarationADefinition(Ctx);
244 
245   if (auto FD = dyn_cast<FunctionDecl>(D))
246     return FD->isThisDeclarationADefinition();
247 
248   if (auto TD = dyn_cast<TagDecl>(D))
249     return TD->isThisDeclarationADefinition();
250 
251   if (auto MD = dyn_cast<ObjCMethodDecl>(D))
252     return MD->isThisDeclarationADefinition() || isa<ObjCImplDecl>(ContainerDC);
253 
254   if (isa<TypedefNameDecl>(D) ||
255       isa<EnumConstantDecl>(D) ||
256       isa<FieldDecl>(D) ||
257       isa<MSPropertyDecl>(D) ||
258       isa<ObjCImplDecl>(D) ||
259       isa<ObjCPropertyImplDecl>(D))
260     return true;
261 
262   return false;
263 }
264 
265 /// Whether the given NamedDecl should be skipped because it has no name.
266 static bool shouldSkipNamelessDecl(const NamedDecl *ND) {
267   return (ND->getDeclName().isEmpty() && !isa<TagDecl>(ND) &&
268           !isa<ObjCCategoryDecl>(ND)) || isa<CXXDeductionGuideDecl>(ND);
269 }
270 
271 static const Decl *adjustParent(const Decl *Parent) {
272   if (!Parent)
273     return nullptr;
274   for (;; Parent = cast<Decl>(Parent->getDeclContext())) {
275     if (isa<TranslationUnitDecl>(Parent))
276       return nullptr;
277     if (isa<LinkageSpecDecl>(Parent) || isa<BlockDecl>(Parent))
278       continue;
279     if (auto NS = dyn_cast<NamespaceDecl>(Parent)) {
280       if (NS->isAnonymousNamespace())
281         continue;
282     } else if (auto RD = dyn_cast<RecordDecl>(Parent)) {
283       if (RD->isAnonymousStructOrUnion())
284         continue;
285     } else if (auto ND = dyn_cast<NamedDecl>(Parent)) {
286       if (shouldSkipNamelessDecl(ND))
287         continue;
288     }
289     return Parent;
290   }
291 }
292 
293 static const Decl *getCanonicalDecl(const Decl *D) {
294   D = D->getCanonicalDecl();
295   if (auto TD = dyn_cast<TemplateDecl>(D)) {
296     if (auto TTD = TD->getTemplatedDecl()) {
297       D = TTD;
298       assert(D->isCanonicalDecl());
299     }
300   }
301 
302   return D;
303 }
304 
305 static bool shouldReportOccurrenceForSystemDeclOnlyMode(
306     bool IsRef, SymbolRoleSet Roles, ArrayRef<SymbolRelation> Relations) {
307   if (!IsRef)
308     return true;
309 
310   auto acceptForRelation = [](SymbolRoleSet roles) -> bool {
311     bool accept = false;
312     applyForEachSymbolRoleInterruptible(roles, [&accept](SymbolRole r) -> bool {
313       switch (r) {
314       case SymbolRole::RelationChildOf:
315       case SymbolRole::RelationBaseOf:
316       case SymbolRole::RelationOverrideOf:
317       case SymbolRole::RelationExtendedBy:
318       case SymbolRole::RelationAccessorOf:
319       case SymbolRole::RelationIBTypeOf:
320         accept = true;
321         return false;
322       case SymbolRole::Declaration:
323       case SymbolRole::Definition:
324       case SymbolRole::Reference:
325       case SymbolRole::Read:
326       case SymbolRole::Write:
327       case SymbolRole::Call:
328       case SymbolRole::Dynamic:
329       case SymbolRole::AddressOf:
330       case SymbolRole::Implicit:
331       case SymbolRole::Undefinition:
332       case SymbolRole::RelationReceivedBy:
333       case SymbolRole::RelationCalledBy:
334       case SymbolRole::RelationContainedBy:
335       case SymbolRole::RelationSpecializationOf:
336       case SymbolRole::NameReference:
337         return true;
338       }
339       llvm_unreachable("Unsupported SymbolRole value!");
340     });
341     return accept;
342   };
343 
344   for (auto &Rel : Relations) {
345     if (acceptForRelation(Rel.Roles))
346       return true;
347   }
348 
349   return false;
350 }
351 
352 bool IndexingContext::handleDeclOccurrence(const Decl *D, SourceLocation Loc,
353                                            bool IsRef, const Decl *Parent,
354                                            SymbolRoleSet Roles,
355                                            ArrayRef<SymbolRelation> Relations,
356                                            const Expr *OrigE,
357                                            const Decl *OrigD,
358                                            const DeclContext *ContainerDC) {
359   if (D->isImplicit() && !isa<ObjCMethodDecl>(D))
360     return true;
361   if (!isa<NamedDecl>(D) || shouldSkipNamelessDecl(cast<NamedDecl>(D)))
362     return true;
363 
364   SourceManager &SM = Ctx->getSourceManager();
365   FileID FID = SM.getFileID(SM.getFileLoc(Loc));
366   if (FID.isInvalid())
367     return true;
368 
369   bool Invalid = false;
370   const SrcMgr::SLocEntry &SEntry = SM.getSLocEntry(FID, &Invalid);
371   if (Invalid || !SEntry.isFile())
372     return true;
373 
374   if (SEntry.getFile().getFileCharacteristic() != SrcMgr::C_User) {
375     switch (IndexOpts.SystemSymbolFilter) {
376     case IndexingOptions::SystemSymbolFilterKind::None:
377       return true;
378     case IndexingOptions::SystemSymbolFilterKind::DeclarationsOnly:
379       if (!shouldReportOccurrenceForSystemDeclOnlyMode(IsRef, Roles, Relations))
380         return true;
381       break;
382     case IndexingOptions::SystemSymbolFilterKind::All:
383       break;
384     }
385   }
386 
387   if (!OrigD)
388     OrigD = D;
389 
390   if (isTemplateImplicitInstantiation(D)) {
391     if (!IsRef)
392       return true;
393     D = adjustTemplateImplicitInstantiation(D);
394     if (!D)
395       return true;
396     assert(!isTemplateImplicitInstantiation(D));
397   }
398 
399   if (IsRef)
400     Roles |= (unsigned)SymbolRole::Reference;
401   else if (isDeclADefinition(OrigD, ContainerDC, *Ctx))
402     Roles |= (unsigned)SymbolRole::Definition;
403   else
404     Roles |= (unsigned)SymbolRole::Declaration;
405 
406   D = getCanonicalDecl(D);
407   Parent = adjustParent(Parent);
408   if (Parent)
409     Parent = getCanonicalDecl(Parent);
410 
411   SmallVector<SymbolRelation, 6> FinalRelations;
412   FinalRelations.reserve(Relations.size()+1);
413 
414   auto addRelation = [&](SymbolRelation Rel) {
415     auto It = llvm::find_if(FinalRelations, [&](SymbolRelation Elem) -> bool {
416       return Elem.RelatedSymbol == Rel.RelatedSymbol;
417     });
418     if (It != FinalRelations.end()) {
419       It->Roles |= Rel.Roles;
420     } else {
421       FinalRelations.push_back(Rel);
422     }
423     Roles |= Rel.Roles;
424   };
425 
426   if (Parent) {
427     if (IsRef || (!isa<ParmVarDecl>(D) && isFunctionLocalSymbol(D))) {
428       addRelation(SymbolRelation{
429         (unsigned)SymbolRole::RelationContainedBy,
430         Parent
431       });
432     } else {
433       addRelation(SymbolRelation{
434         (unsigned)SymbolRole::RelationChildOf,
435         Parent
436       });
437     }
438   }
439 
440   for (auto &Rel : Relations) {
441     addRelation(SymbolRelation(Rel.Roles,
442                                Rel.RelatedSymbol->getCanonicalDecl()));
443   }
444 
445   IndexDataConsumer::ASTNodeInfo Node{OrigE, OrigD, Parent, ContainerDC};
446   return DataConsumer.handleDeclOccurence(D, Roles, FinalRelations, Loc, Node);
447 }
448 
449 void IndexingContext::handleMacroDefined(const IdentifierInfo &Name,
450                                          SourceLocation Loc,
451                                          const MacroInfo &MI) {
452   SymbolRoleSet Roles = (unsigned)SymbolRole::Definition;
453   DataConsumer.handleMacroOccurence(&Name, &MI, Roles, Loc);
454 }
455 
456 void IndexingContext::handleMacroUndefined(const IdentifierInfo &Name,
457                                            SourceLocation Loc,
458                                            const MacroInfo &MI) {
459   SymbolRoleSet Roles = (unsigned)SymbolRole::Undefinition;
460   DataConsumer.handleMacroOccurence(&Name, &MI, Roles, Loc);
461 }
462 
463 void IndexingContext::handleMacroReference(const IdentifierInfo &Name,
464                                            SourceLocation Loc,
465                                            const MacroInfo &MI) {
466   SymbolRoleSet Roles = (unsigned)SymbolRole::Reference;
467   DataConsumer.handleMacroOccurence(&Name, &MI, Roles, Loc);
468 }
469