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