IndexingContext.cpp revision 55d23c925b058be29b792008ddb7d68f6c4fa9a0
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    return handleDecl(OrigD, OrigD->getLocation(), getCursor(OrigD), CXXDInfo);
650  }
651
652  DeclInfo DInfo(/*isRedeclaration=*/!OrigD->isCanonicalDecl(),
653                 /*isDefinition=*/RD->isThisDeclarationADefinition(),
654                 /*isContainer=*/RD->isThisDeclarationADefinition());
655  return handleDecl(OrigD, OrigD->getLocation(), getCursor(OrigD), DInfo);
656}
657
658bool IndexingContext::markEntityOccurrenceInFile(const NamedDecl *D,
659                                                 SourceLocation Loc) {
660  if (!D || Loc.isInvalid())
661    return true;
662
663  SourceManager &SM = Ctx->getSourceManager();
664  D = getEntityDecl(D);
665
666  std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(SM.getFileLoc(Loc));
667  FileID FID = LocInfo.first;
668  if (FID.isInvalid())
669    return true;
670
671  const FileEntry *FE = SM.getFileEntryForID(FID);
672  if (!FE)
673    return true;
674  RefFileOccurence RefOccur(FE, D);
675  std::pair<llvm::DenseSet<RefFileOccurence>::iterator, bool>
676  res = RefFileOccurences.insert(RefOccur);
677  if (!res.second)
678    return true; // already in map.
679
680  return false;
681}
682
683const NamedDecl *IndexingContext::getEntityDecl(const NamedDecl *D) const {
684  assert(D);
685  D = cast<NamedDecl>(D->getCanonicalDecl());
686
687  if (const ObjCImplementationDecl *
688               ImplD = dyn_cast<ObjCImplementationDecl>(D)) {
689    return getEntityDecl(ImplD->getClassInterface());
690
691  } else if (const ObjCCategoryImplDecl *
692               CatImplD = dyn_cast<ObjCCategoryImplDecl>(D)) {
693    return getEntityDecl(CatImplD->getCategoryDecl());
694  } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
695    if (FunctionTemplateDecl *TemplD = FD->getDescribedFunctionTemplate())
696      return getEntityDecl(TemplD);
697  } else if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
698    if (ClassTemplateDecl *TemplD = RD->getDescribedClassTemplate())
699      return getEntityDecl(TemplD);
700  }
701
702  return D;
703}
704
705const DeclContext *
706IndexingContext::getEntityContainer(const Decl *D) const {
707  const DeclContext *DC = dyn_cast<DeclContext>(D);
708  if (DC)
709    return DC;
710
711  if (const ClassTemplateDecl *ClassTempl = dyn_cast<ClassTemplateDecl>(D)) {
712    DC = ClassTempl->getTemplatedDecl();
713  } if (const FunctionTemplateDecl *
714          FuncTempl = dyn_cast<FunctionTemplateDecl>(D)) {
715    DC = FuncTempl->getTemplatedDecl();
716  }
717
718  return DC;
719}
720
721CXIdxClientContainer
722IndexingContext::getClientContainerForDC(const DeclContext *DC) const {
723  if (!DC)
724    return 0;
725
726  ContainerMapTy::const_iterator I = ContainerMap.find(DC);
727  if (I == ContainerMap.end())
728    return 0;
729
730  return I->second;
731}
732
733CXIdxClientFile IndexingContext::getIndexFile(const FileEntry *File) {
734  if (!File)
735    return 0;
736
737  FileMapTy::iterator FI = FileMap.find(File);
738  if (FI != FileMap.end())
739    return FI->second;
740
741  return 0;
742}
743
744CXIdxLoc IndexingContext::getIndexLoc(SourceLocation Loc) const {
745  CXIdxLoc idxLoc =  { {0, 0}, 0 };
746  if (Loc.isInvalid())
747    return idxLoc;
748
749  idxLoc.ptr_data[0] = (void*)this;
750  idxLoc.int_data = Loc.getRawEncoding();
751  return idxLoc;
752}
753
754void IndexingContext::translateLoc(SourceLocation Loc,
755                                   CXIdxClientFile *indexFile, CXFile *file,
756                                   unsigned *line, unsigned *column,
757                                   unsigned *offset) {
758  if (Loc.isInvalid())
759    return;
760
761  SourceManager &SM = Ctx->getSourceManager();
762  Loc = SM.getFileLoc(Loc);
763
764  std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
765  FileID FID = LocInfo.first;
766  unsigned FileOffset = LocInfo.second;
767
768  if (FID.isInvalid())
769    return;
770
771  const FileEntry *FE = SM.getFileEntryForID(FID);
772  if (indexFile)
773    *indexFile = getIndexFile(FE);
774  if (file)
775    *file = (void *)FE;
776  if (line)
777    *line = SM.getLineNumber(FID, FileOffset);
778  if (column)
779    *column = SM.getColumnNumber(FID, FileOffset);
780  if (offset)
781    *offset = FileOffset;
782}
783
784void IndexingContext::getEntityInfo(const NamedDecl *D,
785                                    EntityInfo &EntityInfo,
786                                    ScratchAlloc &SA) {
787  if (!D)
788    return;
789
790  D = getEntityDecl(D);
791  EntityInfo.cursor = getCursor(D);
792  EntityInfo.Dcl = D;
793  EntityInfo.IndexCtx = this;
794  EntityInfo.kind = CXIdxEntity_Unexposed;
795  EntityInfo.templateKind = CXIdxEntity_NonTemplate;
796  EntityInfo.lang = CXIdxEntityLang_C;
797
798  if (D->hasAttrs()) {
799    AttrListInfo *attrs = SA.allocate<AttrListInfo>();
800    new (attrs) AttrListInfo(D, *this, SA);
801    EntityInfo.AttrList = attrs;
802    EntityInfo.attributes = attrs->getAttrs();
803    EntityInfo.numAttributes = attrs->getNumAttrs();
804  }
805
806  if (const TagDecl *TD = dyn_cast<TagDecl>(D)) {
807    switch (TD->getTagKind()) {
808    case TTK_Struct:
809      EntityInfo.kind = CXIdxEntity_Struct; break;
810    case TTK_Union:
811      EntityInfo.kind = CXIdxEntity_Union; break;
812    case TTK_Class:
813      EntityInfo.kind = CXIdxEntity_CXXClass;
814      EntityInfo.lang = CXIdxEntityLang_CXX;
815      break;
816    case TTK_Enum:
817      EntityInfo.kind = CXIdxEntity_Enum; break;
818    }
819
820    if (const CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(D))
821      if (!CXXRec->isCLike())
822        EntityInfo.lang = CXIdxEntityLang_CXX;
823
824    if (isa<ClassTemplatePartialSpecializationDecl>(D)) {
825      EntityInfo.templateKind = CXIdxEntity_TemplatePartialSpecialization;
826    } else if (isa<ClassTemplateSpecializationDecl>(D)) {
827      EntityInfo.templateKind = CXIdxEntity_TemplateSpecialization;
828    }
829
830  } else {
831    switch (D->getKind()) {
832    case Decl::Typedef:
833      EntityInfo.kind = CXIdxEntity_Typedef; break;
834    case Decl::Function:
835      EntityInfo.kind = CXIdxEntity_Function;
836      break;
837    case Decl::ParmVar:
838      EntityInfo.kind = CXIdxEntity_Variable;
839      break;
840    case Decl::Var:
841      EntityInfo.kind = CXIdxEntity_Variable;
842      if (isa<CXXRecordDecl>(D->getDeclContext())) {
843        EntityInfo.kind = CXIdxEntity_CXXStaticVariable;
844        EntityInfo.lang = CXIdxEntityLang_CXX;
845      }
846      break;
847    case Decl::Field:
848      EntityInfo.kind = CXIdxEntity_Field;
849      if (const CXXRecordDecl *
850            CXXRec = dyn_cast<CXXRecordDecl>(D->getDeclContext())) {
851        // FIXME: isPOD check is not sufficient, a POD can contain methods,
852        // we want a isCStructLike check.
853        if (!CXXRec->isPOD())
854          EntityInfo.lang = CXIdxEntityLang_CXX;
855      }
856      break;
857    case Decl::EnumConstant:
858      EntityInfo.kind = CXIdxEntity_EnumConstant; break;
859    case Decl::ObjCInterface:
860      EntityInfo.kind = CXIdxEntity_ObjCClass;
861      EntityInfo.lang = CXIdxEntityLang_ObjC;
862      break;
863    case Decl::ObjCProtocol:
864      EntityInfo.kind = CXIdxEntity_ObjCProtocol;
865      EntityInfo.lang = CXIdxEntityLang_ObjC;
866      break;
867    case Decl::ObjCCategory:
868      EntityInfo.kind = CXIdxEntity_ObjCCategory;
869      EntityInfo.lang = CXIdxEntityLang_ObjC;
870      break;
871    case Decl::ObjCMethod:
872      if (cast<ObjCMethodDecl>(D)->isInstanceMethod())
873        EntityInfo.kind = CXIdxEntity_ObjCInstanceMethod;
874      else
875        EntityInfo.kind = CXIdxEntity_ObjCClassMethod;
876      EntityInfo.lang = CXIdxEntityLang_ObjC;
877      break;
878    case Decl::ObjCProperty:
879      EntityInfo.kind = CXIdxEntity_ObjCProperty;
880      EntityInfo.lang = CXIdxEntityLang_ObjC;
881      break;
882    case Decl::ObjCIvar:
883      EntityInfo.kind = CXIdxEntity_ObjCIvar;
884      EntityInfo.lang = CXIdxEntityLang_ObjC;
885      break;
886    case Decl::Namespace:
887      EntityInfo.kind = CXIdxEntity_CXXNamespace;
888      EntityInfo.lang = CXIdxEntityLang_CXX;
889      break;
890    case Decl::NamespaceAlias:
891      EntityInfo.kind = CXIdxEntity_CXXNamespaceAlias;
892      EntityInfo.lang = CXIdxEntityLang_CXX;
893      break;
894    case Decl::CXXConstructor:
895      EntityInfo.kind = CXIdxEntity_CXXConstructor;
896      EntityInfo.lang = CXIdxEntityLang_CXX;
897      break;
898    case Decl::CXXDestructor:
899      EntityInfo.kind = CXIdxEntity_CXXDestructor;
900      EntityInfo.lang = CXIdxEntityLang_CXX;
901      break;
902    case Decl::CXXConversion:
903      EntityInfo.kind = CXIdxEntity_CXXConversionFunction;
904      EntityInfo.lang = CXIdxEntityLang_CXX;
905      break;
906    case Decl::CXXMethod: {
907      const CXXMethodDecl *MD = cast<CXXMethodDecl>(D);
908      if (MD->isStatic())
909        EntityInfo.kind = CXIdxEntity_CXXStaticMethod;
910      else
911        EntityInfo.kind = CXIdxEntity_CXXInstanceMethod;
912      EntityInfo.lang = CXIdxEntityLang_CXX;
913      break;
914    }
915    case Decl::ClassTemplate:
916      EntityInfo.kind = CXIdxEntity_CXXClass;
917      EntityInfo.templateKind = CXIdxEntity_Template;
918      break;
919    case Decl::FunctionTemplate:
920      EntityInfo.kind = CXIdxEntity_Function;
921      EntityInfo.templateKind = CXIdxEntity_Template;
922      if (const CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(
923                           cast<FunctionTemplateDecl>(D)->getTemplatedDecl())) {
924        if (isa<CXXConstructorDecl>(MD))
925          EntityInfo.kind = CXIdxEntity_CXXConstructor;
926        else if (isa<CXXDestructorDecl>(MD))
927          EntityInfo.kind = CXIdxEntity_CXXDestructor;
928        else if (isa<CXXConversionDecl>(MD))
929          EntityInfo.kind = CXIdxEntity_CXXConversionFunction;
930        else {
931          if (MD->isStatic())
932            EntityInfo.kind = CXIdxEntity_CXXStaticMethod;
933          else
934            EntityInfo.kind = CXIdxEntity_CXXInstanceMethod;
935        }
936      }
937      break;
938    case Decl::TypeAliasTemplate:
939      EntityInfo.kind = CXIdxEntity_CXXTypeAlias;
940      EntityInfo.templateKind = CXIdxEntity_Template;
941      break;
942    case Decl::TypeAlias:
943      EntityInfo.kind = CXIdxEntity_CXXTypeAlias;
944      EntityInfo.lang = CXIdxEntityLang_CXX;
945      break;
946    default:
947      break;
948    }
949  }
950
951  if (EntityInfo.kind == CXIdxEntity_Unexposed)
952    return;
953
954  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
955    if (FD->getTemplatedKind() ==
956          FunctionDecl::TK_FunctionTemplateSpecialization)
957      EntityInfo.templateKind = CXIdxEntity_TemplateSpecialization;
958  }
959
960  if (EntityInfo.templateKind != CXIdxEntity_NonTemplate)
961    EntityInfo.lang = CXIdxEntityLang_CXX;
962
963  if (IdentifierInfo *II = D->getIdentifier()) {
964    EntityInfo.name = SA.toCStr(II->getName());
965
966  } else if (isa<TagDecl>(D) || isa<FieldDecl>(D) || isa<NamespaceDecl>(D)) {
967    EntityInfo.name = 0; // anonymous tag/field/namespace.
968
969  } else {
970    llvm::SmallString<256> StrBuf;
971    {
972      llvm::raw_svector_ostream OS(StrBuf);
973      D->printName(OS);
974    }
975    EntityInfo.name = SA.copyCStr(StrBuf.str());
976  }
977
978  {
979    llvm::SmallString<512> StrBuf;
980    bool Ignore = getDeclCursorUSR(D, StrBuf);
981    if (Ignore) {
982      EntityInfo.USR = 0;
983    } else {
984      EntityInfo.USR = SA.copyCStr(StrBuf.str());
985    }
986  }
987}
988
989void IndexingContext::getContainerInfo(const DeclContext *DC,
990                                       ContainerInfo &ContInfo) {
991  ContInfo.cursor = getCursor(cast<Decl>(DC));
992  ContInfo.DC = DC;
993  ContInfo.IndexCtx = this;
994}
995
996CXCursor IndexingContext::getRefCursor(const NamedDecl *D, SourceLocation Loc) {
997  if (const TypeDecl *TD = dyn_cast<TypeDecl>(D))
998    return MakeCursorTypeRef(TD, Loc, CXTU);
999  if (const ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(D))
1000    return MakeCursorObjCClassRef(ID, Loc, CXTU);
1001  if (const ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D))
1002    return MakeCursorObjCProtocolRef(PD, Loc, CXTU);
1003  if (const TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
1004    return MakeCursorTemplateRef(Template, Loc, CXTU);
1005  if (const NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(D))
1006    return MakeCursorNamespaceRef(Namespace, Loc, CXTU);
1007  if (const NamespaceAliasDecl *Namespace = dyn_cast<NamespaceAliasDecl>(D))
1008    return MakeCursorNamespaceRef(Namespace, Loc, CXTU);
1009  if (const FieldDecl *Field = dyn_cast<FieldDecl>(D))
1010    return MakeCursorMemberRef(Field, Loc, CXTU);
1011
1012  return clang_getNullCursor();
1013}
1014
1015bool IndexingContext::shouldIgnoreIfImplicit(const NamedDecl *D) {
1016  if (isa<ObjCInterfaceDecl>(D))
1017    return false;
1018  if (isa<ObjCCategoryDecl>(D))
1019    return false;
1020  if (isa<ObjCIvarDecl>(D))
1021    return false;
1022  if (isa<ObjCMethodDecl>(D))
1023    return false;
1024  return true;
1025}
1026