IndexingContext.cpp revision 68478b0cc1ff03c0d13ceca6800c5becf08791e7
1//===- CIndexHigh.cpp - Higher level API functions ------------------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#include "IndexingContext.h"
11#include "CXTranslationUnit.h"
12#include "CIndexDiagnostic.h"
13
14#include "clang/Frontend/ASTUnit.h"
15#include "clang/AST/DeclCXX.h"
16#include "clang/AST/DeclTemplate.h"
17
18using namespace clang;
19using namespace cxindex;
20using namespace cxcursor;
21
22IndexingContext::ObjCProtocolListInfo::ObjCProtocolListInfo(
23                                    const ObjCProtocolList &ProtList,
24                                    IndexingContext &IdxCtx,
25                                    StrAdapter &SA) {
26  ObjCInterfaceDecl::protocol_loc_iterator LI = ProtList.loc_begin();
27  for (ObjCInterfaceDecl::protocol_iterator
28         I = ProtList.begin(), E = ProtList.end(); I != E; ++I, ++LI) {
29    SourceLocation Loc = *LI;
30    ObjCProtocolDecl *PD = *I;
31    ProtEntities.push_back(EntityInfo());
32    IdxCtx.getEntityInfo(PD, ProtEntities.back(), SA);
33    CXIdxObjCProtocolRefInfo ProtInfo = { 0,
34                                MakeCursorObjCProtocolRef(PD, Loc, IdxCtx.CXTU),
35                                IdxCtx.getIndexLoc(Loc) };
36    ProtInfos.push_back(ProtInfo);
37  }
38
39  for (unsigned i = 0, e = ProtInfos.size(); i != e; ++i)
40    ProtInfos[i].protocol = &ProtEntities[i];
41
42  for (unsigned i = 0, e = ProtInfos.size(); i != e; ++i)
43    Prots.push_back(&ProtInfos[i]);
44}
45
46IndexingContext::AttrListInfo::AttrListInfo(const Decl *D,
47                                            IndexingContext &IdxCtx,
48                                            StrAdapter &SA) {
49  for (AttrVec::const_iterator AttrI = D->attr_begin(), AttrE = D->attr_end();
50         AttrI != AttrE; ++AttrI) {
51    const Attr *A = *AttrI;
52    CXCursor C = MakeCXCursor(A, const_cast<Decl *>(D), IdxCtx.CXTU);
53    CXIdxLoc Loc =  IdxCtx.getIndexLoc(A->getLocation());
54    switch (C.kind) {
55    default:
56      Attrs.push_back(AttrInfo(CXIdxAttr_Unexposed, C, Loc, A));
57      break;
58    case CXCursor_IBActionAttr:
59      Attrs.push_back(AttrInfo(CXIdxAttr_IBAction, C, Loc, A));
60      break;
61    case CXCursor_IBOutletAttr:
62      Attrs.push_back(AttrInfo(CXIdxAttr_IBOutlet, C, Loc, A));
63      break;
64    case CXCursor_IBOutletCollectionAttr:
65      IBCollAttrs.push_back(IBOutletCollectionInfo(C, Loc, A));
66      break;
67    }
68  }
69
70  for (unsigned i = 0, e = IBCollAttrs.size(); i != e; ++i) {
71    IBOutletCollectionInfo &IBInfo = IBCollAttrs[i];
72    CXAttrs.push_back(&IBInfo);
73
74    const IBOutletCollectionAttr *
75      IBAttr = cast<IBOutletCollectionAttr>(IBInfo.A);
76    IBInfo.IBCollInfo.attrInfo = &IBInfo;
77    IBInfo.IBCollInfo.classLoc = IdxCtx.getIndexLoc(IBAttr->getInterfaceLoc());
78    IBInfo.IBCollInfo.objcClass = 0;
79    IBInfo.IBCollInfo.classCursor = clang_getNullCursor();
80    QualType Ty = IBAttr->getInterface();
81    if (const ObjCInterfaceType *InterTy = Ty->getAs<ObjCInterfaceType>()) {
82      if (const ObjCInterfaceDecl *InterD = InterTy->getInterface()) {
83        IdxCtx.getEntityInfo(InterD, IBInfo.ClassInfo, SA);
84        IBInfo.IBCollInfo.objcClass = &IBInfo.ClassInfo;
85        IBInfo.IBCollInfo.classCursor = MakeCursorObjCClassRef(InterD,
86                                        IBAttr->getInterfaceLoc(), IdxCtx.CXTU);
87      }
88    }
89  }
90
91  for (unsigned i = 0, e = Attrs.size(); i != e; ++i)
92    CXAttrs.push_back(&Attrs[i]);
93}
94
95IndexingContext::CXXBasesListInfo::CXXBasesListInfo(const CXXRecordDecl *D,
96                                   IndexingContext &IdxCtx,
97                                   IndexingContext::StrAdapter &SA) {
98  for (CXXRecordDecl::base_class_const_iterator
99         I = D->bases_begin(), E = D->bases_end(); I != E; ++I) {
100    const CXXBaseSpecifier &Base = *I;
101    BaseEntities.push_back(EntityInfo());
102    const NamedDecl *BaseD = 0;
103    if (const RecordType *RT = Base.getType()->getAs<RecordType>())
104      BaseD = RT->getDecl();
105    else if (const TypedefType *TDT = Base.getType()->getAs<TypedefType>())
106      BaseD = TDT->getDecl();
107    if (BaseD)
108      IdxCtx.getEntityInfo(BaseD, BaseEntities.back(), SA);
109    CXIdxBaseClassInfo BaseInfo = { 0,
110                         MakeCursorCXXBaseSpecifier(&Base, IdxCtx.CXTU),
111                         IdxCtx.getIndexLoc(Base.getSourceRange().getBegin()) };
112    BaseInfos.push_back(BaseInfo);
113  }
114
115  for (unsigned i = 0, e = BaseInfos.size(); i != e; ++i) {
116    if (BaseEntities[i].name && BaseEntities[i].USR)
117      BaseInfos[i].base = &BaseEntities[i];
118  }
119
120  for (unsigned i = 0, e = BaseInfos.size(); i != e; ++i)
121    CXBases.push_back(&BaseInfos[i]);
122}
123
124const char *IndexingContext::StrAdapter::toCStr(StringRef Str) {
125  if (Str.empty())
126    return "";
127  if (Str.data()[Str.size()] == '\0')
128    return Str.data();
129  return copyCStr(Str);
130}
131
132const char *IndexingContext::StrAdapter::copyCStr(StringRef Str) {
133  char *buf = IdxCtx.StrScratch.Allocate<char>(Str.size() + 1);
134  std::uninitialized_copy(Str.begin(), Str.end(), buf);
135  buf[Str.size()] = '\0';
136  return buf;
137}
138
139void IndexingContext::setASTContext(ASTContext &ctx) {
140  Ctx = &ctx;
141  static_cast<ASTUnit*>(CXTU->TUData)->setASTContext(&ctx);
142}
143
144bool IndexingContext::shouldAbort() {
145  if (!CB.abortQuery)
146    return false;
147  return CB.abortQuery(ClientData, 0);
148}
149
150void IndexingContext::enteredMainFile(const FileEntry *File) {
151  if (File && CB.enteredMainFile) {
152    CXIdxClientFile idxFile = CB.enteredMainFile(ClientData, (CXFile)File, 0);
153    FileMap[File] = idxFile;
154  }
155}
156
157void IndexingContext::ppIncludedFile(SourceLocation hashLoc,
158                                     StringRef filename,
159                                     const FileEntry *File,
160                                     bool isImport, bool isAngled) {
161  if (!CB.ppIncludedFile)
162    return;
163
164  StrAdapter SA(*this);
165  CXIdxIncludedFileInfo Info = { getIndexLoc(hashLoc),
166                                 SA.toCStr(filename),
167                                 (CXFile)File,
168                                 isImport, isAngled };
169  CXIdxClientFile idxFile = CB.ppIncludedFile(ClientData, &Info);
170  FileMap[File] = idxFile;
171}
172
173void IndexingContext::startedTranslationUnit() {
174  CXIdxClientContainer idxCont = 0;
175  if (CB.startedTranslationUnit)
176    idxCont = CB.startedTranslationUnit(ClientData, 0);
177  addContainerInMap(Ctx->getTranslationUnitDecl(), idxCont);
178}
179
180void IndexingContext::handleDiagnosticSet(CXDiagnostic CXDiagSet) {
181  if (!CB.diagnostic)
182    return;
183
184  CB.diagnostic(ClientData, CXDiagSet, 0);
185}
186
187bool IndexingContext::handleDecl(const NamedDecl *D,
188                                 SourceLocation Loc, CXCursor Cursor,
189                                 DeclInfo &DInfo) {
190  if (!CB.indexDeclaration || !D)
191    return false;
192  if (D->isImplicit() && shouldIgnoreIfImplicit(D))
193    return false;
194
195  StrAdapter SA(*this);
196  getEntityInfo(D, DInfo.EntInfo, SA);
197  if (!DInfo.EntInfo.USR || Loc.isInvalid())
198    return false;
199
200  markEntityOccurrenceInFile(D, Loc);
201
202  DInfo.entityInfo = &DInfo.EntInfo;
203  DInfo.cursor = Cursor;
204  DInfo.loc = getIndexLoc(Loc);
205  DInfo.isImplicit = D->isImplicit();
206
207  AttrListInfo AttrList(D, *this, SA);
208  DInfo.attributes = AttrList.getAttrs();
209  DInfo.numAttributes = AttrList.getNumAttrs();
210
211  getContainerInfo(D->getDeclContext(), DInfo.Container);
212  DInfo.container = &DInfo.Container;
213  if (DInfo.isContainer) {
214    getContainerInfo(getEntityContainer(D), DInfo.DeclAsContainer);
215    DInfo.declAsContainer = &DInfo.DeclAsContainer;
216  }
217
218  CB.indexDeclaration(ClientData, &DInfo);
219  return true;
220}
221
222bool IndexingContext::handleObjCContainer(const ObjCContainerDecl *D,
223                                          SourceLocation Loc, CXCursor Cursor,
224                                          ObjCContainerDeclInfo &ContDInfo) {
225  ContDInfo.ObjCContDeclInfo.declInfo = &ContDInfo;
226  return handleDecl(D, Loc, Cursor, ContDInfo);
227}
228
229bool IndexingContext::handleFunction(const FunctionDecl *D) {
230  DeclInfo DInfo(!D->isFirstDeclaration(), D->isThisDeclarationADefinition(),
231                 D->isThisDeclarationADefinition());
232  return handleDecl(D, D->getLocation(), getCursor(D), DInfo);
233}
234
235bool IndexingContext::handleVar(const VarDecl *D) {
236  DeclInfo DInfo(!D->isFirstDeclaration(), D->isThisDeclarationADefinition(),
237                 /*isContainer=*/false);
238  return handleDecl(D, D->getLocation(), getCursor(D), DInfo);
239}
240
241bool IndexingContext::handleField(const FieldDecl *D) {
242  DeclInfo DInfo(/*isRedeclaration=*/false, /*isDefinition=*/true,
243                 /*isContainer=*/false);
244  return handleDecl(D, D->getLocation(), getCursor(D), DInfo);
245}
246
247bool IndexingContext::handleEnumerator(const EnumConstantDecl *D) {
248  DeclInfo DInfo(/*isRedeclaration=*/false, /*isDefinition=*/true,
249                 /*isContainer=*/false);
250  return handleDecl(D, D->getLocation(), getCursor(D), DInfo);
251}
252
253bool IndexingContext::handleTagDecl(const TagDecl *D) {
254  if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(D))
255    return handleCXXRecordDecl(CXXRD, D);
256
257  DeclInfo DInfo(!D->isFirstDeclaration(), D->isThisDeclarationADefinition(),
258                 D->isThisDeclarationADefinition());
259  return handleDecl(D, D->getLocation(), getCursor(D), DInfo);
260}
261
262bool IndexingContext::handleTypedefName(const TypedefNameDecl *D) {
263  DeclInfo DInfo(!D->isFirstDeclaration(), /*isDefinition=*/true,
264                 /*isContainer=*/false);
265  return handleDecl(D, D->getLocation(), getCursor(D), DInfo);
266}
267
268bool IndexingContext::handleObjCClass(const ObjCClassDecl *D) {
269  const ObjCClassDecl::ObjCClassRef *Ref = D->getForwardDecl();
270  ObjCInterfaceDecl *IFaceD = Ref->getInterface();
271  SourceLocation Loc = Ref->getLocation();
272  bool isRedeclaration = IFaceD->getLocation() != Loc;
273
274  ObjCContainerDeclInfo ContDInfo(/*isForwardRef=*/true, isRedeclaration,
275                                  /*isImplementation=*/false);
276  return handleObjCContainer(IFaceD, Loc,
277                          MakeCursorObjCClassRef(IFaceD, Loc, CXTU), ContDInfo);
278}
279
280bool IndexingContext::handleObjCInterface(const ObjCInterfaceDecl *D) {
281  StrAdapter SA(*this);
282
283  CXIdxBaseClassInfo BaseClass;
284  EntityInfo BaseEntity;
285  BaseClass.cursor = clang_getNullCursor();
286  if (ObjCInterfaceDecl *SuperD = D->getSuperClass()) {
287    getEntityInfo(SuperD, BaseEntity, SA);
288    SourceLocation SuperLoc = D->getSuperClassLoc();
289    BaseClass.base = &BaseEntity;
290    BaseClass.cursor = MakeCursorObjCSuperClassRef(SuperD, SuperLoc, CXTU);
291    BaseClass.loc = getIndexLoc(SuperLoc);
292  }
293
294  ObjCProtocolListInfo ProtInfo(D->getReferencedProtocols(), *this, SA);
295
296  ObjCInterfaceDeclInfo InterInfo(D);
297  InterInfo.ObjCProtoListInfo = ProtInfo.getListInfo();
298  InterInfo.ObjCInterDeclInfo.containerInfo = &InterInfo.ObjCContDeclInfo;
299  InterInfo.ObjCInterDeclInfo.superInfo = D->getSuperClass() ? &BaseClass : 0;
300  InterInfo.ObjCInterDeclInfo.protocols = &InterInfo.ObjCProtoListInfo;
301
302  return handleObjCContainer(D, D->getLocation(), getCursor(D), InterInfo);
303}
304
305bool IndexingContext::handleObjCImplementation(
306                                              const ObjCImplementationDecl *D) {
307  ObjCContainerDeclInfo ContDInfo(/*isForwardRef=*/false,
308                      /*isRedeclaration=*/true,
309                      /*isImplementation=*/true);
310  return handleObjCContainer(D, D->getLocation(), getCursor(D), ContDInfo);
311}
312
313bool IndexingContext::handleObjCForwardProtocol(const ObjCProtocolDecl *D,
314                                                SourceLocation Loc,
315                                                bool isRedeclaration) {
316  ObjCContainerDeclInfo ContDInfo(/*isForwardRef=*/true,
317                                  isRedeclaration,
318                                  /*isImplementation=*/false);
319  return handleObjCContainer(D, Loc, MakeCursorObjCProtocolRef(D, Loc, CXTU),
320                             ContDInfo);
321}
322
323bool IndexingContext::handleObjCProtocol(const ObjCProtocolDecl *D) {
324  StrAdapter SA(*this);
325  ObjCProtocolListInfo ProtListInfo(D->getReferencedProtocols(), *this, SA);
326
327  ObjCProtocolDeclInfo ProtInfo(D);
328  ProtInfo.ObjCProtoRefListInfo = ProtListInfo.getListInfo();
329
330  return handleObjCContainer(D, D->getLocation(), getCursor(D), ProtInfo);
331}
332
333bool IndexingContext::handleObjCCategory(const ObjCCategoryDecl *D) {
334  ObjCCategoryDeclInfo CatDInfo(/*isImplementation=*/false);
335  EntityInfo ClassEntity;
336  StrAdapter SA(*this);
337  const ObjCInterfaceDecl *IFaceD = D->getClassInterface();
338  SourceLocation ClassLoc = D->getLocation();
339  SourceLocation CategoryLoc = D->IsClassExtension() ? ClassLoc
340                                                     : D->getCategoryNameLoc();
341  getEntityInfo(IFaceD, ClassEntity, SA);
342
343  CatDInfo.ObjCCatDeclInfo.containerInfo = &CatDInfo.ObjCContDeclInfo;
344  if (IFaceD) {
345    CatDInfo.ObjCCatDeclInfo.objcClass = &ClassEntity;
346    CatDInfo.ObjCCatDeclInfo.classCursor =
347        MakeCursorObjCClassRef(IFaceD, ClassLoc, CXTU);
348  } else {
349    CatDInfo.ObjCCatDeclInfo.objcClass = 0;
350    CatDInfo.ObjCCatDeclInfo.classCursor = clang_getNullCursor();
351  }
352  CatDInfo.ObjCCatDeclInfo.classLoc = getIndexLoc(ClassLoc);
353  return handleObjCContainer(D, CategoryLoc, getCursor(D), CatDInfo);
354}
355
356bool IndexingContext::handleObjCCategoryImpl(const ObjCCategoryImplDecl *D) {
357  const ObjCCategoryDecl *CatD = D->getCategoryDecl();
358  ObjCCategoryDeclInfo CatDInfo(/*isImplementation=*/true);
359  EntityInfo ClassEntity;
360  StrAdapter SA(*this);
361  const ObjCInterfaceDecl *IFaceD = CatD->getClassInterface();
362  SourceLocation ClassLoc = D->getLocation();
363  SourceLocation CategoryLoc = ClassLoc; //FIXME: D->getCategoryNameLoc();
364  getEntityInfo(IFaceD, ClassEntity, SA);
365
366  CatDInfo.ObjCCatDeclInfo.containerInfo = &CatDInfo.ObjCContDeclInfo;
367  if (IFaceD) {
368    CatDInfo.ObjCCatDeclInfo.objcClass = &ClassEntity;
369    CatDInfo.ObjCCatDeclInfo.classCursor =
370        MakeCursorObjCClassRef(IFaceD, ClassLoc, CXTU);
371  } else {
372    CatDInfo.ObjCCatDeclInfo.objcClass = 0;
373    CatDInfo.ObjCCatDeclInfo.classCursor = clang_getNullCursor();
374  }
375  CatDInfo.ObjCCatDeclInfo.classLoc = getIndexLoc(ClassLoc);
376  return handleObjCContainer(D, CategoryLoc, getCursor(D), CatDInfo);
377}
378
379bool IndexingContext::handleObjCMethod(const ObjCMethodDecl *D) {
380  DeclInfo DInfo(!D->isCanonicalDecl(), D->isThisDeclarationADefinition(),
381                 D->isThisDeclarationADefinition());
382  return handleDecl(D, D->getLocation(), getCursor(D), DInfo);
383}
384
385bool IndexingContext::handleSynthesizedObjCProperty(
386                                                const ObjCPropertyImplDecl *D) {
387  ObjCPropertyDecl *PD = D->getPropertyDecl();
388  return handleReference(PD, D->getLocation(), getCursor(D), 0, D->getDeclContext());
389}
390
391bool IndexingContext::handleSynthesizedObjCMethod(const ObjCMethodDecl *D,
392                                                  SourceLocation Loc) {
393  DeclInfo DInfo(/*isRedeclaration=*/true, /*isDefinition=*/true,
394                 /*isContainer=*/false);
395  return handleDecl(D, Loc, getCursor(D), DInfo);
396}
397
398bool IndexingContext::handleObjCProperty(const ObjCPropertyDecl *D) {
399  DeclInfo DInfo(/*isRedeclaration=*/false, /*isDefinition=*/false,
400                 /*isContainer=*/false);
401  return handleDecl(D, D->getLocation(), getCursor(D), DInfo);
402}
403
404bool IndexingContext::handleNamespace(const NamespaceDecl *D) {
405  DeclInfo DInfo(/*isRedeclaration=*/!D->isOriginalNamespace(),
406                 /*isDefinition=*/true,
407                 /*isContainer=*/true);
408  return handleDecl(D, D->getLocation(), getCursor(D), DInfo);
409}
410
411bool IndexingContext::handleClassTemplate(const ClassTemplateDecl *D) {
412  return handleCXXRecordDecl(D->getTemplatedDecl(), D);
413}
414
415bool IndexingContext::handleFunctionTemplate(const FunctionTemplateDecl *D) {
416  DeclInfo DInfo(/*isRedeclaration=*/!D->isCanonicalDecl(),
417                 /*isDefinition=*/D->isThisDeclarationADefinition(),
418                 /*isContainer=*/D->isThisDeclarationADefinition());
419  return handleDecl(D, D->getLocation(), getCursor(D), DInfo);
420}
421
422bool IndexingContext::handleTypeAliasTemplate(const TypeAliasTemplateDecl *D) {
423  DeclInfo DInfo(/*isRedeclaration=*/!D->isCanonicalDecl(),
424                 /*isDefinition=*/true, /*isContainer=*/false);
425  return handleDecl(D, D->getLocation(), getCursor(D), DInfo);
426}
427
428bool IndexingContext::handleReference(const NamedDecl *D, SourceLocation Loc,
429                                      const NamedDecl *Parent,
430                                      const DeclContext *DC,
431                                      const Expr *E,
432                                      CXIdxEntityRefKind Kind) {
433  if (!D)
434    return false;
435
436  CXCursor Cursor = E ? MakeCXCursor(const_cast<Expr*>(E),
437                                     const_cast<Decl*>(cast<Decl>(DC)), CXTU)
438                      : getRefCursor(D, Loc);
439  return handleReference(D, Loc, Cursor, Parent, DC, E, Kind);
440}
441
442bool IndexingContext::handleReference(const NamedDecl *D, SourceLocation Loc,
443                                      CXCursor Cursor,
444                                      const NamedDecl *Parent,
445                                      const DeclContext *DC,
446                                      const Expr *E,
447                                      CXIdxEntityRefKind Kind) {
448  if (!CB.indexEntityReference)
449    return false;
450
451  if (!D)
452    return false;
453  if (Loc.isInvalid())
454    return false;
455  if (D->getParentFunctionOrMethod())
456    return false;
457  if (isNotFromSourceFile(D->getLocation()))
458    return false;
459  if (D->isImplicit() && shouldIgnoreIfImplicit(D))
460    return false;
461
462  if (suppressRefs()) {
463    if (markEntityOccurrenceInFile(D, Loc))
464      return false; // already occurred.
465  }
466
467  StrAdapter SA(*this);
468  EntityInfo RefEntity, ParentEntity;
469  getEntityInfo(D, RefEntity, SA);
470  if (!RefEntity.USR)
471    return false;
472
473  getEntityInfo(Parent, ParentEntity, SA);
474
475  ContainerInfo Container;
476  getContainerInfo(DC, Container);
477
478  CXIdxEntityRefInfo Info = { Cursor,
479                              getIndexLoc(Loc),
480                              &RefEntity,
481                              Parent ? &ParentEntity : 0,
482                              &Container,
483                              Kind };
484  CB.indexEntityReference(ClientData, &Info);
485  return true;
486}
487
488bool IndexingContext::isNotFromSourceFile(SourceLocation Loc) const {
489  if (Loc.isInvalid())
490    return true;
491  SourceManager &SM = Ctx->getSourceManager();
492  SourceLocation FileLoc = SM.getFileLoc(Loc);
493  FileID FID = SM.getFileID(FileLoc);
494  return SM.getFileEntryForID(FID) == 0;
495}
496
497void IndexingContext::addContainerInMap(const DeclContext *DC,
498                                        CXIdxClientContainer container) {
499  if (!DC)
500    return;
501
502  assert(getScopedContext(DC) == DC);
503  ContainerMapTy::iterator I = ContainerMap.find(DC);
504  if (I == ContainerMap.end()) {
505    if (container)
506      ContainerMap[DC] = container;
507    return;
508  }
509  // Allow changing the container of a previously seen DeclContext so we
510  // can handle invalid user code, like a function re-definition.
511  if (container)
512    I->second = container;
513  else
514    ContainerMap.erase(I);
515}
516
517CXIdxClientEntity IndexingContext::getClientEntity(const Decl *D) const {
518  if (!D)
519    return 0;
520  EntityMapTy::const_iterator I = EntityMap.find(D);
521  if (I == EntityMap.end())
522    return 0;
523  return I->second;
524}
525
526void IndexingContext::setClientEntity(const Decl *D, CXIdxClientEntity client) {
527  if (!D)
528    return;
529  EntityMap[D] = client;
530}
531
532bool IndexingContext::handleCXXRecordDecl(const CXXRecordDecl *RD,
533                                          const NamedDecl *OrigD) {
534  if (RD->isThisDeclarationADefinition()) {
535    StrAdapter SA(*this);
536    CXXClassDeclInfo CXXDInfo(/*isRedeclaration=*/!OrigD->isCanonicalDecl(),
537                           /*isDefinition=*/RD->isThisDeclarationADefinition());
538    CXXBasesListInfo BaseList(RD, *this, SA);
539    CXXDInfo.CXXClassInfo.declInfo = &CXXDInfo;
540    CXXDInfo.CXXClassInfo.bases = BaseList.getBases();
541    CXXDInfo.CXXClassInfo.numBases = BaseList.getNumBases();
542
543    return handleDecl(OrigD, OrigD->getLocation(), getCursor(OrigD), CXXDInfo);
544  }
545
546  DeclInfo DInfo(/*isRedeclaration=*/!OrigD->isCanonicalDecl(),
547                 /*isDefinition=*/RD->isThisDeclarationADefinition(),
548                 /*isContainer=*/RD->isThisDeclarationADefinition());
549  return handleDecl(OrigD, OrigD->getLocation(), getCursor(OrigD), DInfo);
550}
551
552bool IndexingContext::markEntityOccurrenceInFile(const NamedDecl *D,
553                                                 SourceLocation Loc) {
554  SourceManager &SM = Ctx->getSourceManager();
555  D = getEntityDecl(D);
556
557  std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
558  FileID FID = LocInfo.first;
559  if (FID.isInvalid())
560    return true;
561
562  const FileEntry *FE = SM.getFileEntryForID(FID);
563  if (!FE)
564    return true;
565  RefFileOccurence RefOccur(FE, D);
566  std::pair<llvm::DenseSet<RefFileOccurence>::iterator, bool>
567  res = RefFileOccurences.insert(RefOccur);
568  if (!res.second)
569    return true; // already in map.
570
571  return false;
572}
573
574const NamedDecl *IndexingContext::getEntityDecl(const NamedDecl *D) const {
575  assert(D);
576  D = cast<NamedDecl>(D->getCanonicalDecl());
577
578  if (const ObjCImplementationDecl *
579               ImplD = dyn_cast<ObjCImplementationDecl>(D)) {
580    return getEntityDecl(ImplD->getClassInterface());
581
582  } else if (const ObjCCategoryImplDecl *
583               CatImplD = dyn_cast<ObjCCategoryImplDecl>(D)) {
584    return getEntityDecl(CatImplD->getCategoryDecl());
585  } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
586    if (FunctionTemplateDecl *TemplD = FD->getDescribedFunctionTemplate())
587      return getEntityDecl(TemplD);
588  } else if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
589    if (ClassTemplateDecl *TemplD = RD->getDescribedClassTemplate())
590      return getEntityDecl(TemplD);
591  }
592
593  return D;
594}
595
596const DeclContext *
597IndexingContext::getEntityContainer(const Decl *D) const {
598  const DeclContext *DC = dyn_cast<DeclContext>(D);
599  if (DC)
600    return DC;
601
602  if (const ClassTemplateDecl *ClassTempl = dyn_cast<ClassTemplateDecl>(D)) {
603    DC = ClassTempl->getTemplatedDecl();
604  } if (const FunctionTemplateDecl *
605          FuncTempl = dyn_cast<FunctionTemplateDecl>(D)) {
606    DC = FuncTempl->getTemplatedDecl();
607  }
608
609  return DC;
610}
611
612const DeclContext *
613IndexingContext::getScopedContext(const DeclContext *DC) const {
614  // Local contexts are ignored for indexing.
615  const DeclContext *FuncCtx = cast<Decl>(DC)->getParentFunctionOrMethod();
616  if (FuncCtx)
617    return FuncCtx;
618
619  // We consider enums always scoped for indexing.
620  if (isa<TagDecl>(DC))
621    return DC;
622
623  if (const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(DC)) {
624    if (NS->isAnonymousNamespace())
625      return getScopedContext(NS->getParent());
626    return NS;
627  }
628
629  return DC->getRedeclContext();
630}
631
632CXIdxClientContainer
633IndexingContext::getClientContainerForDC(const DeclContext *DC) const {
634  if (!DC)
635    return 0;
636
637  DC = getScopedContext(DC);
638  ContainerMapTy::const_iterator I = ContainerMap.find(DC);
639  if (I == ContainerMap.end())
640    return 0;
641
642  return I->second;
643}
644
645CXIdxClientFile IndexingContext::getIndexFile(const FileEntry *File) {
646  if (!File)
647    return 0;
648
649  FileMapTy::iterator FI = FileMap.find(File);
650  if (FI != FileMap.end())
651    return FI->second;
652
653  return 0;
654}
655
656CXIdxLoc IndexingContext::getIndexLoc(SourceLocation Loc) const {
657  CXIdxLoc idxLoc =  { {0, 0}, 0 };
658  if (Loc.isInvalid())
659    return idxLoc;
660
661  idxLoc.ptr_data[0] = (void*)this;
662  idxLoc.int_data = Loc.getRawEncoding();
663  return idxLoc;
664}
665
666void IndexingContext::translateLoc(SourceLocation Loc,
667                                   CXIdxClientFile *indexFile, CXFile *file,
668                                   unsigned *line, unsigned *column,
669                                   unsigned *offset) {
670  if (Loc.isInvalid())
671    return;
672
673  SourceManager &SM = Ctx->getSourceManager();
674  Loc = SM.getFileLoc(Loc);
675
676  std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
677  FileID FID = LocInfo.first;
678  unsigned FileOffset = LocInfo.second;
679
680  if (FID.isInvalid())
681    return;
682
683  const FileEntry *FE = SM.getFileEntryForID(FID);
684  if (indexFile)
685    *indexFile = getIndexFile(FE);
686  if (file)
687    *file = (void *)FE;
688  if (line)
689    *line = SM.getLineNumber(FID, FileOffset);
690  if (column)
691    *column = SM.getColumnNumber(FID, FileOffset);
692  if (offset)
693    *offset = FileOffset;
694}
695
696void IndexingContext::getEntityInfo(const NamedDecl *D,
697                                    EntityInfo &EntityInfo,
698                                    StrAdapter &SA) {
699  if (!D)
700    return;
701
702  D = getEntityDecl(D);
703  EntityInfo.cursor = getCursor(D);
704  EntityInfo.Dcl = D;
705  EntityInfo.IndexCtx = this;
706  EntityInfo.kind = CXIdxEntity_Unexposed;
707  EntityInfo.templateKind = CXIdxEntity_NonTemplate;
708
709  if (const TagDecl *TD = dyn_cast<TagDecl>(D)) {
710    switch (TD->getTagKind()) {
711    case TTK_Struct:
712      EntityInfo.kind = CXIdxEntity_Struct; break;
713    case TTK_Union:
714      EntityInfo.kind = CXIdxEntity_Union; break;
715    case TTK_Class:
716      EntityInfo.kind = CXIdxEntity_CXXClass; break;
717    case TTK_Enum:
718      EntityInfo.kind = CXIdxEntity_Enum; break;
719    }
720
721    if (const CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(D)) {
722      if (TD->getTagKind() == TTK_Struct &&
723          CXXRec->hasDefinition() && !CXXRec->isPOD())
724        EntityInfo.kind = CXIdxEntity_CXXClass;
725    }
726
727    if (isa<ClassTemplatePartialSpecializationDecl>(D)) {
728      EntityInfo.templateKind = CXIdxEntity_TemplatePartialSpecialization;
729    } else if (isa<ClassTemplateSpecializationDecl>(D)) {
730      EntityInfo.templateKind = CXIdxEntity_TemplateSpecialization;
731    }
732
733  } else {
734    switch (D->getKind()) {
735    case Decl::Typedef:
736      EntityInfo.kind = CXIdxEntity_Typedef; break;
737    case Decl::Function:
738      EntityInfo.kind = CXIdxEntity_Function;
739      break;
740    case Decl::Var:
741      EntityInfo.kind = CXIdxEntity_Variable;
742      if (isa<CXXRecordDecl>(D->getDeclContext()))
743        EntityInfo.kind = CXIdxEntity_CXXStaticVariable;
744      break;
745    case Decl::Field:
746      EntityInfo.kind = CXIdxEntity_Field;
747      if (const CXXRecordDecl *
748            CXXRec = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
749        if (!CXXRec->isPOD())
750          EntityInfo.kind = CXIdxEntity_CXXInstanceVariable;
751      break;
752    case Decl::EnumConstant:
753      EntityInfo.kind = CXIdxEntity_EnumConstant; break;
754    case Decl::ObjCInterface:
755      EntityInfo.kind = CXIdxEntity_ObjCClass; break;
756    case Decl::ObjCProtocol:
757      EntityInfo.kind = CXIdxEntity_ObjCProtocol; break;
758    case Decl::ObjCCategory:
759      EntityInfo.kind = CXIdxEntity_ObjCCategory; break;
760    case Decl::ObjCMethod:
761      if (cast<ObjCMethodDecl>(D)->isInstanceMethod())
762        EntityInfo.kind = CXIdxEntity_ObjCInstanceMethod;
763      else
764        EntityInfo.kind = CXIdxEntity_ObjCClassMethod;
765      break;
766    case Decl::ObjCProperty:
767      EntityInfo.kind = CXIdxEntity_ObjCProperty; break;
768    case Decl::ObjCIvar:
769      EntityInfo.kind = CXIdxEntity_ObjCIvar; break;
770    case Decl::Namespace:
771      EntityInfo.kind = CXIdxEntity_CXXNamespace; break;
772    case Decl::NamespaceAlias:
773      EntityInfo.kind = CXIdxEntity_CXXNamespaceAlias; break;
774    case Decl::CXXConstructor:
775      EntityInfo.kind = CXIdxEntity_CXXConstructor; break;
776    case Decl::CXXDestructor:
777      EntityInfo.kind = CXIdxEntity_CXXDestructor; break;
778    case Decl::CXXConversion:
779      EntityInfo.kind = CXIdxEntity_CXXConversionFunction; break;
780    case Decl::CXXMethod: {
781      const CXXMethodDecl *MD = cast<CXXMethodDecl>(D);
782      if (MD->isStatic())
783        EntityInfo.kind = CXIdxEntity_CXXStaticMethod;
784      else
785        EntityInfo.kind = CXIdxEntity_CXXInstanceMethod;
786      break;
787    }
788    case Decl::ClassTemplate:
789      EntityInfo.kind = CXIdxEntity_CXXClass;
790      EntityInfo.templateKind = CXIdxEntity_Template;
791      break;
792    case Decl::FunctionTemplate:
793      EntityInfo.kind = CXIdxEntity_Function;
794      EntityInfo.templateKind = CXIdxEntity_Template;
795      if (const CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(
796                           cast<FunctionTemplateDecl>(D)->getTemplatedDecl())) {
797        if (isa<CXXConstructorDecl>(MD))
798          EntityInfo.kind = CXIdxEntity_CXXConstructor;
799        else if (isa<CXXDestructorDecl>(MD))
800          EntityInfo.kind = CXIdxEntity_CXXDestructor;
801        else if (isa<CXXConversionDecl>(MD))
802          EntityInfo.kind = CXIdxEntity_CXXConversionFunction;
803        else {
804          if (MD->isStatic())
805            EntityInfo.kind = CXIdxEntity_CXXStaticMethod;
806          else
807            EntityInfo.kind = CXIdxEntity_CXXInstanceMethod;
808        }
809      }
810      break;
811    case Decl::TypeAliasTemplate:
812      EntityInfo.kind = CXIdxEntity_CXXTypeAlias;
813      EntityInfo.templateKind = CXIdxEntity_Template;
814      break;
815    case Decl::TypeAlias:
816      EntityInfo.kind = CXIdxEntity_CXXTypeAlias; break;
817    default:
818      break;
819    }
820  }
821
822  if (EntityInfo.kind == CXIdxEntity_Unexposed)
823    return;
824
825  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
826    if (FD->getTemplatedKind() ==
827          FunctionDecl::TK_FunctionTemplateSpecialization)
828      EntityInfo.templateKind = CXIdxEntity_TemplateSpecialization;
829  }
830
831  if (IdentifierInfo *II = D->getIdentifier()) {
832    EntityInfo.name = SA.toCStr(II->getName());
833
834  } else if (isa<TagDecl>(D) || isa<FieldDecl>(D) || isa<NamespaceDecl>(D)) {
835    EntityInfo.name = 0; // anonymous tag/field/namespace.
836
837  } else {
838    llvm::SmallString<256> StrBuf;
839    {
840      llvm::raw_svector_ostream OS(StrBuf);
841      D->printName(OS);
842    }
843    EntityInfo.name = SA.copyCStr(StrBuf.str());
844  }
845
846  {
847    llvm::SmallString<512> StrBuf;
848    bool Ignore = getDeclCursorUSR(D, StrBuf);
849    if (Ignore) {
850      EntityInfo.USR = 0;
851    } else {
852      EntityInfo.USR = SA.copyCStr(StrBuf.str());
853    }
854  }
855}
856
857void IndexingContext::getContainerInfo(const DeclContext *DC,
858                                       ContainerInfo &ContInfo) {
859  ContInfo.cursor = getCursor(cast<Decl>(DC));
860  ContInfo.DC = DC;
861  ContInfo.IndexCtx = this;
862}
863
864CXCursor IndexingContext::getRefCursor(const NamedDecl *D, SourceLocation Loc) {
865  if (const TypeDecl *TD = dyn_cast<TypeDecl>(D))
866    return MakeCursorTypeRef(TD, Loc, CXTU);
867  if (const ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(D))
868    return MakeCursorObjCClassRef(ID, Loc, CXTU);
869  if (const ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D))
870    return MakeCursorObjCProtocolRef(PD, Loc, CXTU);
871  if (const TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
872    return MakeCursorTemplateRef(Template, Loc, CXTU);
873  if (const NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(D))
874    return MakeCursorNamespaceRef(Namespace, Loc, CXTU);
875  if (const NamespaceAliasDecl *Namespace = dyn_cast<NamespaceAliasDecl>(D))
876    return MakeCursorNamespaceRef(Namespace, Loc, CXTU);
877  if (const FieldDecl *Field = dyn_cast<FieldDecl>(D))
878    return MakeCursorMemberRef(Field, Loc, CXTU);
879
880  return clang_getNullCursor();
881}
882
883bool IndexingContext::shouldIgnoreIfImplicit(const NamedDecl *D) {
884  if (isa<ObjCInterfaceDecl>(D))
885    return false;
886  if (isa<ObjCCategoryDecl>(D))
887    return false;
888  if (isa<ObjCIvarDecl>(D))
889    return false;
890  if (isa<ObjCMethodDecl>(D))
891    return false;
892  return true;
893}
894