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