IndexingContext.cpp revision 0b28928a715c423b3471c539f1d5499b405c0ec9
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->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
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  CatDInfo.ObjCCatDeclInfo.containerInfo = &CatDInfo.ObjCContDeclInfo;
469  if (IFaceD) {
470    CatDInfo.ObjCCatDeclInfo.objcClass = &ClassEntity;
471    CatDInfo.ObjCCatDeclInfo.classCursor =
472        MakeCursorObjCClassRef(IFaceD, ClassLoc, CXTU);
473  } else {
474    CatDInfo.ObjCCatDeclInfo.objcClass = 0;
475    CatDInfo.ObjCCatDeclInfo.classCursor = clang_getNullCursor();
476  }
477  CatDInfo.ObjCCatDeclInfo.classLoc = getIndexLoc(ClassLoc);
478  CatDInfo.ObjCCatDeclInfo.protocols = 0;
479
480  return handleObjCContainer(D, CategoryLoc, getCursor(D), CatDInfo);
481}
482
483bool IndexingContext::handleObjCMethod(const ObjCMethodDecl *D) {
484  DeclInfo DInfo(!D->isCanonicalDecl(), D->isThisDeclarationADefinition(),
485                 D->isThisDeclarationADefinition());
486  return handleDecl(D, D->getLocation(), getCursor(D), DInfo);
487}
488
489bool IndexingContext::handleSynthesizedObjCProperty(
490                                                const ObjCPropertyImplDecl *D) {
491  ObjCPropertyDecl *PD = D->getPropertyDecl();
492  return handleReference(PD, D->getLocation(), getCursor(D), 0, D->getDeclContext());
493}
494
495bool IndexingContext::handleSynthesizedObjCMethod(const ObjCMethodDecl *D,
496                                                  SourceLocation Loc) {
497  DeclInfo DInfo(/*isRedeclaration=*/true, /*isDefinition=*/true,
498                 /*isContainer=*/false);
499  return handleDecl(D, Loc, getCursor(D), DInfo);
500}
501
502bool IndexingContext::handleObjCProperty(const ObjCPropertyDecl *D) {
503  DeclInfo DInfo(/*isRedeclaration=*/false, /*isDefinition=*/false,
504                 /*isContainer=*/false);
505  return handleDecl(D, D->getLocation(), getCursor(D), DInfo);
506}
507
508bool IndexingContext::handleNamespace(const NamespaceDecl *D) {
509  DeclInfo DInfo(/*isRedeclaration=*/!D->isOriginalNamespace(),
510                 /*isDefinition=*/true,
511                 /*isContainer=*/true);
512  return handleDecl(D, D->getLocation(), getCursor(D), DInfo);
513}
514
515bool IndexingContext::handleClassTemplate(const ClassTemplateDecl *D) {
516  return handleCXXRecordDecl(D->getTemplatedDecl(), D);
517}
518
519bool IndexingContext::handleFunctionTemplate(const FunctionTemplateDecl *D) {
520  DeclInfo DInfo(/*isRedeclaration=*/!D->isCanonicalDecl(),
521                 /*isDefinition=*/D->isThisDeclarationADefinition(),
522                 /*isContainer=*/D->isThisDeclarationADefinition());
523  return handleDecl(D, D->getLocation(), getCursor(D), DInfo);
524}
525
526bool IndexingContext::handleTypeAliasTemplate(const TypeAliasTemplateDecl *D) {
527  DeclInfo DInfo(/*isRedeclaration=*/!D->isCanonicalDecl(),
528                 /*isDefinition=*/true, /*isContainer=*/false);
529  return handleDecl(D, D->getLocation(), getCursor(D), DInfo);
530}
531
532bool IndexingContext::handleReference(const NamedDecl *D, SourceLocation Loc,
533                                      const NamedDecl *Parent,
534                                      const DeclContext *DC,
535                                      const Expr *E,
536                                      CXIdxEntityRefKind Kind) {
537  if (!D)
538    return false;
539
540  CXCursor Cursor = E ? MakeCXCursor(const_cast<Expr*>(E),
541                                     const_cast<Decl*>(cast<Decl>(DC)), CXTU)
542                      : getRefCursor(D, Loc);
543  return handleReference(D, Loc, Cursor, Parent, DC, E, Kind);
544}
545
546bool IndexingContext::handleReference(const NamedDecl *D, SourceLocation Loc,
547                                      CXCursor Cursor,
548                                      const NamedDecl *Parent,
549                                      const DeclContext *DC,
550                                      const Expr *E,
551                                      CXIdxEntityRefKind Kind) {
552  if (!CB.indexEntityReference)
553    return false;
554
555  if (!D)
556    return false;
557  if (Loc.isInvalid())
558    return false;
559  if (!indexFunctionLocalSymbols() && D->getParentFunctionOrMethod())
560    return false;
561  if (isNotFromSourceFile(D->getLocation()))
562    return false;
563  if (D->isImplicit() && shouldIgnoreIfImplicit(D))
564    return false;
565
566  if (suppressRefs()) {
567    if (markEntityOccurrenceInFile(D, Loc))
568      return false; // already occurred.
569  }
570
571  ScratchAlloc SA(*this);
572  EntityInfo RefEntity, ParentEntity;
573  getEntityInfo(D, RefEntity, SA);
574  if (!RefEntity.USR)
575    return false;
576
577  getEntityInfo(Parent, ParentEntity, SA);
578
579  ContainerInfo Container;
580  getContainerInfo(DC, Container);
581
582  CXIdxEntityRefInfo Info = { Kind,
583                              Cursor,
584                              getIndexLoc(Loc),
585                              &RefEntity,
586                              Parent ? &ParentEntity : 0,
587                              &Container };
588  CB.indexEntityReference(ClientData, &Info);
589  return true;
590}
591
592bool IndexingContext::isNotFromSourceFile(SourceLocation Loc) const {
593  if (Loc.isInvalid())
594    return true;
595  SourceManager &SM = Ctx->getSourceManager();
596  SourceLocation FileLoc = SM.getFileLoc(Loc);
597  FileID FID = SM.getFileID(FileLoc);
598  return SM.getFileEntryForID(FID) == 0;
599}
600
601void IndexingContext::addContainerInMap(const DeclContext *DC,
602                                        CXIdxClientContainer container) {
603  if (!DC)
604    return;
605
606  ContainerMapTy::iterator I = ContainerMap.find(DC);
607  if (I == ContainerMap.end()) {
608    if (container)
609      ContainerMap[DC] = container;
610    return;
611  }
612  // Allow changing the container of a previously seen DeclContext so we
613  // can handle invalid user code, like a function re-definition.
614  if (container)
615    I->second = container;
616  else
617    ContainerMap.erase(I);
618}
619
620CXIdxClientEntity IndexingContext::getClientEntity(const Decl *D) const {
621  if (!D)
622    return 0;
623  EntityMapTy::const_iterator I = EntityMap.find(D);
624  if (I == EntityMap.end())
625    return 0;
626  return I->second;
627}
628
629void IndexingContext::setClientEntity(const Decl *D, CXIdxClientEntity client) {
630  if (!D)
631    return;
632  EntityMap[D] = client;
633}
634
635bool IndexingContext::handleCXXRecordDecl(const CXXRecordDecl *RD,
636                                          const NamedDecl *OrigD) {
637  if (RD->isThisDeclarationADefinition()) {
638    ScratchAlloc SA(*this);
639    CXXClassDeclInfo CXXDInfo(/*isRedeclaration=*/!OrigD->isCanonicalDecl(),
640                           /*isDefinition=*/RD->isThisDeclarationADefinition());
641    CXXBasesListInfo BaseList(RD, *this, SA);
642    CXXDInfo.CXXClassInfo.declInfo = &CXXDInfo;
643    CXXDInfo.CXXClassInfo.bases = BaseList.getBases();
644    CXXDInfo.CXXClassInfo.numBases = BaseList.getNumBases();
645
646    return handleDecl(OrigD, OrigD->getLocation(), getCursor(OrigD), CXXDInfo);
647  }
648
649  DeclInfo DInfo(/*isRedeclaration=*/!OrigD->isCanonicalDecl(),
650                 /*isDefinition=*/RD->isThisDeclarationADefinition(),
651                 /*isContainer=*/RD->isThisDeclarationADefinition());
652  return handleDecl(OrigD, OrigD->getLocation(), getCursor(OrigD), DInfo);
653}
654
655bool IndexingContext::markEntityOccurrenceInFile(const NamedDecl *D,
656                                                 SourceLocation Loc) {
657  if (!D || Loc.isInvalid())
658    return true;
659
660  SourceManager &SM = Ctx->getSourceManager();
661  D = getEntityDecl(D);
662
663  std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(SM.getFileLoc(Loc));
664  FileID FID = LocInfo.first;
665  if (FID.isInvalid())
666    return true;
667
668  const FileEntry *FE = SM.getFileEntryForID(FID);
669  if (!FE)
670    return true;
671  RefFileOccurence RefOccur(FE, D);
672  std::pair<llvm::DenseSet<RefFileOccurence>::iterator, bool>
673  res = RefFileOccurences.insert(RefOccur);
674  if (!res.second)
675    return true; // already in map.
676
677  return false;
678}
679
680const NamedDecl *IndexingContext::getEntityDecl(const NamedDecl *D) const {
681  assert(D);
682  D = cast<NamedDecl>(D->getCanonicalDecl());
683
684  if (const ObjCImplementationDecl *
685               ImplD = dyn_cast<ObjCImplementationDecl>(D)) {
686    return getEntityDecl(ImplD->getClassInterface());
687
688  } else if (const ObjCCategoryImplDecl *
689               CatImplD = dyn_cast<ObjCCategoryImplDecl>(D)) {
690    return getEntityDecl(CatImplD->getCategoryDecl());
691  } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
692    if (FunctionTemplateDecl *TemplD = FD->getDescribedFunctionTemplate())
693      return getEntityDecl(TemplD);
694  } else if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
695    if (ClassTemplateDecl *TemplD = RD->getDescribedClassTemplate())
696      return getEntityDecl(TemplD);
697  }
698
699  return D;
700}
701
702const DeclContext *
703IndexingContext::getEntityContainer(const Decl *D) const {
704  const DeclContext *DC = dyn_cast<DeclContext>(D);
705  if (DC)
706    return DC;
707
708  if (const ClassTemplateDecl *ClassTempl = dyn_cast<ClassTemplateDecl>(D)) {
709    DC = ClassTempl->getTemplatedDecl();
710  } if (const FunctionTemplateDecl *
711          FuncTempl = dyn_cast<FunctionTemplateDecl>(D)) {
712    DC = FuncTempl->getTemplatedDecl();
713  }
714
715  return DC;
716}
717
718CXIdxClientContainer
719IndexingContext::getClientContainerForDC(const DeclContext *DC) const {
720  if (!DC)
721    return 0;
722
723  ContainerMapTy::const_iterator I = ContainerMap.find(DC);
724  if (I == ContainerMap.end())
725    return 0;
726
727  return I->second;
728}
729
730CXIdxClientFile IndexingContext::getIndexFile(const FileEntry *File) {
731  if (!File)
732    return 0;
733
734  FileMapTy::iterator FI = FileMap.find(File);
735  if (FI != FileMap.end())
736    return FI->second;
737
738  return 0;
739}
740
741CXIdxLoc IndexingContext::getIndexLoc(SourceLocation Loc) const {
742  CXIdxLoc idxLoc =  { {0, 0}, 0 };
743  if (Loc.isInvalid())
744    return idxLoc;
745
746  idxLoc.ptr_data[0] = (void*)this;
747  idxLoc.int_data = Loc.getRawEncoding();
748  return idxLoc;
749}
750
751void IndexingContext::translateLoc(SourceLocation Loc,
752                                   CXIdxClientFile *indexFile, CXFile *file,
753                                   unsigned *line, unsigned *column,
754                                   unsigned *offset) {
755  if (Loc.isInvalid())
756    return;
757
758  SourceManager &SM = Ctx->getSourceManager();
759  Loc = SM.getFileLoc(Loc);
760
761  std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
762  FileID FID = LocInfo.first;
763  unsigned FileOffset = LocInfo.second;
764
765  if (FID.isInvalid())
766    return;
767
768  const FileEntry *FE = SM.getFileEntryForID(FID);
769  if (indexFile)
770    *indexFile = getIndexFile(FE);
771  if (file)
772    *file = (void *)FE;
773  if (line)
774    *line = SM.getLineNumber(FID, FileOffset);
775  if (column)
776    *column = SM.getColumnNumber(FID, FileOffset);
777  if (offset)
778    *offset = FileOffset;
779}
780
781void IndexingContext::getEntityInfo(const NamedDecl *D,
782                                    EntityInfo &EntityInfo,
783                                    ScratchAlloc &SA) {
784  if (!D)
785    return;
786
787  D = getEntityDecl(D);
788  EntityInfo.cursor = getCursor(D);
789  EntityInfo.Dcl = D;
790  EntityInfo.IndexCtx = this;
791  EntityInfo.kind = CXIdxEntity_Unexposed;
792  EntityInfo.templateKind = CXIdxEntity_NonTemplate;
793  EntityInfo.lang = CXIdxEntityLang_C;
794
795  if (D->hasAttrs()) {
796    AttrListInfo *attrs = SA.allocate<AttrListInfo>();
797    new (attrs) AttrListInfo(D, *this, SA);
798    EntityInfo.AttrList = attrs;
799    EntityInfo.attributes = attrs->getAttrs();
800    EntityInfo.numAttributes = attrs->getNumAttrs();
801  }
802
803  if (const TagDecl *TD = dyn_cast<TagDecl>(D)) {
804    switch (TD->getTagKind()) {
805    case TTK_Struct:
806      EntityInfo.kind = CXIdxEntity_Struct; break;
807    case TTK_Union:
808      EntityInfo.kind = CXIdxEntity_Union; break;
809    case TTK_Class:
810      EntityInfo.kind = CXIdxEntity_CXXClass;
811      EntityInfo.lang = CXIdxEntityLang_CXX;
812      break;
813    case TTK_Enum:
814      EntityInfo.kind = CXIdxEntity_Enum; break;
815    }
816
817    if (const CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(D)) {
818      // FIXME: isPOD check is not sufficient, a POD can contain methods,
819      // we want a isCStructLike check.
820      if (CXXRec->hasDefinition() && !CXXRec->isPOD())
821        EntityInfo.lang = CXIdxEntityLang_CXX;
822    }
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