1 //===- CXIndexDataConsumer.cpp - Index data consumer for libclang----------===//
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 "CXIndexDataConsumer.h"
10 #include "CIndexDiagnostic.h"
11 #include "CXTranslationUnit.h"
12 #include "clang/AST/Attr.h"
13 #include "clang/AST/DeclCXX.h"
14 #include "clang/AST/DeclTemplate.h"
15 #include "clang/AST/DeclVisitor.h"
16 #include "clang/Frontend/ASTUnit.h"
17 
18 using namespace clang;
19 using namespace clang::index;
20 using namespace cxindex;
21 using namespace cxcursor;
22 
23 namespace {
24 class IndexingDeclVisitor : public ConstDeclVisitor<IndexingDeclVisitor, bool> {
25   CXIndexDataConsumer &DataConsumer;
26   SourceLocation DeclLoc;
27   const DeclContext *LexicalDC;
28 
29 public:
IndexingDeclVisitor(CXIndexDataConsumer & dataConsumer,SourceLocation Loc,const DeclContext * lexicalDC)30   IndexingDeclVisitor(CXIndexDataConsumer &dataConsumer, SourceLocation Loc,
31                       const DeclContext *lexicalDC)
32     : DataConsumer(dataConsumer), DeclLoc(Loc), LexicalDC(lexicalDC) { }
33 
VisitFunctionDecl(const FunctionDecl * D)34   bool VisitFunctionDecl(const FunctionDecl *D) {
35     DataConsumer.handleFunction(D);
36     return true;
37   }
38 
VisitVarDecl(const VarDecl * D)39   bool VisitVarDecl(const VarDecl *D) {
40     DataConsumer.handleVar(D);
41     return true;
42   }
43 
VisitFieldDecl(const FieldDecl * D)44   bool VisitFieldDecl(const FieldDecl *D) {
45     DataConsumer.handleField(D);
46     return true;
47   }
48 
VisitMSPropertyDecl(const MSPropertyDecl * D)49   bool VisitMSPropertyDecl(const MSPropertyDecl *D) {
50     return true;
51   }
52 
VisitEnumConstantDecl(const EnumConstantDecl * D)53   bool VisitEnumConstantDecl(const EnumConstantDecl *D) {
54     DataConsumer.handleEnumerator(D);
55     return true;
56   }
57 
VisitTypedefNameDecl(const TypedefNameDecl * D)58   bool VisitTypedefNameDecl(const TypedefNameDecl *D) {
59     DataConsumer.handleTypedefName(D);
60     return true;
61   }
62 
VisitTagDecl(const TagDecl * D)63   bool VisitTagDecl(const TagDecl *D) {
64     DataConsumer.handleTagDecl(D);
65     return true;
66   }
67 
VisitObjCInterfaceDecl(const ObjCInterfaceDecl * D)68   bool VisitObjCInterfaceDecl(const ObjCInterfaceDecl *D) {
69     DataConsumer.handleObjCInterface(D);
70     return true;
71   }
72 
VisitObjCProtocolDecl(const ObjCProtocolDecl * D)73   bool VisitObjCProtocolDecl(const ObjCProtocolDecl *D) {
74     DataConsumer.handleObjCProtocol(D);
75     return true;
76   }
77 
VisitObjCImplementationDecl(const ObjCImplementationDecl * D)78   bool VisitObjCImplementationDecl(const ObjCImplementationDecl *D) {
79     DataConsumer.handleObjCImplementation(D);
80     return true;
81   }
82 
VisitObjCCategoryDecl(const ObjCCategoryDecl * D)83   bool VisitObjCCategoryDecl(const ObjCCategoryDecl *D) {
84     DataConsumer.handleObjCCategory(D);
85     return true;
86   }
87 
VisitObjCCategoryImplDecl(const ObjCCategoryImplDecl * D)88   bool VisitObjCCategoryImplDecl(const ObjCCategoryImplDecl *D) {
89     DataConsumer.handleObjCCategoryImpl(D);
90     return true;
91   }
92 
VisitObjCMethodDecl(const ObjCMethodDecl * D)93   bool VisitObjCMethodDecl(const ObjCMethodDecl *D) {
94     if (isa<ObjCImplDecl>(LexicalDC) && !D->isThisDeclarationADefinition())
95       DataConsumer.handleSynthesizedObjCMethod(D, DeclLoc, LexicalDC);
96     else
97       DataConsumer.handleObjCMethod(D, DeclLoc);
98     return true;
99   }
100 
VisitObjCPropertyDecl(const ObjCPropertyDecl * D)101   bool VisitObjCPropertyDecl(const ObjCPropertyDecl *D) {
102     DataConsumer.handleObjCProperty(D);
103     return true;
104   }
105 
VisitObjCPropertyImplDecl(const ObjCPropertyImplDecl * D)106   bool VisitObjCPropertyImplDecl(const ObjCPropertyImplDecl *D) {
107     DataConsumer.handleSynthesizedObjCProperty(D);
108     return true;
109   }
110 
VisitNamespaceDecl(const NamespaceDecl * D)111   bool VisitNamespaceDecl(const NamespaceDecl *D) {
112     DataConsumer.handleNamespace(D);
113     return true;
114   }
115 
VisitUsingDecl(const UsingDecl * D)116   bool VisitUsingDecl(const UsingDecl *D) {
117     return true;
118   }
119 
VisitUsingDirectiveDecl(const UsingDirectiveDecl * D)120   bool VisitUsingDirectiveDecl(const UsingDirectiveDecl *D) {
121     return true;
122   }
123 
VisitClassTemplateDecl(const ClassTemplateDecl * D)124   bool VisitClassTemplateDecl(const ClassTemplateDecl *D) {
125     DataConsumer.handleClassTemplate(D);
126     return true;
127   }
128 
VisitClassTemplateSpecializationDecl(const ClassTemplateSpecializationDecl * D)129   bool VisitClassTemplateSpecializationDecl(const
130                                            ClassTemplateSpecializationDecl *D) {
131     DataConsumer.handleTagDecl(D);
132     return true;
133   }
134 
VisitFunctionTemplateDecl(const FunctionTemplateDecl * D)135   bool VisitFunctionTemplateDecl(const FunctionTemplateDecl *D) {
136     DataConsumer.handleFunctionTemplate(D);
137     return true;
138   }
139 
VisitTypeAliasTemplateDecl(const TypeAliasTemplateDecl * D)140   bool VisitTypeAliasTemplateDecl(const TypeAliasTemplateDecl *D) {
141     DataConsumer.handleTypeAliasTemplate(D);
142     return true;
143   }
144 
VisitImportDecl(const ImportDecl * D)145   bool VisitImportDecl(const ImportDecl *D) {
146     DataConsumer.importedModule(D);
147     return true;
148   }
149 };
150 
getSymbolRole(SymbolRoleSet Role)151 CXSymbolRole getSymbolRole(SymbolRoleSet Role) {
152   // CXSymbolRole mirrors low 9 bits of clang::index::SymbolRole.
153   return CXSymbolRole(static_cast<uint32_t>(Role) & ((1 << 9) - 1));
154 }
155 }
156 
handleDeclOccurrence(const Decl * D,SymbolRoleSet Roles,ArrayRef<SymbolRelation> Relations,SourceLocation Loc,ASTNodeInfo ASTNode)157 bool CXIndexDataConsumer::handleDeclOccurrence(
158     const Decl *D, SymbolRoleSet Roles, ArrayRef<SymbolRelation> Relations,
159     SourceLocation Loc, ASTNodeInfo ASTNode) {
160   Loc = getASTContext().getSourceManager().getFileLoc(Loc);
161 
162   if (Roles & (unsigned)SymbolRole::Reference) {
163     const NamedDecl *ND = dyn_cast<NamedDecl>(D);
164     if (!ND)
165       return true;
166 
167     if (auto *ObjCID = dyn_cast_or_null<ObjCInterfaceDecl>(ASTNode.OrigD)) {
168       if (!ObjCID->isThisDeclarationADefinition() &&
169           ObjCID->getLocation() == Loc) {
170         // The libclang API treats this as ObjCClassRef declaration.
171         IndexingDeclVisitor(*this, Loc, nullptr).Visit(ObjCID);
172         return true;
173       }
174     }
175     if (auto *ObjCPD = dyn_cast_or_null<ObjCProtocolDecl>(ASTNode.OrigD)) {
176       if (!ObjCPD->isThisDeclarationADefinition() &&
177           ObjCPD->getLocation() == Loc) {
178         // The libclang API treats this as ObjCProtocolRef declaration.
179         IndexingDeclVisitor(*this, Loc, nullptr).Visit(ObjCPD);
180         return true;
181       }
182     }
183 
184     CXIdxEntityRefKind Kind = CXIdxEntityRef_Direct;
185     if (Roles & (unsigned)SymbolRole::Implicit) {
186       Kind = CXIdxEntityRef_Implicit;
187     }
188     CXSymbolRole CXRole = getSymbolRole(Roles);
189 
190     CXCursor Cursor;
191     if (ASTNode.OrigE) {
192       Cursor = cxcursor::MakeCXCursor(ASTNode.OrigE,
193                                       cast<Decl>(ASTNode.ContainerDC),
194                                       getCXTU());
195     } else {
196       if (ASTNode.OrigD) {
197         if (auto *OrigND = dyn_cast<NamedDecl>(ASTNode.OrigD))
198           Cursor = getRefCursor(OrigND, Loc);
199         else
200           Cursor = MakeCXCursor(ASTNode.OrigD, CXTU);
201       } else {
202         Cursor = getRefCursor(ND, Loc);
203       }
204     }
205     handleReference(ND, Loc, Cursor,
206                     dyn_cast_or_null<NamedDecl>(ASTNode.Parent),
207                     ASTNode.ContainerDC, ASTNode.OrigE, Kind, CXRole);
208 
209   } else {
210     const DeclContext *LexicalDC = ASTNode.ContainerDC;
211     if (!LexicalDC) {
212       for (const auto &SymRel : Relations) {
213         if (SymRel.Roles & (unsigned)SymbolRole::RelationChildOf)
214           LexicalDC = dyn_cast<DeclContext>(SymRel.RelatedSymbol);
215       }
216     }
217     IndexingDeclVisitor(*this, Loc, LexicalDC).Visit(ASTNode.OrigD);
218   }
219 
220   return !shouldAbort();
221 }
222 
handleModuleOccurrence(const ImportDecl * ImportD,const Module * Mod,SymbolRoleSet Roles,SourceLocation Loc)223 bool CXIndexDataConsumer::handleModuleOccurrence(const ImportDecl *ImportD,
224                                                  const Module *Mod,
225                                                  SymbolRoleSet Roles,
226                                                  SourceLocation Loc) {
227   if (Roles & (SymbolRoleSet)SymbolRole::Declaration)
228     IndexingDeclVisitor(*this, SourceLocation(), nullptr).Visit(ImportD);
229   return !shouldAbort();
230 }
231 
finish()232 void CXIndexDataConsumer::finish() {
233   indexDiagnostics();
234 }
235 
236 
ObjCProtocolListInfo(const ObjCProtocolList & ProtList,CXIndexDataConsumer & IdxCtx,ScratchAlloc & SA)237 CXIndexDataConsumer::ObjCProtocolListInfo::ObjCProtocolListInfo(
238                                     const ObjCProtocolList &ProtList,
239                                     CXIndexDataConsumer &IdxCtx,
240                                     ScratchAlloc &SA) {
241   ObjCInterfaceDecl::protocol_loc_iterator LI = ProtList.loc_begin();
242   for (ObjCInterfaceDecl::protocol_iterator
243          I = ProtList.begin(), E = ProtList.end(); I != E; ++I, ++LI) {
244     SourceLocation Loc = *LI;
245     ObjCProtocolDecl *PD = *I;
246     ProtEntities.push_back(EntityInfo());
247     IdxCtx.getEntityInfo(PD, ProtEntities.back(), SA);
248     CXIdxObjCProtocolRefInfo ProtInfo = { nullptr,
249                                 MakeCursorObjCProtocolRef(PD, Loc, IdxCtx.CXTU),
250                                 IdxCtx.getIndexLoc(Loc) };
251     ProtInfos.push_back(ProtInfo);
252 
253     if (IdxCtx.shouldSuppressRefs())
254       IdxCtx.markEntityOccurrenceInFile(PD, Loc);
255   }
256 
257   for (unsigned i = 0, e = ProtInfos.size(); i != e; ++i)
258     ProtInfos[i].protocol = &ProtEntities[i];
259 
260   for (unsigned i = 0, e = ProtInfos.size(); i != e; ++i)
261     Prots.push_back(&ProtInfos[i]);
262 }
263 
264 
IBOutletCollectionInfo(const IBOutletCollectionInfo & other)265 IBOutletCollectionInfo::IBOutletCollectionInfo(
266                                           const IBOutletCollectionInfo &other)
267   : AttrInfo(CXIdxAttr_IBOutletCollection, other.cursor, other.loc, other.A) {
268 
269   IBCollInfo.attrInfo = this;
270   IBCollInfo.classCursor = other.IBCollInfo.classCursor;
271   IBCollInfo.classLoc = other.IBCollInfo.classLoc;
272   if (other.IBCollInfo.objcClass) {
273     ClassInfo = other.ClassInfo;
274     IBCollInfo.objcClass = &ClassInfo;
275   } else
276     IBCollInfo.objcClass = nullptr;
277 }
278 
AttrListInfo(const Decl * D,CXIndexDataConsumer & IdxCtx)279 AttrListInfo::AttrListInfo(const Decl *D, CXIndexDataConsumer &IdxCtx)
280   : SA(IdxCtx), ref_cnt(0) {
281 
282   if (!D->hasAttrs())
283     return;
284 
285   for (const auto *A : D->attrs()) {
286     CXCursor C = MakeCXCursor(A, D, IdxCtx.CXTU);
287     CXIdxLoc Loc =  IdxCtx.getIndexLoc(A->getLocation());
288     switch (C.kind) {
289     default:
290       Attrs.push_back(AttrInfo(CXIdxAttr_Unexposed, C, Loc, A));
291       break;
292     case CXCursor_IBActionAttr:
293       Attrs.push_back(AttrInfo(CXIdxAttr_IBAction, C, Loc, A));
294       break;
295     case CXCursor_IBOutletAttr:
296       Attrs.push_back(AttrInfo(CXIdxAttr_IBOutlet, C, Loc, A));
297       break;
298     case CXCursor_IBOutletCollectionAttr:
299       IBCollAttrs.push_back(IBOutletCollectionInfo(C, Loc, A));
300       break;
301     }
302   }
303 
304   for (unsigned i = 0, e = IBCollAttrs.size(); i != e; ++i) {
305     IBOutletCollectionInfo &IBInfo = IBCollAttrs[i];
306     CXAttrs.push_back(&IBInfo);
307 
308     const IBOutletCollectionAttr *
309       IBAttr = cast<IBOutletCollectionAttr>(IBInfo.A);
310     SourceLocation InterfaceLocStart =
311         IBAttr->getInterfaceLoc()->getTypeLoc().getBeginLoc();
312     IBInfo.IBCollInfo.attrInfo = &IBInfo;
313     IBInfo.IBCollInfo.classLoc = IdxCtx.getIndexLoc(InterfaceLocStart);
314     IBInfo.IBCollInfo.objcClass = nullptr;
315     IBInfo.IBCollInfo.classCursor = clang_getNullCursor();
316     QualType Ty = IBAttr->getInterface();
317     if (const ObjCObjectType *ObjectTy = Ty->getAs<ObjCObjectType>()) {
318       if (const ObjCInterfaceDecl *InterD = ObjectTy->getInterface()) {
319         IdxCtx.getEntityInfo(InterD, IBInfo.ClassInfo, SA);
320         IBInfo.IBCollInfo.objcClass = &IBInfo.ClassInfo;
321         IBInfo.IBCollInfo.classCursor =
322             MakeCursorObjCClassRef(InterD, InterfaceLocStart, IdxCtx.CXTU);
323       }
324     }
325   }
326 
327   for (unsigned i = 0, e = Attrs.size(); i != e; ++i)
328     CXAttrs.push_back(&Attrs[i]);
329 }
330 
331 IntrusiveRefCntPtr<AttrListInfo>
create(const Decl * D,CXIndexDataConsumer & IdxCtx)332 AttrListInfo::create(const Decl *D, CXIndexDataConsumer &IdxCtx) {
333   ScratchAlloc SA(IdxCtx);
334   AttrListInfo *attrs = SA.allocate<AttrListInfo>();
335   return new (attrs) AttrListInfo(D, IdxCtx);
336 }
337 
CXXBasesListInfo(const CXXRecordDecl * D,CXIndexDataConsumer & IdxCtx,ScratchAlloc & SA)338 CXIndexDataConsumer::CXXBasesListInfo::CXXBasesListInfo(const CXXRecordDecl *D,
339                                    CXIndexDataConsumer &IdxCtx,
340                                    ScratchAlloc &SA) {
341   for (const auto &Base : D->bases()) {
342     BaseEntities.push_back(EntityInfo());
343     const NamedDecl *BaseD = nullptr;
344     QualType T = Base.getType();
345     SourceLocation Loc = getBaseLoc(Base);
346 
347     if (const TypedefType *TDT = T->getAs<TypedefType>()) {
348       BaseD = TDT->getDecl();
349     } else if (const TemplateSpecializationType *
350           TST = T->getAs<TemplateSpecializationType>()) {
351       BaseD = TST->getTemplateName().getAsTemplateDecl();
352     } else if (const RecordType *RT = T->getAs<RecordType>()) {
353       BaseD = RT->getDecl();
354     }
355 
356     if (BaseD)
357       IdxCtx.getEntityInfo(BaseD, BaseEntities.back(), SA);
358     CXIdxBaseClassInfo BaseInfo = { nullptr,
359                          MakeCursorCXXBaseSpecifier(&Base, IdxCtx.CXTU),
360                          IdxCtx.getIndexLoc(Loc) };
361     BaseInfos.push_back(BaseInfo);
362   }
363 
364   for (unsigned i = 0, e = BaseInfos.size(); i != e; ++i) {
365     if (BaseEntities[i].name && BaseEntities[i].USR)
366       BaseInfos[i].base = &BaseEntities[i];
367   }
368 
369   for (unsigned i = 0, e = BaseInfos.size(); i != e; ++i)
370     CXBases.push_back(&BaseInfos[i]);
371 }
372 
getBaseLoc(const CXXBaseSpecifier & Base) const373 SourceLocation CXIndexDataConsumer::CXXBasesListInfo::getBaseLoc(
374                                            const CXXBaseSpecifier &Base) const {
375   SourceLocation Loc = Base.getSourceRange().getBegin();
376   TypeLoc TL;
377   if (Base.getTypeSourceInfo())
378     TL = Base.getTypeSourceInfo()->getTypeLoc();
379   if (TL.isNull())
380     return Loc;
381 
382   if (QualifiedTypeLoc QL = TL.getAs<QualifiedTypeLoc>())
383     TL = QL.getUnqualifiedLoc();
384 
385   if (ElaboratedTypeLoc EL = TL.getAs<ElaboratedTypeLoc>())
386     return EL.getNamedTypeLoc().getBeginLoc();
387   if (DependentNameTypeLoc DL = TL.getAs<DependentNameTypeLoc>())
388     return DL.getNameLoc();
389   if (DependentTemplateSpecializationTypeLoc DTL =
390           TL.getAs<DependentTemplateSpecializationTypeLoc>())
391     return DTL.getTemplateNameLoc();
392 
393   return Loc;
394 }
395 
toCStr(StringRef Str)396 const char *ScratchAlloc::toCStr(StringRef Str) {
397   if (Str.empty())
398     return "";
399   if (Str.data()[Str.size()] == '\0')
400     return Str.data();
401   return copyCStr(Str);
402 }
403 
copyCStr(StringRef Str)404 const char *ScratchAlloc::copyCStr(StringRef Str) {
405   char *buf = IdxCtx.StrScratch.Allocate<char>(Str.size() + 1);
406   std::uninitialized_copy(Str.begin(), Str.end(), buf);
407   buf[Str.size()] = '\0';
408   return buf;
409 }
410 
setASTContext(ASTContext & ctx)411 void CXIndexDataConsumer::setASTContext(ASTContext &ctx) {
412   Ctx = &ctx;
413   cxtu::getASTUnit(CXTU)->setASTContext(&ctx);
414 }
415 
setPreprocessor(std::shared_ptr<Preprocessor> PP)416 void CXIndexDataConsumer::setPreprocessor(std::shared_ptr<Preprocessor> PP) {
417   cxtu::getASTUnit(CXTU)->setPreprocessor(std::move(PP));
418 }
419 
isFunctionLocalDecl(const Decl * D)420 bool CXIndexDataConsumer::isFunctionLocalDecl(const Decl *D) {
421   assert(D);
422 
423   if (!D->getParentFunctionOrMethod())
424     return false;
425 
426   if (const NamedDecl *ND = dyn_cast<NamedDecl>(D)) {
427     switch (ND->getFormalLinkage()) {
428     case NoLinkage:
429     case InternalLinkage:
430       return true;
431     case VisibleNoLinkage:
432     case ModuleInternalLinkage:
433     case UniqueExternalLinkage:
434       llvm_unreachable("Not a sema linkage");
435     case ModuleLinkage:
436     case ExternalLinkage:
437       return false;
438     }
439   }
440 
441   return true;
442 }
443 
shouldAbort()444 bool CXIndexDataConsumer::shouldAbort() {
445   if (!CB.abortQuery)
446     return false;
447   return CB.abortQuery(ClientData, nullptr);
448 }
449 
enteredMainFile(const FileEntry * File)450 void CXIndexDataConsumer::enteredMainFile(const FileEntry *File) {
451   if (File && CB.enteredMainFile) {
452     CXIdxClientFile idxFile =
453       CB.enteredMainFile(ClientData,
454                          static_cast<CXFile>(const_cast<FileEntry *>(File)),
455                          nullptr);
456     FileMap[File] = idxFile;
457   }
458 }
459 
ppIncludedFile(SourceLocation hashLoc,StringRef filename,const FileEntry * File,bool isImport,bool isAngled,bool isModuleImport)460 void CXIndexDataConsumer::ppIncludedFile(SourceLocation hashLoc,
461                                      StringRef filename,
462                                      const FileEntry *File,
463                                      bool isImport, bool isAngled,
464                                      bool isModuleImport) {
465   if (!CB.ppIncludedFile)
466     return;
467 
468   ScratchAlloc SA(*this);
469   CXIdxIncludedFileInfo Info = { getIndexLoc(hashLoc),
470                                  SA.toCStr(filename),
471                                  static_cast<CXFile>(
472                                    const_cast<FileEntry *>(File)),
473                                  isImport, isAngled, isModuleImport };
474   CXIdxClientFile idxFile = CB.ppIncludedFile(ClientData, &Info);
475   FileMap[File] = idxFile;
476 }
477 
importedModule(const ImportDecl * ImportD)478 void CXIndexDataConsumer::importedModule(const ImportDecl *ImportD) {
479   if (!CB.importedASTFile)
480     return;
481 
482   Module *Mod = ImportD->getImportedModule();
483   if (!Mod)
484     return;
485 
486   // If the imported module is part of the top-level module that we're
487   // indexing, it doesn't correspond to an imported AST file.
488   // FIXME: This assumes that AST files and top-level modules directly
489   // correspond, which is unlikely to remain true forever.
490   if (Module *SrcMod = ImportD->getImportedOwningModule())
491     if (SrcMod->getTopLevelModule() == Mod->getTopLevelModule())
492       return;
493 
494   FileEntry *FE = nullptr;
495   if (auto File = Mod->getASTFile())
496     FE = const_cast<FileEntry *>(&File->getFileEntry());
497   CXIdxImportedASTFileInfo Info = {static_cast<CXFile>(FE), Mod,
498                                    getIndexLoc(ImportD->getLocation()),
499                                    ImportD->isImplicit()};
500   CXIdxClientASTFile astFile = CB.importedASTFile(ClientData, &Info);
501   (void)astFile;
502 }
503 
importedPCH(const FileEntry * File)504 void CXIndexDataConsumer::importedPCH(const FileEntry *File) {
505   if (!CB.importedASTFile)
506     return;
507 
508   CXIdxImportedASTFileInfo Info = {
509                                     static_cast<CXFile>(
510                                       const_cast<FileEntry *>(File)),
511                                     /*module=*/nullptr,
512                                     getIndexLoc(SourceLocation()),
513                                     /*isImplicit=*/false
514                                   };
515   CXIdxClientASTFile astFile = CB.importedASTFile(ClientData, &Info);
516   (void)astFile;
517 }
518 
startedTranslationUnit()519 void CXIndexDataConsumer::startedTranslationUnit() {
520   CXIdxClientContainer idxCont = nullptr;
521   if (CB.startedTranslationUnit)
522     idxCont = CB.startedTranslationUnit(ClientData, nullptr);
523   addContainerInMap(Ctx->getTranslationUnitDecl(), idxCont);
524 }
525 
indexDiagnostics()526 void CXIndexDataConsumer::indexDiagnostics() {
527   if (!hasDiagnosticCallback())
528     return;
529 
530   CXDiagnosticSetImpl *DiagSet = cxdiag::lazyCreateDiags(getCXTU());
531   handleDiagnosticSet(DiagSet);
532 }
533 
handleDiagnosticSet(CXDiagnostic CXDiagSet)534 void CXIndexDataConsumer::handleDiagnosticSet(CXDiagnostic CXDiagSet) {
535   if (!CB.diagnostic)
536     return;
537 
538   CB.diagnostic(ClientData, CXDiagSet, nullptr);
539 }
540 
handleDecl(const NamedDecl * D,SourceLocation Loc,CXCursor Cursor,DeclInfo & DInfo,const DeclContext * LexicalDC,const DeclContext * SemaDC)541 bool CXIndexDataConsumer::handleDecl(const NamedDecl *D,
542                                  SourceLocation Loc, CXCursor Cursor,
543                                  DeclInfo &DInfo,
544                                  const DeclContext *LexicalDC,
545                                  const DeclContext *SemaDC) {
546   if (!CB.indexDeclaration || !D)
547     return false;
548   if (D->isImplicit() && shouldIgnoreIfImplicit(D))
549     return false;
550 
551   ScratchAlloc SA(*this);
552   getEntityInfo(D, DInfo.EntInfo, SA);
553   if ((!shouldIndexFunctionLocalSymbols() && !DInfo.EntInfo.USR)
554       || Loc.isInvalid())
555     return false;
556 
557   if (!LexicalDC)
558     LexicalDC = D->getLexicalDeclContext();
559 
560   if (shouldSuppressRefs())
561     markEntityOccurrenceInFile(D, Loc);
562 
563   DInfo.entityInfo = &DInfo.EntInfo;
564   DInfo.cursor = Cursor;
565   DInfo.loc = getIndexLoc(Loc);
566   DInfo.isImplicit = D->isImplicit();
567 
568   DInfo.attributes = DInfo.EntInfo.attributes;
569   DInfo.numAttributes = DInfo.EntInfo.numAttributes;
570 
571   if (!SemaDC)
572     SemaDC = D->getDeclContext();
573   getContainerInfo(SemaDC, DInfo.SemanticContainer);
574   DInfo.semanticContainer = &DInfo.SemanticContainer;
575 
576   if (LexicalDC == SemaDC) {
577     DInfo.lexicalContainer = &DInfo.SemanticContainer;
578   } else if (isTemplateImplicitInstantiation(D)) {
579     // Implicit instantiations have the lexical context of where they were
580     // instantiated first. We choose instead the semantic context because:
581     // 1) at the time that we see the instantiation we have not seen the
582     //   function where it occurred yet.
583     // 2) the lexical context of the first instantiation is not useful
584     //   information anyway.
585     DInfo.lexicalContainer = &DInfo.SemanticContainer;
586   } else {
587     getContainerInfo(LexicalDC, DInfo.LexicalContainer);
588     DInfo.lexicalContainer = &DInfo.LexicalContainer;
589   }
590 
591   if (DInfo.isContainer) {
592     getContainerInfo(getEntityContainer(D), DInfo.DeclAsContainer);
593     DInfo.declAsContainer = &DInfo.DeclAsContainer;
594   }
595 
596   CB.indexDeclaration(ClientData, &DInfo);
597   return true;
598 }
599 
handleObjCContainer(const ObjCContainerDecl * D,SourceLocation Loc,CXCursor Cursor,ObjCContainerDeclInfo & ContDInfo)600 bool CXIndexDataConsumer::handleObjCContainer(const ObjCContainerDecl *D,
601                                           SourceLocation Loc, CXCursor Cursor,
602                                           ObjCContainerDeclInfo &ContDInfo) {
603   ContDInfo.ObjCContDeclInfo.declInfo = &ContDInfo;
604   return handleDecl(D, Loc, Cursor, ContDInfo);
605 }
606 
handleFunction(const FunctionDecl * D)607 bool CXIndexDataConsumer::handleFunction(const FunctionDecl *D) {
608   bool isDef = D->isThisDeclarationADefinition();
609   bool isContainer = isDef;
610   bool isSkipped = false;
611   if (D->hasSkippedBody()) {
612     isSkipped = true;
613     isDef = true;
614     isContainer = false;
615   }
616 
617   DeclInfo DInfo(!D->isFirstDecl(), isDef, isContainer);
618   if (isSkipped)
619     DInfo.flags |= CXIdxDeclFlag_Skipped;
620   return handleDecl(D, D->getLocation(), getCursor(D), DInfo);
621 }
622 
handleVar(const VarDecl * D)623 bool CXIndexDataConsumer::handleVar(const VarDecl *D) {
624   DeclInfo DInfo(!D->isFirstDecl(), D->isThisDeclarationADefinition(),
625                  /*isContainer=*/false);
626   return handleDecl(D, D->getLocation(), getCursor(D), DInfo);
627 }
628 
handleField(const FieldDecl * D)629 bool CXIndexDataConsumer::handleField(const FieldDecl *D) {
630   DeclInfo DInfo(/*isRedeclaration=*/false, /*isDefinition=*/true,
631                  /*isContainer=*/false);
632   return handleDecl(D, D->getLocation(), getCursor(D), DInfo);
633 }
634 
handleEnumerator(const EnumConstantDecl * D)635 bool CXIndexDataConsumer::handleEnumerator(const EnumConstantDecl *D) {
636   DeclInfo DInfo(/*isRedeclaration=*/false, /*isDefinition=*/true,
637                  /*isContainer=*/false);
638   return handleDecl(D, D->getLocation(), getCursor(D), DInfo);
639 }
640 
handleTagDecl(const TagDecl * D)641 bool CXIndexDataConsumer::handleTagDecl(const TagDecl *D) {
642   if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(D))
643     return handleCXXRecordDecl(CXXRD, D);
644 
645   DeclInfo DInfo(!D->isFirstDecl(), D->isThisDeclarationADefinition(),
646                  D->isThisDeclarationADefinition());
647   return handleDecl(D, D->getLocation(), getCursor(D), DInfo);
648 }
649 
handleTypedefName(const TypedefNameDecl * D)650 bool CXIndexDataConsumer::handleTypedefName(const TypedefNameDecl *D) {
651   DeclInfo DInfo(!D->isFirstDecl(), /*isDefinition=*/true,
652                  /*isContainer=*/false);
653   return handleDecl(D, D->getLocation(), getCursor(D), DInfo);
654 }
655 
handleObjCInterface(const ObjCInterfaceDecl * D)656 bool CXIndexDataConsumer::handleObjCInterface(const ObjCInterfaceDecl *D) {
657   // For @class forward declarations, suppress them the same way as references.
658   if (!D->isThisDeclarationADefinition()) {
659     if (shouldSuppressRefs() && markEntityOccurrenceInFile(D, D->getLocation()))
660       return false; // already occurred.
661 
662     // FIXME: This seems like the wrong definition for redeclaration.
663     bool isRedeclaration = D->hasDefinition() || D->getPreviousDecl();
664     ObjCContainerDeclInfo ContDInfo(/*isForwardRef=*/true, isRedeclaration,
665                                     /*isImplementation=*/false);
666     return handleObjCContainer(D, D->getLocation(),
667                                MakeCursorObjCClassRef(D, D->getLocation(),
668                                                       CXTU),
669                                ContDInfo);
670   }
671 
672   ScratchAlloc SA(*this);
673 
674   CXIdxBaseClassInfo BaseClass;
675   EntityInfo BaseEntity;
676   BaseClass.cursor = clang_getNullCursor();
677   if (ObjCInterfaceDecl *SuperD = D->getSuperClass()) {
678     getEntityInfo(SuperD, BaseEntity, SA);
679     SourceLocation SuperLoc = D->getSuperClassLoc();
680     BaseClass.base = &BaseEntity;
681     BaseClass.cursor = MakeCursorObjCSuperClassRef(SuperD, SuperLoc, CXTU);
682     BaseClass.loc = getIndexLoc(SuperLoc);
683 
684     if (shouldSuppressRefs())
685       markEntityOccurrenceInFile(SuperD, SuperLoc);
686   }
687 
688   ObjCProtocolList EmptyProtoList;
689   ObjCProtocolListInfo ProtInfo(D->isThisDeclarationADefinition()
690                                   ? D->getReferencedProtocols()
691                                   : EmptyProtoList,
692                                 *this, SA);
693 
694   ObjCInterfaceDeclInfo InterInfo(D);
695   InterInfo.ObjCProtoListInfo = ProtInfo.getListInfo();
696   InterInfo.ObjCInterDeclInfo.containerInfo = &InterInfo.ObjCContDeclInfo;
697   InterInfo.ObjCInterDeclInfo.superInfo = D->getSuperClass() ? &BaseClass
698                                                              : nullptr;
699   InterInfo.ObjCInterDeclInfo.protocols = &InterInfo.ObjCProtoListInfo;
700 
701   return handleObjCContainer(D, D->getLocation(), getCursor(D), InterInfo);
702 }
703 
handleObjCImplementation(const ObjCImplementationDecl * D)704 bool CXIndexDataConsumer::handleObjCImplementation(
705                                               const ObjCImplementationDecl *D) {
706   ObjCContainerDeclInfo ContDInfo(/*isForwardRef=*/false,
707                       /*isRedeclaration=*/true,
708                       /*isImplementation=*/true);
709   return handleObjCContainer(D, D->getLocation(), getCursor(D), ContDInfo);
710 }
711 
handleObjCProtocol(const ObjCProtocolDecl * D)712 bool CXIndexDataConsumer::handleObjCProtocol(const ObjCProtocolDecl *D) {
713   if (!D->isThisDeclarationADefinition()) {
714     if (shouldSuppressRefs() && markEntityOccurrenceInFile(D, D->getLocation()))
715       return false; // already occurred.
716 
717     // FIXME: This seems like the wrong definition for redeclaration.
718     bool isRedeclaration = D->hasDefinition() || D->getPreviousDecl();
719     ObjCContainerDeclInfo ContDInfo(/*isForwardRef=*/true,
720                                     isRedeclaration,
721                                     /*isImplementation=*/false);
722     return handleObjCContainer(D, D->getLocation(),
723                                MakeCursorObjCProtocolRef(D, D->getLocation(),
724                                                          CXTU),
725                                ContDInfo);
726   }
727 
728   ScratchAlloc SA(*this);
729   ObjCProtocolList EmptyProtoList;
730   ObjCProtocolListInfo ProtListInfo(D->isThisDeclarationADefinition()
731                                       ? D->getReferencedProtocols()
732                                       : EmptyProtoList,
733                                     *this, SA);
734 
735   ObjCProtocolDeclInfo ProtInfo(D);
736   ProtInfo.ObjCProtoRefListInfo = ProtListInfo.getListInfo();
737 
738   return handleObjCContainer(D, D->getLocation(), getCursor(D), ProtInfo);
739 }
740 
handleObjCCategory(const ObjCCategoryDecl * D)741 bool CXIndexDataConsumer::handleObjCCategory(const ObjCCategoryDecl *D) {
742   ScratchAlloc SA(*this);
743 
744   ObjCCategoryDeclInfo CatDInfo(/*isImplementation=*/false);
745   EntityInfo ClassEntity;
746   const ObjCInterfaceDecl *IFaceD = D->getClassInterface();
747   SourceLocation ClassLoc = D->getLocation();
748   SourceLocation CategoryLoc = D->IsClassExtension() ? ClassLoc
749                                                      : D->getCategoryNameLoc();
750   getEntityInfo(IFaceD, ClassEntity, SA);
751 
752   if (shouldSuppressRefs())
753     markEntityOccurrenceInFile(IFaceD, ClassLoc);
754 
755   ObjCProtocolListInfo ProtInfo(D->getReferencedProtocols(), *this, SA);
756 
757   CatDInfo.ObjCCatDeclInfo.containerInfo = &CatDInfo.ObjCContDeclInfo;
758   if (IFaceD) {
759     CatDInfo.ObjCCatDeclInfo.objcClass = &ClassEntity;
760     CatDInfo.ObjCCatDeclInfo.classCursor =
761         MakeCursorObjCClassRef(IFaceD, ClassLoc, CXTU);
762   } else {
763     CatDInfo.ObjCCatDeclInfo.objcClass = nullptr;
764     CatDInfo.ObjCCatDeclInfo.classCursor = clang_getNullCursor();
765   }
766   CatDInfo.ObjCCatDeclInfo.classLoc = getIndexLoc(ClassLoc);
767   CatDInfo.ObjCProtoListInfo = ProtInfo.getListInfo();
768   CatDInfo.ObjCCatDeclInfo.protocols = &CatDInfo.ObjCProtoListInfo;
769 
770   return handleObjCContainer(D, CategoryLoc, getCursor(D), CatDInfo);
771 }
772 
handleObjCCategoryImpl(const ObjCCategoryImplDecl * D)773 bool CXIndexDataConsumer::handleObjCCategoryImpl(const ObjCCategoryImplDecl *D) {
774   ScratchAlloc SA(*this);
775 
776   const ObjCCategoryDecl *CatD = D->getCategoryDecl();
777   ObjCCategoryDeclInfo CatDInfo(/*isImplementation=*/true);
778   EntityInfo ClassEntity;
779   const ObjCInterfaceDecl *IFaceD = CatD->getClassInterface();
780   SourceLocation ClassLoc = D->getLocation();
781   SourceLocation CategoryLoc = D->getCategoryNameLoc();
782   getEntityInfo(IFaceD, ClassEntity, SA);
783 
784   if (shouldSuppressRefs())
785     markEntityOccurrenceInFile(IFaceD, ClassLoc);
786 
787   CatDInfo.ObjCCatDeclInfo.containerInfo = &CatDInfo.ObjCContDeclInfo;
788   if (IFaceD) {
789     CatDInfo.ObjCCatDeclInfo.objcClass = &ClassEntity;
790     CatDInfo.ObjCCatDeclInfo.classCursor =
791         MakeCursorObjCClassRef(IFaceD, ClassLoc, CXTU);
792   } else {
793     CatDInfo.ObjCCatDeclInfo.objcClass = nullptr;
794     CatDInfo.ObjCCatDeclInfo.classCursor = clang_getNullCursor();
795   }
796   CatDInfo.ObjCCatDeclInfo.classLoc = getIndexLoc(ClassLoc);
797   CatDInfo.ObjCCatDeclInfo.protocols = nullptr;
798 
799   return handleObjCContainer(D, CategoryLoc, getCursor(D), CatDInfo);
800 }
801 
handleObjCMethod(const ObjCMethodDecl * D,SourceLocation Loc)802 bool CXIndexDataConsumer::handleObjCMethod(const ObjCMethodDecl *D,
803                                            SourceLocation Loc) {
804   bool isDef = D->isThisDeclarationADefinition();
805   bool isContainer = isDef;
806   bool isSkipped = false;
807   if (D->hasSkippedBody()) {
808     isSkipped = true;
809     isDef = true;
810     isContainer = false;
811   }
812 
813   DeclInfo DInfo(!D->isCanonicalDecl(), isDef, isContainer);
814   if (isSkipped)
815     DInfo.flags |= CXIdxDeclFlag_Skipped;
816   return handleDecl(D, Loc, getCursor(D), DInfo);
817 }
818 
handleSynthesizedObjCProperty(const ObjCPropertyImplDecl * D)819 bool CXIndexDataConsumer::handleSynthesizedObjCProperty(
820                                                 const ObjCPropertyImplDecl *D) {
821   ObjCPropertyDecl *PD = D->getPropertyDecl();
822   auto *DC = D->getDeclContext();
823   return handleReference(PD, D->getLocation(), getCursor(D),
824                          dyn_cast<NamedDecl>(DC), DC);
825 }
826 
handleSynthesizedObjCMethod(const ObjCMethodDecl * D,SourceLocation Loc,const DeclContext * LexicalDC)827 bool CXIndexDataConsumer::handleSynthesizedObjCMethod(const ObjCMethodDecl *D,
828                                                   SourceLocation Loc,
829                                                  const DeclContext *LexicalDC) {
830   DeclInfo DInfo(/*isRedeclaration=*/true, /*isDefinition=*/true,
831                  /*isContainer=*/false);
832   return handleDecl(D, Loc, getCursor(D), DInfo, LexicalDC, D->getDeclContext());
833 }
834 
handleObjCProperty(const ObjCPropertyDecl * D)835 bool CXIndexDataConsumer::handleObjCProperty(const ObjCPropertyDecl *D) {
836   ScratchAlloc SA(*this);
837 
838   ObjCPropertyDeclInfo DInfo;
839   EntityInfo GetterEntity;
840   EntityInfo SetterEntity;
841 
842   DInfo.ObjCPropDeclInfo.declInfo = &DInfo;
843 
844   if (ObjCMethodDecl *Getter = D->getGetterMethodDecl()) {
845     getEntityInfo(Getter, GetterEntity, SA);
846     DInfo.ObjCPropDeclInfo.getter = &GetterEntity;
847   } else {
848     DInfo.ObjCPropDeclInfo.getter = nullptr;
849   }
850   if (ObjCMethodDecl *Setter = D->getSetterMethodDecl()) {
851     getEntityInfo(Setter, SetterEntity, SA);
852     DInfo.ObjCPropDeclInfo.setter = &SetterEntity;
853   } else {
854     DInfo.ObjCPropDeclInfo.setter = nullptr;
855   }
856 
857   return handleDecl(D, D->getLocation(), getCursor(D), DInfo);
858 }
859 
handleNamespace(const NamespaceDecl * D)860 bool CXIndexDataConsumer::handleNamespace(const NamespaceDecl *D) {
861   DeclInfo DInfo(/*isRedeclaration=*/!D->isOriginalNamespace(),
862                  /*isDefinition=*/true,
863                  /*isContainer=*/true);
864   return handleDecl(D, D->getLocation(), getCursor(D), DInfo);
865 }
866 
handleClassTemplate(const ClassTemplateDecl * D)867 bool CXIndexDataConsumer::handleClassTemplate(const ClassTemplateDecl *D) {
868   return handleCXXRecordDecl(D->getTemplatedDecl(), D);
869 }
870 
handleFunctionTemplate(const FunctionTemplateDecl * D)871 bool CXIndexDataConsumer::handleFunctionTemplate(const FunctionTemplateDecl *D) {
872   DeclInfo DInfo(/*isRedeclaration=*/!D->isCanonicalDecl(),
873                  /*isDefinition=*/D->isThisDeclarationADefinition(),
874                  /*isContainer=*/D->isThisDeclarationADefinition());
875   return handleDecl(D, D->getLocation(), getCursor(D), DInfo);
876 }
877 
handleTypeAliasTemplate(const TypeAliasTemplateDecl * D)878 bool CXIndexDataConsumer::handleTypeAliasTemplate(const TypeAliasTemplateDecl *D) {
879   DeclInfo DInfo(/*isRedeclaration=*/!D->isCanonicalDecl(),
880                  /*isDefinition=*/true, /*isContainer=*/false);
881   return handleDecl(D, D->getLocation(), getCursor(D), DInfo);
882 }
883 
handleReference(const NamedDecl * D,SourceLocation Loc,CXCursor Cursor,const NamedDecl * Parent,const DeclContext * DC,const Expr * E,CXIdxEntityRefKind Kind,CXSymbolRole Role)884 bool CXIndexDataConsumer::handleReference(const NamedDecl *D, SourceLocation Loc,
885                                       CXCursor Cursor,
886                                       const NamedDecl *Parent,
887                                       const DeclContext *DC,
888                                       const Expr *E,
889                                       CXIdxEntityRefKind Kind,
890                                       CXSymbolRole Role) {
891   if (!CB.indexEntityReference)
892     return false;
893 
894   if (!D || !DC)
895     return false;
896   if (Loc.isInvalid())
897     return false;
898   if (!shouldIndexFunctionLocalSymbols() && isFunctionLocalDecl(D))
899     return false;
900   if (isNotFromSourceFile(D->getLocation()))
901     return false;
902   if (D->isImplicit() && shouldIgnoreIfImplicit(D))
903     return false;
904 
905   if (shouldSuppressRefs()) {
906     if (markEntityOccurrenceInFile(D, Loc))
907       return false; // already occurred.
908   }
909 
910   ScratchAlloc SA(*this);
911   EntityInfo RefEntity, ParentEntity;
912   getEntityInfo(D, RefEntity, SA);
913   if (!RefEntity.USR)
914     return false;
915 
916   getEntityInfo(Parent, ParentEntity, SA);
917 
918   ContainerInfo Container;
919   getContainerInfo(DC, Container);
920 
921   CXIdxEntityRefInfo Info = { Kind,
922                               Cursor,
923                               getIndexLoc(Loc),
924                               &RefEntity,
925                               Parent ? &ParentEntity : nullptr,
926                               &Container,
927                               Role };
928   CB.indexEntityReference(ClientData, &Info);
929   return true;
930 }
931 
isNotFromSourceFile(SourceLocation Loc) const932 bool CXIndexDataConsumer::isNotFromSourceFile(SourceLocation Loc) const {
933   if (Loc.isInvalid())
934     return true;
935   SourceManager &SM = Ctx->getSourceManager();
936   SourceLocation FileLoc = SM.getFileLoc(Loc);
937   FileID FID = SM.getFileID(FileLoc);
938   return SM.getFileEntryForID(FID) == nullptr;
939 }
940 
addContainerInMap(const DeclContext * DC,CXIdxClientContainer container)941 void CXIndexDataConsumer::addContainerInMap(const DeclContext *DC,
942                                         CXIdxClientContainer container) {
943   if (!DC)
944     return;
945 
946   ContainerMapTy::iterator I = ContainerMap.find(DC);
947   if (I == ContainerMap.end()) {
948     if (container)
949       ContainerMap[DC] = container;
950     return;
951   }
952   // Allow changing the container of a previously seen DeclContext so we
953   // can handle invalid user code, like a function re-definition.
954   if (container)
955     I->second = container;
956   else
957     ContainerMap.erase(I);
958 }
959 
getClientEntity(const Decl * D) const960 CXIdxClientEntity CXIndexDataConsumer::getClientEntity(const Decl *D) const {
961   if (!D)
962     return nullptr;
963   EntityMapTy::const_iterator I = EntityMap.find(D);
964   if (I == EntityMap.end())
965     return nullptr;
966   return I->second;
967 }
968 
setClientEntity(const Decl * D,CXIdxClientEntity client)969 void CXIndexDataConsumer::setClientEntity(const Decl *D, CXIdxClientEntity client) {
970   if (!D)
971     return;
972   EntityMap[D] = client;
973 }
974 
handleCXXRecordDecl(const CXXRecordDecl * RD,const NamedDecl * OrigD)975 bool CXIndexDataConsumer::handleCXXRecordDecl(const CXXRecordDecl *RD,
976                                           const NamedDecl *OrigD) {
977   if (RD->isThisDeclarationADefinition()) {
978     ScratchAlloc SA(*this);
979     CXXClassDeclInfo CXXDInfo(/*isRedeclaration=*/!OrigD->isCanonicalDecl(),
980                            /*isDefinition=*/RD->isThisDeclarationADefinition());
981     CXXBasesListInfo BaseList(RD, *this, SA);
982     CXXDInfo.CXXClassInfo.declInfo = &CXXDInfo;
983     CXXDInfo.CXXClassInfo.bases = BaseList.getBases();
984     CXXDInfo.CXXClassInfo.numBases = BaseList.getNumBases();
985 
986     if (shouldSuppressRefs()) {
987       // Go through bases and mark them as referenced.
988       for (unsigned i = 0, e = BaseList.getNumBases(); i != e; ++i) {
989         const CXIdxBaseClassInfo *baseInfo = BaseList.getBases()[i];
990         if (baseInfo->base) {
991           const NamedDecl *BaseD = BaseList.BaseEntities[i].Dcl;
992           SourceLocation
993             Loc = SourceLocation::getFromRawEncoding(baseInfo->loc.int_data);
994           markEntityOccurrenceInFile(BaseD, Loc);
995         }
996       }
997     }
998 
999     return handleDecl(OrigD, OrigD->getLocation(), getCursor(OrigD), CXXDInfo);
1000   }
1001 
1002   DeclInfo DInfo(/*isRedeclaration=*/!OrigD->isCanonicalDecl(),
1003                  /*isDefinition=*/RD->isThisDeclarationADefinition(),
1004                  /*isContainer=*/RD->isThisDeclarationADefinition());
1005   return handleDecl(OrigD, OrigD->getLocation(), getCursor(OrigD), DInfo);
1006 }
1007 
markEntityOccurrenceInFile(const NamedDecl * D,SourceLocation Loc)1008 bool CXIndexDataConsumer::markEntityOccurrenceInFile(const NamedDecl *D,
1009                                                  SourceLocation Loc) {
1010   if (!D || Loc.isInvalid())
1011     return true;
1012 
1013   SourceManager &SM = Ctx->getSourceManager();
1014   D = getEntityDecl(D);
1015 
1016   std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(SM.getFileLoc(Loc));
1017   FileID FID = LocInfo.first;
1018   if (FID.isInvalid())
1019     return true;
1020 
1021   const FileEntry *FE = SM.getFileEntryForID(FID);
1022   if (!FE)
1023     return true;
1024   RefFileOccurrence RefOccur(FE, D);
1025   std::pair<llvm::DenseSet<RefFileOccurrence>::iterator, bool>
1026   res = RefFileOccurrences.insert(RefOccur);
1027   return !res.second; // already in map
1028 }
1029 
getEntityDecl(const NamedDecl * D) const1030 const NamedDecl *CXIndexDataConsumer::getEntityDecl(const NamedDecl *D) const {
1031   assert(D);
1032   D = cast<NamedDecl>(D->getCanonicalDecl());
1033 
1034   if (const ObjCImplementationDecl *
1035                ImplD = dyn_cast<ObjCImplementationDecl>(D)) {
1036     return getEntityDecl(ImplD->getClassInterface());
1037 
1038   } else if (const ObjCCategoryImplDecl *
1039                CatImplD = dyn_cast<ObjCCategoryImplDecl>(D)) {
1040     return getEntityDecl(CatImplD->getCategoryDecl());
1041   } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1042     if (FunctionTemplateDecl *TemplD = FD->getDescribedFunctionTemplate())
1043       return getEntityDecl(TemplD);
1044   } else if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
1045     if (ClassTemplateDecl *TemplD = RD->getDescribedClassTemplate())
1046       return getEntityDecl(TemplD);
1047   }
1048 
1049   return D;
1050 }
1051 
1052 const DeclContext *
getEntityContainer(const Decl * D) const1053 CXIndexDataConsumer::getEntityContainer(const Decl *D) const {
1054   const DeclContext *DC = dyn_cast<DeclContext>(D);
1055   if (DC)
1056     return DC;
1057 
1058   if (const ClassTemplateDecl *ClassTempl = dyn_cast<ClassTemplateDecl>(D)) {
1059     DC = ClassTempl->getTemplatedDecl();
1060   } else if (const FunctionTemplateDecl *
1061           FuncTempl = dyn_cast<FunctionTemplateDecl>(D)) {
1062     DC = FuncTempl->getTemplatedDecl();
1063   }
1064 
1065   return DC;
1066 }
1067 
1068 CXIdxClientContainer
getClientContainerForDC(const DeclContext * DC) const1069 CXIndexDataConsumer::getClientContainerForDC(const DeclContext *DC) const {
1070   if (!DC)
1071     return nullptr;
1072 
1073   ContainerMapTy::const_iterator I = ContainerMap.find(DC);
1074   if (I == ContainerMap.end())
1075     return nullptr;
1076 
1077   return I->second;
1078 }
1079 
getIndexFile(const FileEntry * File)1080 CXIdxClientFile CXIndexDataConsumer::getIndexFile(const FileEntry *File) {
1081   if (!File)
1082     return nullptr;
1083 
1084   FileMapTy::iterator FI = FileMap.find(File);
1085   if (FI != FileMap.end())
1086     return FI->second;
1087 
1088   return nullptr;
1089 }
1090 
getIndexLoc(SourceLocation Loc) const1091 CXIdxLoc CXIndexDataConsumer::getIndexLoc(SourceLocation Loc) const {
1092   CXIdxLoc idxLoc =  { {nullptr, nullptr}, 0 };
1093   if (Loc.isInvalid())
1094     return idxLoc;
1095 
1096   idxLoc.ptr_data[0] = const_cast<CXIndexDataConsumer *>(this);
1097   idxLoc.int_data = Loc.getRawEncoding();
1098   return idxLoc;
1099 }
1100 
translateLoc(SourceLocation Loc,CXIdxClientFile * indexFile,CXFile * file,unsigned * line,unsigned * column,unsigned * offset)1101 void CXIndexDataConsumer::translateLoc(SourceLocation Loc,
1102                                    CXIdxClientFile *indexFile, CXFile *file,
1103                                    unsigned *line, unsigned *column,
1104                                    unsigned *offset) {
1105   if (Loc.isInvalid())
1106     return;
1107 
1108   SourceManager &SM = Ctx->getSourceManager();
1109   Loc = SM.getFileLoc(Loc);
1110 
1111   std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
1112   FileID FID = LocInfo.first;
1113   unsigned FileOffset = LocInfo.second;
1114 
1115   if (FID.isInvalid())
1116     return;
1117 
1118   const FileEntry *FE = SM.getFileEntryForID(FID);
1119   if (indexFile)
1120     *indexFile = getIndexFile(FE);
1121   if (file)
1122     *file = const_cast<FileEntry *>(FE);
1123   if (line)
1124     *line = SM.getLineNumber(FID, FileOffset);
1125   if (column)
1126     *column = SM.getColumnNumber(FID, FileOffset);
1127   if (offset)
1128     *offset = FileOffset;
1129 }
1130 
1131 static CXIdxEntityKind getEntityKindFromSymbolKind(SymbolKind K, SymbolLanguage L);
1132 static CXIdxEntityCXXTemplateKind
1133 getEntityKindFromSymbolProperties(SymbolPropertySet K);
1134 static CXIdxEntityLanguage getEntityLangFromSymbolLang(SymbolLanguage L);
1135 
getEntityInfo(const NamedDecl * D,EntityInfo & EntityInfo,ScratchAlloc & SA)1136 void CXIndexDataConsumer::getEntityInfo(const NamedDecl *D,
1137                                     EntityInfo &EntityInfo,
1138                                     ScratchAlloc &SA) {
1139   if (!D)
1140     return;
1141 
1142   D = getEntityDecl(D);
1143   EntityInfo.cursor = getCursor(D);
1144   EntityInfo.Dcl = D;
1145   EntityInfo.IndexCtx = this;
1146 
1147   SymbolInfo SymInfo = getSymbolInfo(D);
1148   EntityInfo.kind = getEntityKindFromSymbolKind(SymInfo.Kind, SymInfo.Lang);
1149   EntityInfo.templateKind = getEntityKindFromSymbolProperties(SymInfo.Properties);
1150   EntityInfo.lang = getEntityLangFromSymbolLang(SymInfo.Lang);
1151 
1152   if (D->hasAttrs()) {
1153     EntityInfo.AttrList = AttrListInfo::create(D, *this);
1154     EntityInfo.attributes = EntityInfo.AttrList->getAttrs();
1155     EntityInfo.numAttributes = EntityInfo.AttrList->getNumAttrs();
1156   }
1157 
1158   if (EntityInfo.kind == CXIdxEntity_Unexposed)
1159     return;
1160 
1161   if (IdentifierInfo *II = D->getIdentifier()) {
1162     EntityInfo.name = SA.toCStr(II->getName());
1163 
1164   } else if (isa<TagDecl>(D) || isa<FieldDecl>(D) || isa<NamespaceDecl>(D)) {
1165     EntityInfo.name = nullptr; // anonymous tag/field/namespace.
1166 
1167   } else {
1168     SmallString<256> StrBuf;
1169     {
1170       llvm::raw_svector_ostream OS(StrBuf);
1171       D->printName(OS);
1172     }
1173     EntityInfo.name = SA.copyCStr(StrBuf.str());
1174   }
1175 
1176   {
1177     SmallString<512> StrBuf;
1178     bool Ignore = getDeclCursorUSR(D, StrBuf);
1179     if (Ignore) {
1180       EntityInfo.USR = nullptr;
1181     } else {
1182       EntityInfo.USR = SA.copyCStr(StrBuf.str());
1183     }
1184   }
1185 }
1186 
getContainerInfo(const DeclContext * DC,ContainerInfo & ContInfo)1187 void CXIndexDataConsumer::getContainerInfo(const DeclContext *DC,
1188                                        ContainerInfo &ContInfo) {
1189   ContInfo.cursor = getCursor(cast<Decl>(DC));
1190   ContInfo.DC = DC;
1191   ContInfo.IndexCtx = this;
1192 }
1193 
getRefCursor(const NamedDecl * D,SourceLocation Loc)1194 CXCursor CXIndexDataConsumer::getRefCursor(const NamedDecl *D, SourceLocation Loc) {
1195   if (const TypeDecl *TD = dyn_cast<TypeDecl>(D))
1196     return MakeCursorTypeRef(TD, Loc, CXTU);
1197   if (const ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(D))
1198     return MakeCursorObjCClassRef(ID, Loc, CXTU);
1199   if (const ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D))
1200     return MakeCursorObjCProtocolRef(PD, Loc, CXTU);
1201   if (const TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
1202     return MakeCursorTemplateRef(Template, Loc, CXTU);
1203   if (const NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(D))
1204     return MakeCursorNamespaceRef(Namespace, Loc, CXTU);
1205   if (const NamespaceAliasDecl *Namespace = dyn_cast<NamespaceAliasDecl>(D))
1206     return MakeCursorNamespaceRef(Namespace, Loc, CXTU);
1207   if (const FieldDecl *Field = dyn_cast<FieldDecl>(D))
1208     return MakeCursorMemberRef(Field, Loc, CXTU);
1209   if (const VarDecl *Var = dyn_cast<VarDecl>(D))
1210     return MakeCursorVariableRef(Var, Loc, CXTU);
1211 
1212   return clang_getNullCursor();
1213 }
1214 
shouldIgnoreIfImplicit(const Decl * D)1215 bool CXIndexDataConsumer::shouldIgnoreIfImplicit(const Decl *D) {
1216   if (isa<ObjCInterfaceDecl>(D))
1217     return false;
1218   if (isa<ObjCCategoryDecl>(D))
1219     return false;
1220   if (isa<ObjCIvarDecl>(D))
1221     return false;
1222   if (isa<ObjCMethodDecl>(D))
1223     return false;
1224   if (isa<ImportDecl>(D))
1225     return false;
1226   return true;
1227 }
1228 
isTemplateImplicitInstantiation(const Decl * D)1229 bool CXIndexDataConsumer::isTemplateImplicitInstantiation(const Decl *D) {
1230   if (const ClassTemplateSpecializationDecl *
1231         SD = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
1232     return SD->getSpecializationKind() == TSK_ImplicitInstantiation;
1233   }
1234   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1235     return FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation;
1236   }
1237   return false;
1238 }
1239 
getEntityKindFromSymbolKind(SymbolKind K,SymbolLanguage Lang)1240 static CXIdxEntityKind getEntityKindFromSymbolKind(SymbolKind K, SymbolLanguage Lang) {
1241   switch (K) {
1242   case SymbolKind::Unknown:
1243   case SymbolKind::Module:
1244   case SymbolKind::Macro:
1245   case SymbolKind::ClassProperty:
1246   case SymbolKind::Using:
1247   case SymbolKind::TemplateTypeParm:
1248   case SymbolKind::TemplateTemplateParm:
1249   case SymbolKind::NonTypeTemplateParm:
1250     return CXIdxEntity_Unexposed;
1251 
1252   case SymbolKind::Enum: return CXIdxEntity_Enum;
1253   case SymbolKind::Struct: return CXIdxEntity_Struct;
1254   case SymbolKind::Union: return CXIdxEntity_Union;
1255   case SymbolKind::TypeAlias:
1256     if (Lang == SymbolLanguage::CXX)
1257       return CXIdxEntity_CXXTypeAlias;
1258     return CXIdxEntity_Typedef;
1259   case SymbolKind::Function: return CXIdxEntity_Function;
1260   case SymbolKind::Variable: return CXIdxEntity_Variable;
1261   case SymbolKind::Field:
1262     if (Lang == SymbolLanguage::ObjC)
1263       return CXIdxEntity_ObjCIvar;
1264     return CXIdxEntity_Field;
1265   case SymbolKind::EnumConstant: return CXIdxEntity_EnumConstant;
1266   case SymbolKind::Class:
1267     if (Lang == SymbolLanguage::ObjC)
1268       return CXIdxEntity_ObjCClass;
1269     return CXIdxEntity_CXXClass;
1270   case SymbolKind::Protocol:
1271     if (Lang == SymbolLanguage::ObjC)
1272       return CXIdxEntity_ObjCProtocol;
1273     return CXIdxEntity_CXXInterface;
1274   case SymbolKind::Extension: return CXIdxEntity_ObjCCategory;
1275   case SymbolKind::InstanceMethod:
1276     if (Lang == SymbolLanguage::ObjC)
1277       return CXIdxEntity_ObjCInstanceMethod;
1278     return CXIdxEntity_CXXInstanceMethod;
1279   case SymbolKind::ClassMethod: return CXIdxEntity_ObjCClassMethod;
1280   case SymbolKind::StaticMethod: return CXIdxEntity_CXXStaticMethod;
1281   case SymbolKind::InstanceProperty: return CXIdxEntity_ObjCProperty;
1282   case SymbolKind::StaticProperty: return CXIdxEntity_CXXStaticVariable;
1283   case SymbolKind::Namespace: return CXIdxEntity_CXXNamespace;
1284   case SymbolKind::NamespaceAlias: return CXIdxEntity_CXXNamespaceAlias;
1285   case SymbolKind::Constructor: return CXIdxEntity_CXXConstructor;
1286   case SymbolKind::Destructor: return CXIdxEntity_CXXDestructor;
1287   case SymbolKind::ConversionFunction: return CXIdxEntity_CXXConversionFunction;
1288   case SymbolKind::Parameter: return CXIdxEntity_Variable;
1289   }
1290   llvm_unreachable("invalid symbol kind");
1291 }
1292 
1293 static CXIdxEntityCXXTemplateKind
getEntityKindFromSymbolProperties(SymbolPropertySet K)1294 getEntityKindFromSymbolProperties(SymbolPropertySet K) {
1295   if (K & (SymbolPropertySet)SymbolProperty::TemplatePartialSpecialization)
1296     return CXIdxEntity_TemplatePartialSpecialization;
1297   if (K & (SymbolPropertySet)SymbolProperty::TemplateSpecialization)
1298     return CXIdxEntity_TemplateSpecialization;
1299   if (K & (SymbolPropertySet)SymbolProperty::Generic)
1300     return CXIdxEntity_Template;
1301   return CXIdxEntity_NonTemplate;
1302 }
1303 
getEntityLangFromSymbolLang(SymbolLanguage L)1304 static CXIdxEntityLanguage getEntityLangFromSymbolLang(SymbolLanguage L) {
1305   switch (L) {
1306   case SymbolLanguage::C: return CXIdxEntityLang_C;
1307   case SymbolLanguage::ObjC: return CXIdxEntityLang_ObjC;
1308   case SymbolLanguage::CXX: return CXIdxEntityLang_CXX;
1309   case SymbolLanguage::Swift: return CXIdxEntityLang_Swift;
1310   }
1311   llvm_unreachable("invalid symbol language");
1312 }
1313