CIndex.cpp revision e2079cf54ded1eda9e35d215aef6628373368276
1//===- CIndex.cpp - Clang-C Source Indexing Library -----------------------===//
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// This file implements the main API hooks in the Clang-C Source Indexing
11// library.
12//
13//===----------------------------------------------------------------------===//
14
15#include "CIndexer.h"
16#include "CXCursor.h"
17#include "CXTranslationUnit.h"
18#include "CXString.h"
19#include "CXType.h"
20#include "CXSourceLocation.h"
21#include "CIndexDiagnostic.h"
22#include "CursorVisitor.h"
23
24#include "clang/Basic/Version.h"
25
26#include "clang/AST/StmtVisitor.h"
27#include "clang/Basic/Diagnostic.h"
28#include "clang/Frontend/ASTUnit.h"
29#include "clang/Frontend/CompilerInstance.h"
30#include "clang/Frontend/FrontendDiagnostic.h"
31#include "clang/Lex/Lexer.h"
32#include "clang/Lex/HeaderSearch.h"
33#include "clang/Lex/PreprocessingRecord.h"
34#include "clang/Lex/Preprocessor.h"
35#include "llvm/ADT/STLExtras.h"
36#include "llvm/ADT/Optional.h"
37#include "llvm/ADT/StringSwitch.h"
38#include "clang/Analysis/Support/SaveAndRestore.h"
39#include "llvm/Support/CrashRecoveryContext.h"
40#include "llvm/Support/PrettyStackTrace.h"
41#include "llvm/Support/MemoryBuffer.h"
42#include "llvm/Support/raw_ostream.h"
43#include "llvm/Support/Timer.h"
44#include "llvm/Support/Mutex.h"
45#include "llvm/Support/Program.h"
46#include "llvm/Support/Signals.h"
47#include "llvm/Support/Threading.h"
48#include "llvm/Support/Compiler.h"
49
50using namespace clang;
51using namespace clang::cxcursor;
52using namespace clang::cxstring;
53using namespace clang::cxtu;
54
55CXTranslationUnit cxtu::MakeCXTranslationUnit(ASTUnit *TU) {
56  if (!TU)
57    return 0;
58  CXTranslationUnit D = new CXTranslationUnitImpl();
59  D->TUData = TU;
60  D->StringPool = createCXStringPool();
61  D->Diagnostics = 0;
62  return D;
63}
64
65cxtu::CXTUOwner::~CXTUOwner() {
66  if (TU)
67    clang_disposeTranslationUnit(TU);
68}
69
70/// \brief Compare two source ranges to determine their relative position in
71/// the translation unit.
72static RangeComparisonResult RangeCompare(SourceManager &SM,
73                                          SourceRange R1,
74                                          SourceRange R2) {
75  assert(R1.isValid() && "First range is invalid?");
76  assert(R2.isValid() && "Second range is invalid?");
77  if (R1.getEnd() != R2.getBegin() &&
78      SM.isBeforeInTranslationUnit(R1.getEnd(), R2.getBegin()))
79    return RangeBefore;
80  if (R2.getEnd() != R1.getBegin() &&
81      SM.isBeforeInTranslationUnit(R2.getEnd(), R1.getBegin()))
82    return RangeAfter;
83  return RangeOverlap;
84}
85
86/// \brief Determine if a source location falls within, before, or after a
87///   a given source range.
88static RangeComparisonResult LocationCompare(SourceManager &SM,
89                                             SourceLocation L, SourceRange R) {
90  assert(R.isValid() && "First range is invalid?");
91  assert(L.isValid() && "Second range is invalid?");
92  if (L == R.getBegin() || L == R.getEnd())
93    return RangeOverlap;
94  if (SM.isBeforeInTranslationUnit(L, R.getBegin()))
95    return RangeBefore;
96  if (SM.isBeforeInTranslationUnit(R.getEnd(), L))
97    return RangeAfter;
98  return RangeOverlap;
99}
100
101/// \brief Translate a Clang source range into a CIndex source range.
102///
103/// Clang internally represents ranges where the end location points to the
104/// start of the token at the end. However, for external clients it is more
105/// useful to have a CXSourceRange be a proper half-open interval. This routine
106/// does the appropriate translation.
107CXSourceRange cxloc::translateSourceRange(const SourceManager &SM,
108                                          const LangOptions &LangOpts,
109                                          const CharSourceRange &R) {
110  // We want the last character in this location, so we will adjust the
111  // location accordingly.
112  SourceLocation EndLoc = R.getEnd();
113  if (EndLoc.isValid() && EndLoc.isMacroID())
114    EndLoc = SM.getExpansionRange(EndLoc).second;
115  if (R.isTokenRange() && !EndLoc.isInvalid() && EndLoc.isFileID()) {
116    unsigned Length = Lexer::MeasureTokenLength(EndLoc, SM, LangOpts);
117    EndLoc = EndLoc.getLocWithOffset(Length);
118  }
119
120  CXSourceRange Result = { { (void *)&SM, (void *)&LangOpts },
121                           R.getBegin().getRawEncoding(),
122                           EndLoc.getRawEncoding() };
123  return Result;
124}
125
126//===----------------------------------------------------------------------===//
127// Cursor visitor.
128//===----------------------------------------------------------------------===//
129
130static SourceRange getRawCursorExtent(CXCursor C);
131static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr);
132
133
134RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
135  return RangeCompare(AU->getSourceManager(), R, RegionOfInterest);
136}
137
138/// \brief Visit the given cursor and, if requested by the visitor,
139/// its children.
140///
141/// \param Cursor the cursor to visit.
142///
143/// \param CheckRegionOfInterest if true, then the caller already checked that
144/// this cursor is within the region of interest.
145///
146/// \returns true if the visitation should be aborted, false if it
147/// should continue.
148bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
149  if (clang_isInvalid(Cursor.kind))
150    return false;
151
152  if (clang_isDeclaration(Cursor.kind)) {
153    Decl *D = getCursorDecl(Cursor);
154    assert(D && "Invalid declaration cursor");
155    // Ignore implicit declarations, unless it's an objc method because
156    // currently we should report implicit methods for properties when indexing.
157    if (D->isImplicit() && !isa<ObjCMethodDecl>(D))
158      return false;
159  }
160
161  // If we have a range of interest, and this cursor doesn't intersect with it,
162  // we're done.
163  if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
164    SourceRange Range = getRawCursorExtent(Cursor);
165    if (Range.isInvalid() || CompareRegionOfInterest(Range))
166      return false;
167  }
168
169  switch (Visitor(Cursor, Parent, ClientData)) {
170  case CXChildVisit_Break:
171    return true;
172
173  case CXChildVisit_Continue:
174    return false;
175
176  case CXChildVisit_Recurse:
177    return VisitChildren(Cursor);
178  }
179
180  return false;
181}
182
183static bool visitPreprocessedEntitiesInRange(SourceRange R,
184                                             PreprocessingRecord &PPRec,
185                                             CursorVisitor &Visitor) {
186  SourceManager &SM = Visitor.getASTUnit()->getSourceManager();
187  FileID FID;
188
189  if (!Visitor.shouldVisitIncludedEntities()) {
190    // If the begin/end of the range lie in the same FileID, do the optimization
191    // where we skip preprocessed entities that do not come from the same FileID.
192    FID = SM.getFileID(R.getBegin());
193    if (FID != SM.getFileID(R.getEnd()))
194      FID = FileID();
195  }
196
197  std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
198    Entities = PPRec.getPreprocessedEntitiesInRange(R);
199  return Visitor.visitPreprocessedEntities(Entities.first, Entities.second,
200                                           PPRec, FID);
201}
202
203void CursorVisitor::visitFileRegion() {
204  if (RegionOfInterest.isInvalid())
205    return;
206
207  ASTUnit *Unit = static_cast<ASTUnit *>(TU->TUData);
208  SourceManager &SM = Unit->getSourceManager();
209
210  std::pair<FileID, unsigned>
211    Begin = SM.getDecomposedLoc(SM.getFileLoc(RegionOfInterest.getBegin())),
212    End = SM.getDecomposedLoc(SM.getFileLoc(RegionOfInterest.getEnd()));
213
214  if (End.first != Begin.first) {
215    // If the end does not reside in the same file, try to recover by
216    // picking the end of the file of begin location.
217    End.first = Begin.first;
218    End.second = SM.getFileIDSize(Begin.first);
219  }
220
221  assert(Begin.first == End.first);
222  if (Begin.second > End.second)
223    return;
224
225  FileID File = Begin.first;
226  unsigned Offset = Begin.second;
227  unsigned Length = End.second - Begin.second;
228
229  if (!VisitPreprocessorLast &&
230      Unit->getPreprocessor().getPreprocessingRecord())
231    visitPreprocessedEntitiesInRegion();
232
233  visitDeclsFromFileRegion(File, Offset, Length);
234
235  if (VisitPreprocessorLast &&
236      Unit->getPreprocessor().getPreprocessingRecord())
237    visitPreprocessedEntitiesInRegion();
238}
239
240static bool isInLexicalContext(Decl *D, DeclContext *DC) {
241  if (!DC)
242    return false;
243
244  for (DeclContext *DeclDC = D->getLexicalDeclContext();
245         DeclDC; DeclDC = DeclDC->getLexicalParent()) {
246    if (DeclDC == DC)
247      return true;
248  }
249  return false;
250}
251
252void CursorVisitor::visitDeclsFromFileRegion(FileID File,
253                                             unsigned Offset, unsigned Length) {
254  ASTUnit *Unit = static_cast<ASTUnit *>(TU->TUData);
255  SourceManager &SM = Unit->getSourceManager();
256  SourceRange Range = RegionOfInterest;
257
258  SmallVector<Decl *, 16> Decls;
259  Unit->findFileRegionDecls(File, Offset, Length, Decls);
260
261  // If we didn't find any file level decls for the file, try looking at the
262  // file that it was included from.
263  while (Decls.empty()) {
264    bool Invalid = false;
265    const SrcMgr::SLocEntry &SLEntry = SM.getSLocEntry(File, &Invalid);
266    if (Invalid)
267      return;
268
269    SourceLocation Outer;
270    if (SLEntry.isFile())
271      Outer = SLEntry.getFile().getIncludeLoc();
272    else
273      Outer = SLEntry.getExpansion().getExpansionLocStart();
274    if (Outer.isInvalid())
275      return;
276
277    llvm::tie(File, Offset) = SM.getDecomposedExpansionLoc(Outer);
278    Length = 0;
279    Unit->findFileRegionDecls(File, Offset, Length, Decls);
280  }
281
282  assert(!Decls.empty());
283
284  bool VisitedAtLeastOnce = false;
285  DeclContext *CurDC = 0;
286  SmallVector<Decl *, 16>::iterator DIt = Decls.begin();
287  for (SmallVector<Decl *, 16>::iterator DE = Decls.end(); DIt != DE; ++DIt) {
288    Decl *D = *DIt;
289
290    if (isInLexicalContext(D, CurDC))
291      continue;
292
293    CurDC = dyn_cast<DeclContext>(D);
294
295    // We handle forward decls via ObjCClassDecl.
296    if (ObjCInterfaceDecl *InterD = dyn_cast<ObjCInterfaceDecl>(D)) {
297      if (InterD->isForwardDecl())
298        continue;
299      // An interface that started as a forward decl may have changed location
300      // because its @interface was parsed.
301      if (InterD->isInitiallyForwardDecl() &&
302          !SM.isInFileID(SM.getFileLoc(InterD->getLocation()), File))
303        continue;
304    }
305
306    if (TagDecl *TD = dyn_cast<TagDecl>(D))
307      if (!TD->isFreeStanding())
308        continue;
309
310    RangeComparisonResult CompRes = RangeCompare(SM, D->getSourceRange(),Range);
311    if (CompRes == RangeBefore)
312      continue;
313    if (CompRes == RangeAfter)
314      break;
315
316    assert(CompRes == RangeOverlap);
317    VisitedAtLeastOnce = true;
318    if (Visit(MakeCXCursor(D, TU, Range), /*CheckedRegionOfInterest=*/true))
319      break;
320  }
321
322  if (VisitedAtLeastOnce)
323    return;
324
325  // No Decls overlapped with the range. Move up the lexical context until there
326  // is a context that contains the range or we reach the translation unit
327  // level.
328  DeclContext *DC = DIt == Decls.begin() ? (*DIt)->getLexicalDeclContext()
329                                         : (*(DIt-1))->getLexicalDeclContext();
330
331  while (DC && !DC->isTranslationUnit()) {
332    Decl *D = cast<Decl>(DC);
333    SourceRange CurDeclRange = D->getSourceRange();
334    if (CurDeclRange.isInvalid())
335      break;
336
337    if (RangeCompare(SM, CurDeclRange, Range) == RangeOverlap) {
338      Visit(MakeCXCursor(D, TU, Range), /*CheckedRegionOfInterest=*/true);
339      break;
340    }
341
342    DC = D->getLexicalDeclContext();
343  }
344}
345
346bool CursorVisitor::visitPreprocessedEntitiesInRegion() {
347  PreprocessingRecord &PPRec
348    = *AU->getPreprocessor().getPreprocessingRecord();
349  SourceManager &SM = AU->getSourceManager();
350
351  if (RegionOfInterest.isValid()) {
352    SourceRange MappedRange = AU->mapRangeToPreamble(RegionOfInterest);
353    SourceLocation B = MappedRange.getBegin();
354    SourceLocation E = MappedRange.getEnd();
355
356    if (AU->isInPreambleFileID(B)) {
357      if (SM.isLoadedSourceLocation(E))
358        return visitPreprocessedEntitiesInRange(SourceRange(B, E),
359                                                 PPRec, *this);
360
361      // Beginning of range lies in the preamble but it also extends beyond
362      // it into the main file. Split the range into 2 parts, one covering
363      // the preamble and another covering the main file. This allows subsequent
364      // calls to visitPreprocessedEntitiesInRange to accept a source range that
365      // lies in the same FileID, allowing it to skip preprocessed entities that
366      // do not come from the same FileID.
367      bool breaked =
368        visitPreprocessedEntitiesInRange(
369                                   SourceRange(B, AU->getEndOfPreambleFileID()),
370                                          PPRec, *this);
371      if (breaked) return true;
372      return visitPreprocessedEntitiesInRange(
373                                    SourceRange(AU->getStartOfMainFileID(), E),
374                                        PPRec, *this);
375    }
376
377    return visitPreprocessedEntitiesInRange(SourceRange(B, E), PPRec, *this);
378  }
379
380  bool OnlyLocalDecls
381    = !AU->isMainFileAST() && AU->getOnlyLocalDecls();
382
383  if (OnlyLocalDecls)
384    return visitPreprocessedEntities(PPRec.local_begin(), PPRec.local_end(),
385                                     PPRec);
386
387  return visitPreprocessedEntities(PPRec.begin(), PPRec.end(), PPRec);
388}
389
390template<typename InputIterator>
391bool CursorVisitor::visitPreprocessedEntities(InputIterator First,
392                                              InputIterator Last,
393                                              PreprocessingRecord &PPRec,
394                                              FileID FID) {
395  for (; First != Last; ++First) {
396    if (!FID.isInvalid() && !PPRec.isEntityInFileID(First, FID))
397      continue;
398
399    PreprocessedEntity *PPE = *First;
400    if (MacroExpansion *ME = dyn_cast<MacroExpansion>(PPE)) {
401      if (Visit(MakeMacroExpansionCursor(ME, TU)))
402        return true;
403
404      continue;
405    }
406
407    if (MacroDefinition *MD = dyn_cast<MacroDefinition>(PPE)) {
408      if (Visit(MakeMacroDefinitionCursor(MD, TU)))
409        return true;
410
411      continue;
412    }
413
414    if (InclusionDirective *ID = dyn_cast<InclusionDirective>(PPE)) {
415      if (Visit(MakeInclusionDirectiveCursor(ID, TU)))
416        return true;
417
418      continue;
419    }
420  }
421
422  return false;
423}
424
425/// \brief Visit the children of the given cursor.
426///
427/// \returns true if the visitation should be aborted, false if it
428/// should continue.
429bool CursorVisitor::VisitChildren(CXCursor Cursor) {
430  if (clang_isReference(Cursor.kind) &&
431      Cursor.kind != CXCursor_CXXBaseSpecifier) {
432    // By definition, references have no children.
433    return false;
434  }
435
436  // Set the Parent field to Cursor, then back to its old value once we're
437  // done.
438  SetParentRAII SetParent(Parent, StmtParent, Cursor);
439
440  if (clang_isDeclaration(Cursor.kind)) {
441    Decl *D = getCursorDecl(Cursor);
442    if (!D)
443      return false;
444
445    return VisitAttributes(D) || Visit(D);
446  }
447
448  if (clang_isStatement(Cursor.kind)) {
449    if (Stmt *S = getCursorStmt(Cursor))
450      return Visit(S);
451
452    return false;
453  }
454
455  if (clang_isExpression(Cursor.kind)) {
456    if (Expr *E = getCursorExpr(Cursor))
457      return Visit(E);
458
459    return false;
460  }
461
462  if (clang_isTranslationUnit(Cursor.kind)) {
463    CXTranslationUnit tu = getCursorTU(Cursor);
464    ASTUnit *CXXUnit = static_cast<ASTUnit*>(tu->TUData);
465
466    int VisitOrder[2] = { VisitPreprocessorLast, !VisitPreprocessorLast };
467    for (unsigned I = 0; I != 2; ++I) {
468      if (VisitOrder[I]) {
469        if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
470            RegionOfInterest.isInvalid()) {
471          for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(),
472                                        TLEnd = CXXUnit->top_level_end();
473               TL != TLEnd; ++TL) {
474            if (Visit(MakeCXCursor(*TL, tu, RegionOfInterest), true))
475              return true;
476          }
477        } else if (VisitDeclContext(
478                                CXXUnit->getASTContext().getTranslationUnitDecl()))
479          return true;
480        continue;
481      }
482
483      // Walk the preprocessing record.
484      if (CXXUnit->getPreprocessor().getPreprocessingRecord())
485        visitPreprocessedEntitiesInRegion();
486    }
487
488    return false;
489  }
490
491  if (Cursor.kind == CXCursor_CXXBaseSpecifier) {
492    if (CXXBaseSpecifier *Base = getCursorCXXBaseSpecifier(Cursor)) {
493      if (TypeSourceInfo *BaseTSInfo = Base->getTypeSourceInfo()) {
494        return Visit(BaseTSInfo->getTypeLoc());
495      }
496    }
497  }
498
499  if (Cursor.kind == CXCursor_IBOutletCollectionAttr) {
500    IBOutletCollectionAttr *A =
501      cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(Cursor));
502    if (const ObjCInterfaceType *InterT = A->getInterface()->getAs<ObjCInterfaceType>())
503      return Visit(cxcursor::MakeCursorObjCClassRef(InterT->getInterface(),
504                                                    A->getInterfaceLoc(), TU));
505  }
506
507  // Nothing to visit at the moment.
508  return false;
509}
510
511bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
512  if (TypeSourceInfo *TSInfo = B->getSignatureAsWritten())
513    if (Visit(TSInfo->getTypeLoc()))
514        return true;
515
516  if (Stmt *Body = B->getBody())
517    return Visit(MakeCXCursor(Body, StmtParent, TU, RegionOfInterest));
518
519  return false;
520}
521
522llvm::Optional<bool> CursorVisitor::shouldVisitCursor(CXCursor Cursor) {
523  if (RegionOfInterest.isValid()) {
524    SourceRange Range = getFullCursorExtent(Cursor, AU->getSourceManager());
525    if (Range.isInvalid())
526      return llvm::Optional<bool>();
527
528    switch (CompareRegionOfInterest(Range)) {
529    case RangeBefore:
530      // This declaration comes before the region of interest; skip it.
531      return llvm::Optional<bool>();
532
533    case RangeAfter:
534      // This declaration comes after the region of interest; we're done.
535      return false;
536
537    case RangeOverlap:
538      // This declaration overlaps the region of interest; visit it.
539      break;
540    }
541  }
542  return true;
543}
544
545bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
546  DeclContext::decl_iterator I = DC->decls_begin(), E = DC->decls_end();
547
548  // FIXME: Eventually remove.  This part of a hack to support proper
549  // iteration over all Decls contained lexically within an ObjC container.
550  SaveAndRestore<DeclContext::decl_iterator*> DI_saved(DI_current, &I);
551  SaveAndRestore<DeclContext::decl_iterator> DE_saved(DE_current, E);
552
553  for ( ; I != E; ++I) {
554    Decl *D = *I;
555    if (D->getLexicalDeclContext() != DC)
556      continue;
557    CXCursor Cursor = MakeCXCursor(D, TU, RegionOfInterest);
558    const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
559    if (!V.hasValue())
560      continue;
561    if (!V.getValue())
562      return false;
563    if (Visit(Cursor, true))
564      return true;
565  }
566  return false;
567}
568
569bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
570  llvm_unreachable("Translation units are visited directly by Visit()");
571  return false;
572}
573
574bool CursorVisitor::VisitTypeAliasDecl(TypeAliasDecl *D) {
575  if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
576    return Visit(TSInfo->getTypeLoc());
577
578  return false;
579}
580
581bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
582  if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
583    return Visit(TSInfo->getTypeLoc());
584
585  return false;
586}
587
588bool CursorVisitor::VisitTagDecl(TagDecl *D) {
589  return VisitDeclContext(D);
590}
591
592bool CursorVisitor::VisitClassTemplateSpecializationDecl(
593                                          ClassTemplateSpecializationDecl *D) {
594  bool ShouldVisitBody = false;
595  switch (D->getSpecializationKind()) {
596  case TSK_Undeclared:
597  case TSK_ImplicitInstantiation:
598    // Nothing to visit
599    return false;
600
601  case TSK_ExplicitInstantiationDeclaration:
602  case TSK_ExplicitInstantiationDefinition:
603    break;
604
605  case TSK_ExplicitSpecialization:
606    ShouldVisitBody = true;
607    break;
608  }
609
610  // Visit the template arguments used in the specialization.
611  if (TypeSourceInfo *SpecType = D->getTypeAsWritten()) {
612    TypeLoc TL = SpecType->getTypeLoc();
613    if (TemplateSpecializationTypeLoc *TSTLoc
614          = dyn_cast<TemplateSpecializationTypeLoc>(&TL)) {
615      for (unsigned I = 0, N = TSTLoc->getNumArgs(); I != N; ++I)
616        if (VisitTemplateArgumentLoc(TSTLoc->getArgLoc(I)))
617          return true;
618    }
619  }
620
621  if (ShouldVisitBody && VisitCXXRecordDecl(D))
622    return true;
623
624  return false;
625}
626
627bool CursorVisitor::VisitClassTemplatePartialSpecializationDecl(
628                                   ClassTemplatePartialSpecializationDecl *D) {
629  // FIXME: Visit the "outer" template parameter lists on the TagDecl
630  // before visiting these template parameters.
631  if (VisitTemplateParameters(D->getTemplateParameters()))
632    return true;
633
634  // Visit the partial specialization arguments.
635  const TemplateArgumentLoc *TemplateArgs = D->getTemplateArgsAsWritten();
636  for (unsigned I = 0, N = D->getNumTemplateArgsAsWritten(); I != N; ++I)
637    if (VisitTemplateArgumentLoc(TemplateArgs[I]))
638      return true;
639
640  return VisitCXXRecordDecl(D);
641}
642
643bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
644  // Visit the default argument.
645  if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
646    if (TypeSourceInfo *DefArg = D->getDefaultArgumentInfo())
647      if (Visit(DefArg->getTypeLoc()))
648        return true;
649
650  return false;
651}
652
653bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
654  if (Expr *Init = D->getInitExpr())
655    return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
656  return false;
657}
658
659bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
660  if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
661    if (Visit(TSInfo->getTypeLoc()))
662      return true;
663
664  // Visit the nested-name-specifier, if present.
665  if (NestedNameSpecifierLoc QualifierLoc = DD->getQualifierLoc())
666    if (VisitNestedNameSpecifierLoc(QualifierLoc))
667      return true;
668
669  return false;
670}
671
672/// \brief Compare two base or member initializers based on their source order.
673static int CompareCXXCtorInitializers(const void* Xp, const void *Yp) {
674  CXXCtorInitializer const * const *X
675    = static_cast<CXXCtorInitializer const * const *>(Xp);
676  CXXCtorInitializer const * const *Y
677    = static_cast<CXXCtorInitializer const * const *>(Yp);
678
679  if ((*X)->getSourceOrder() < (*Y)->getSourceOrder())
680    return -1;
681  else if ((*X)->getSourceOrder() > (*Y)->getSourceOrder())
682    return 1;
683  else
684    return 0;
685}
686
687bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
688  if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) {
689    // Visit the function declaration's syntactic components in the order
690    // written. This requires a bit of work.
691    TypeLoc TL = TSInfo->getTypeLoc().IgnoreParens();
692    FunctionTypeLoc *FTL = dyn_cast<FunctionTypeLoc>(&TL);
693
694    // If we have a function declared directly (without the use of a typedef),
695    // visit just the return type. Otherwise, just visit the function's type
696    // now.
697    if ((FTL && !isa<CXXConversionDecl>(ND) && Visit(FTL->getResultLoc())) ||
698        (!FTL && Visit(TL)))
699      return true;
700
701    // Visit the nested-name-specifier, if present.
702    if (NestedNameSpecifierLoc QualifierLoc = ND->getQualifierLoc())
703      if (VisitNestedNameSpecifierLoc(QualifierLoc))
704        return true;
705
706    // Visit the declaration name.
707    if (VisitDeclarationNameInfo(ND->getNameInfo()))
708      return true;
709
710    // FIXME: Visit explicitly-specified template arguments!
711
712    // Visit the function parameters, if we have a function type.
713    if (FTL && VisitFunctionTypeLoc(*FTL, true))
714      return true;
715
716    // FIXME: Attributes?
717  }
718
719  if (ND->doesThisDeclarationHaveABody() && !ND->isLateTemplateParsed()) {
720    if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ND)) {
721      // Find the initializers that were written in the source.
722      SmallVector<CXXCtorInitializer *, 4> WrittenInits;
723      for (CXXConstructorDecl::init_iterator I = Constructor->init_begin(),
724                                          IEnd = Constructor->init_end();
725           I != IEnd; ++I) {
726        if (!(*I)->isWritten())
727          continue;
728
729        WrittenInits.push_back(*I);
730      }
731
732      // Sort the initializers in source order
733      llvm::array_pod_sort(WrittenInits.begin(), WrittenInits.end(),
734                           &CompareCXXCtorInitializers);
735
736      // Visit the initializers in source order
737      for (unsigned I = 0, N = WrittenInits.size(); I != N; ++I) {
738        CXXCtorInitializer *Init = WrittenInits[I];
739        if (Init->isAnyMemberInitializer()) {
740          if (Visit(MakeCursorMemberRef(Init->getAnyMember(),
741                                        Init->getMemberLocation(), TU)))
742            return true;
743        } else if (TypeSourceInfo *TInfo = Init->getTypeSourceInfo()) {
744          if (Visit(TInfo->getTypeLoc()))
745            return true;
746        }
747
748        // Visit the initializer value.
749        if (Expr *Initializer = Init->getInit())
750          if (Visit(MakeCXCursor(Initializer, ND, TU, RegionOfInterest)))
751            return true;
752      }
753    }
754
755    if (Visit(MakeCXCursor(ND->getBody(), StmtParent, TU, RegionOfInterest)))
756      return true;
757  }
758
759  return false;
760}
761
762bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
763  if (VisitDeclaratorDecl(D))
764    return true;
765
766  if (Expr *BitWidth = D->getBitWidth())
767    return Visit(MakeCXCursor(BitWidth, StmtParent, TU, RegionOfInterest));
768
769  return false;
770}
771
772bool CursorVisitor::VisitVarDecl(VarDecl *D) {
773  if (VisitDeclaratorDecl(D))
774    return true;
775
776  if (Expr *Init = D->getInit())
777    return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
778
779  return false;
780}
781
782bool CursorVisitor::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
783  if (VisitDeclaratorDecl(D))
784    return true;
785
786  if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
787    if (Expr *DefArg = D->getDefaultArgument())
788      return Visit(MakeCXCursor(DefArg, StmtParent, TU, RegionOfInterest));
789
790  return false;
791}
792
793bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
794  // FIXME: Visit the "outer" template parameter lists on the FunctionDecl
795  // before visiting these template parameters.
796  if (VisitTemplateParameters(D->getTemplateParameters()))
797    return true;
798
799  return VisitFunctionDecl(D->getTemplatedDecl());
800}
801
802bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) {
803  // FIXME: Visit the "outer" template parameter lists on the TagDecl
804  // before visiting these template parameters.
805  if (VisitTemplateParameters(D->getTemplateParameters()))
806    return true;
807
808  return VisitCXXRecordDecl(D->getTemplatedDecl());
809}
810
811bool CursorVisitor::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
812  if (VisitTemplateParameters(D->getTemplateParameters()))
813    return true;
814
815  if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited() &&
816      VisitTemplateArgumentLoc(D->getDefaultArgument()))
817    return true;
818
819  return false;
820}
821
822bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
823  if (TypeSourceInfo *TSInfo = ND->getResultTypeSourceInfo())
824    if (Visit(TSInfo->getTypeLoc()))
825      return true;
826
827  for (ObjCMethodDecl::param_iterator P = ND->param_begin(),
828       PEnd = ND->param_end();
829       P != PEnd; ++P) {
830    if (Visit(MakeCXCursor(*P, TU, RegionOfInterest)))
831      return true;
832  }
833
834  if (ND->isThisDeclarationADefinition() &&
835      Visit(MakeCXCursor(ND->getBody(), StmtParent, TU, RegionOfInterest)))
836    return true;
837
838  return false;
839}
840
841namespace {
842  struct ContainerDeclsSort {
843    SourceManager &SM;
844    ContainerDeclsSort(SourceManager &sm) : SM(sm) {}
845    bool operator()(Decl *A, Decl *B) {
846      SourceLocation L_A = A->getLocStart();
847      SourceLocation L_B = B->getLocStart();
848      assert(L_A.isValid() && L_B.isValid());
849      return SM.isBeforeInTranslationUnit(L_A, L_B);
850    }
851  };
852}
853
854bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
855  // FIXME: Eventually convert back to just 'VisitDeclContext()'.  Essentially
856  // an @implementation can lexically contain Decls that are not properly
857  // nested in the AST.  When we identify such cases, we need to retrofit
858  // this nesting here.
859  if (!DI_current)
860    return VisitDeclContext(D);
861
862  // Scan the Decls that immediately come after the container
863  // in the current DeclContext.  If any fall within the
864  // container's lexical region, stash them into a vector
865  // for later processing.
866  SmallVector<Decl *, 24> DeclsInContainer;
867  SourceLocation EndLoc = D->getSourceRange().getEnd();
868  SourceManager &SM = AU->getSourceManager();
869  if (EndLoc.isValid()) {
870    DeclContext::decl_iterator next = *DI_current;
871    while (++next != DE_current) {
872      Decl *D_next = *next;
873      if (!D_next)
874        break;
875      SourceLocation L = D_next->getLocStart();
876      if (!L.isValid())
877        break;
878      if (SM.isBeforeInTranslationUnit(L, EndLoc)) {
879        *DI_current = next;
880        DeclsInContainer.push_back(D_next);
881        continue;
882      }
883      break;
884    }
885  }
886
887  // The common case.
888  if (DeclsInContainer.empty())
889    return VisitDeclContext(D);
890
891  // Get all the Decls in the DeclContext, and sort them with the
892  // additional ones we've collected.  Then visit them.
893  for (DeclContext::decl_iterator I = D->decls_begin(), E = D->decls_end();
894       I!=E; ++I) {
895    Decl *subDecl = *I;
896    if (!subDecl || subDecl->getLexicalDeclContext() != D ||
897        subDecl->getLocStart().isInvalid())
898      continue;
899    DeclsInContainer.push_back(subDecl);
900  }
901
902  // Now sort the Decls so that they appear in lexical order.
903  std::sort(DeclsInContainer.begin(), DeclsInContainer.end(),
904            ContainerDeclsSort(SM));
905
906  // Now visit the decls.
907  for (SmallVectorImpl<Decl*>::iterator I = DeclsInContainer.begin(),
908         E = DeclsInContainer.end(); I != E; ++I) {
909    CXCursor Cursor = MakeCXCursor(*I, TU, RegionOfInterest);
910    const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
911    if (!V.hasValue())
912      continue;
913    if (!V.getValue())
914      return false;
915    if (Visit(Cursor, true))
916      return true;
917  }
918  return false;
919}
920
921bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
922  if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
923                                   TU)))
924    return true;
925
926  ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
927  for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
928         E = ND->protocol_end(); I != E; ++I, ++PL)
929    if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
930      return true;
931
932  return VisitObjCContainerDecl(ND);
933}
934
935bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
936  ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
937  for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
938       E = PID->protocol_end(); I != E; ++I, ++PL)
939    if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
940      return true;
941
942  return VisitObjCContainerDecl(PID);
943}
944
945bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
946  if (PD->getTypeSourceInfo() && Visit(PD->getTypeSourceInfo()->getTypeLoc()))
947    return true;
948
949  // FIXME: This implements a workaround with @property declarations also being
950  // installed in the DeclContext for the @interface.  Eventually this code
951  // should be removed.
952  ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
953  if (!CDecl || !CDecl->IsClassExtension())
954    return false;
955
956  ObjCInterfaceDecl *ID = CDecl->getClassInterface();
957  if (!ID)
958    return false;
959
960  IdentifierInfo *PropertyId = PD->getIdentifier();
961  ObjCPropertyDecl *prevDecl =
962    ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId);
963
964  if (!prevDecl)
965    return false;
966
967  // Visit synthesized methods since they will be skipped when visiting
968  // the @interface.
969  if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
970    if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
971      if (Visit(MakeCXCursor(MD, TU, RegionOfInterest)))
972        return true;
973
974  if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
975    if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
976      if (Visit(MakeCXCursor(MD, TU, RegionOfInterest)))
977        return true;
978
979  return false;
980}
981
982bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
983  // Issue callbacks for super class.
984  if (D->getSuperClass() &&
985      Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
986                                        D->getSuperClassLoc(),
987                                        TU)))
988    return true;
989
990  ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
991  for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
992         E = D->protocol_end(); I != E; ++I, ++PL)
993    if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
994      return true;
995
996  return VisitObjCContainerDecl(D);
997}
998
999bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
1000  return VisitObjCContainerDecl(D);
1001}
1002
1003bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
1004  // 'ID' could be null when dealing with invalid code.
1005  if (ObjCInterfaceDecl *ID = D->getClassInterface())
1006    if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
1007      return true;
1008
1009  return VisitObjCImplDecl(D);
1010}
1011
1012bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
1013#if 0
1014  // Issue callbacks for super class.
1015  // FIXME: No source location information!
1016  if (D->getSuperClass() &&
1017      Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
1018                                        D->getSuperClassLoc(),
1019                                        TU)))
1020    return true;
1021#endif
1022
1023  return VisitObjCImplDecl(D);
1024}
1025
1026bool CursorVisitor::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D) {
1027  ObjCForwardProtocolDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1028  for (ObjCForwardProtocolDecl::protocol_iterator I = D->protocol_begin(),
1029                                                  E = D->protocol_end();
1030       I != E; ++I, ++PL)
1031    if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
1032      return true;
1033
1034  return false;
1035}
1036
1037bool CursorVisitor::VisitObjCClassDecl(ObjCClassDecl *D) {
1038  if (Visit(MakeCursorObjCClassRef(D->getForwardInterfaceDecl(),
1039                                   D->getForwardDecl()->getLocation(), TU)))
1040      return true;
1041  return false;
1042}
1043
1044bool CursorVisitor::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *PD) {
1045  if (ObjCIvarDecl *Ivar = PD->getPropertyIvarDecl())
1046    return Visit(MakeCursorMemberRef(Ivar, PD->getPropertyIvarDeclLoc(), TU));
1047
1048  return false;
1049}
1050
1051bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
1052  return VisitDeclContext(D);
1053}
1054
1055bool CursorVisitor::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
1056  // Visit nested-name-specifier.
1057  if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1058    if (VisitNestedNameSpecifierLoc(QualifierLoc))
1059      return true;
1060
1061  return Visit(MakeCursorNamespaceRef(D->getAliasedNamespace(),
1062                                      D->getTargetNameLoc(), TU));
1063}
1064
1065bool CursorVisitor::VisitUsingDecl(UsingDecl *D) {
1066  // Visit nested-name-specifier.
1067  if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1068    if (VisitNestedNameSpecifierLoc(QualifierLoc))
1069      return true;
1070  }
1071
1072  if (Visit(MakeCursorOverloadedDeclRef(D, D->getLocation(), TU)))
1073    return true;
1074
1075  return VisitDeclarationNameInfo(D->getNameInfo());
1076}
1077
1078bool CursorVisitor::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
1079  // Visit nested-name-specifier.
1080  if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1081    if (VisitNestedNameSpecifierLoc(QualifierLoc))
1082      return true;
1083
1084  return Visit(MakeCursorNamespaceRef(D->getNominatedNamespaceAsWritten(),
1085                                      D->getIdentLocation(), TU));
1086}
1087
1088bool CursorVisitor::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
1089  // Visit nested-name-specifier.
1090  if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1091    if (VisitNestedNameSpecifierLoc(QualifierLoc))
1092      return true;
1093  }
1094
1095  return VisitDeclarationNameInfo(D->getNameInfo());
1096}
1097
1098bool CursorVisitor::VisitUnresolvedUsingTypenameDecl(
1099                                               UnresolvedUsingTypenameDecl *D) {
1100  // Visit nested-name-specifier.
1101  if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1102    if (VisitNestedNameSpecifierLoc(QualifierLoc))
1103      return true;
1104
1105  return false;
1106}
1107
1108bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) {
1109  switch (Name.getName().getNameKind()) {
1110  case clang::DeclarationName::Identifier:
1111  case clang::DeclarationName::CXXLiteralOperatorName:
1112  case clang::DeclarationName::CXXOperatorName:
1113  case clang::DeclarationName::CXXUsingDirective:
1114    return false;
1115
1116  case clang::DeclarationName::CXXConstructorName:
1117  case clang::DeclarationName::CXXDestructorName:
1118  case clang::DeclarationName::CXXConversionFunctionName:
1119    if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo())
1120      return Visit(TSInfo->getTypeLoc());
1121    return false;
1122
1123  case clang::DeclarationName::ObjCZeroArgSelector:
1124  case clang::DeclarationName::ObjCOneArgSelector:
1125  case clang::DeclarationName::ObjCMultiArgSelector:
1126    // FIXME: Per-identifier location info?
1127    return false;
1128  }
1129
1130  return false;
1131}
1132
1133bool CursorVisitor::VisitNestedNameSpecifier(NestedNameSpecifier *NNS,
1134                                             SourceRange Range) {
1135  // FIXME: This whole routine is a hack to work around the lack of proper
1136  // source information in nested-name-specifiers (PR5791). Since we do have
1137  // a beginning source location, we can visit the first component of the
1138  // nested-name-specifier, if it's a single-token component.
1139  if (!NNS)
1140    return false;
1141
1142  // Get the first component in the nested-name-specifier.
1143  while (NestedNameSpecifier *Prefix = NNS->getPrefix())
1144    NNS = Prefix;
1145
1146  switch (NNS->getKind()) {
1147  case NestedNameSpecifier::Namespace:
1148    return Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(), Range.getBegin(),
1149                                        TU));
1150
1151  case NestedNameSpecifier::NamespaceAlias:
1152    return Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
1153                                        Range.getBegin(), TU));
1154
1155  case NestedNameSpecifier::TypeSpec: {
1156    // If the type has a form where we know that the beginning of the source
1157    // range matches up with a reference cursor. Visit the appropriate reference
1158    // cursor.
1159    const Type *T = NNS->getAsType();
1160    if (const TypedefType *Typedef = dyn_cast<TypedefType>(T))
1161      return Visit(MakeCursorTypeRef(Typedef->getDecl(), Range.getBegin(), TU));
1162    if (const TagType *Tag = dyn_cast<TagType>(T))
1163      return Visit(MakeCursorTypeRef(Tag->getDecl(), Range.getBegin(), TU));
1164    if (const TemplateSpecializationType *TST
1165                                      = dyn_cast<TemplateSpecializationType>(T))
1166      return VisitTemplateName(TST->getTemplateName(), Range.getBegin());
1167    break;
1168  }
1169
1170  case NestedNameSpecifier::TypeSpecWithTemplate:
1171  case NestedNameSpecifier::Global:
1172  case NestedNameSpecifier::Identifier:
1173    break;
1174  }
1175
1176  return false;
1177}
1178
1179bool
1180CursorVisitor::VisitNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
1181  SmallVector<NestedNameSpecifierLoc, 4> Qualifiers;
1182  for (; Qualifier; Qualifier = Qualifier.getPrefix())
1183    Qualifiers.push_back(Qualifier);
1184
1185  while (!Qualifiers.empty()) {
1186    NestedNameSpecifierLoc Q = Qualifiers.pop_back_val();
1187    NestedNameSpecifier *NNS = Q.getNestedNameSpecifier();
1188    switch (NNS->getKind()) {
1189    case NestedNameSpecifier::Namespace:
1190      if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(),
1191                                       Q.getLocalBeginLoc(),
1192                                       TU)))
1193        return true;
1194
1195      break;
1196
1197    case NestedNameSpecifier::NamespaceAlias:
1198      if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
1199                                       Q.getLocalBeginLoc(),
1200                                       TU)))
1201        return true;
1202
1203      break;
1204
1205    case NestedNameSpecifier::TypeSpec:
1206    case NestedNameSpecifier::TypeSpecWithTemplate:
1207      if (Visit(Q.getTypeLoc()))
1208        return true;
1209
1210      break;
1211
1212    case NestedNameSpecifier::Global:
1213    case NestedNameSpecifier::Identifier:
1214      break;
1215    }
1216  }
1217
1218  return false;
1219}
1220
1221bool CursorVisitor::VisitTemplateParameters(
1222                                          const TemplateParameterList *Params) {
1223  if (!Params)
1224    return false;
1225
1226  for (TemplateParameterList::const_iterator P = Params->begin(),
1227                                          PEnd = Params->end();
1228       P != PEnd; ++P) {
1229    if (Visit(MakeCXCursor(*P, TU, RegionOfInterest)))
1230      return true;
1231  }
1232
1233  return false;
1234}
1235
1236bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) {
1237  switch (Name.getKind()) {
1238  case TemplateName::Template:
1239    return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU));
1240
1241  case TemplateName::OverloadedTemplate:
1242    // Visit the overloaded template set.
1243    if (Visit(MakeCursorOverloadedDeclRef(Name, Loc, TU)))
1244      return true;
1245
1246    return false;
1247
1248  case TemplateName::DependentTemplate:
1249    // FIXME: Visit nested-name-specifier.
1250    return false;
1251
1252  case TemplateName::QualifiedTemplate:
1253    // FIXME: Visit nested-name-specifier.
1254    return Visit(MakeCursorTemplateRef(
1255                                  Name.getAsQualifiedTemplateName()->getDecl(),
1256                                       Loc, TU));
1257
1258  case TemplateName::SubstTemplateTemplateParm:
1259    return Visit(MakeCursorTemplateRef(
1260                         Name.getAsSubstTemplateTemplateParm()->getParameter(),
1261                                       Loc, TU));
1262
1263  case TemplateName::SubstTemplateTemplateParmPack:
1264    return Visit(MakeCursorTemplateRef(
1265                  Name.getAsSubstTemplateTemplateParmPack()->getParameterPack(),
1266                                       Loc, TU));
1267  }
1268
1269  return false;
1270}
1271
1272bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) {
1273  switch (TAL.getArgument().getKind()) {
1274  case TemplateArgument::Null:
1275  case TemplateArgument::Integral:
1276  case TemplateArgument::Pack:
1277    return false;
1278
1279  case TemplateArgument::Type:
1280    if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo())
1281      return Visit(TSInfo->getTypeLoc());
1282    return false;
1283
1284  case TemplateArgument::Declaration:
1285    if (Expr *E = TAL.getSourceDeclExpression())
1286      return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
1287    return false;
1288
1289  case TemplateArgument::Expression:
1290    if (Expr *E = TAL.getSourceExpression())
1291      return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
1292    return false;
1293
1294  case TemplateArgument::Template:
1295  case TemplateArgument::TemplateExpansion:
1296    if (VisitNestedNameSpecifierLoc(TAL.getTemplateQualifierLoc()))
1297      return true;
1298
1299    return VisitTemplateName(TAL.getArgument().getAsTemplateOrTemplatePattern(),
1300                             TAL.getTemplateNameLoc());
1301  }
1302
1303  return false;
1304}
1305
1306bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1307  return VisitDeclContext(D);
1308}
1309
1310bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1311  return Visit(TL.getUnqualifiedLoc());
1312}
1313
1314bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
1315  ASTContext &Context = AU->getASTContext();
1316
1317  // Some builtin types (such as Objective-C's "id", "sel", and
1318  // "Class") have associated declarations. Create cursors for those.
1319  QualType VisitType;
1320  switch (TL.getTypePtr()->getKind()) {
1321
1322  case BuiltinType::Void:
1323  case BuiltinType::NullPtr:
1324  case BuiltinType::Dependent:
1325#define BUILTIN_TYPE(Id, SingletonId)
1326#define SIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
1327#define UNSIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
1328#define FLOATING_TYPE(Id, SingletonId) case BuiltinType::Id:
1329#define PLACEHOLDER_TYPE(Id, SingletonId) case BuiltinType::Id:
1330#include "clang/AST/BuiltinTypes.def"
1331    break;
1332
1333  case BuiltinType::ObjCId:
1334    VisitType = Context.getObjCIdType();
1335    break;
1336
1337  case BuiltinType::ObjCClass:
1338    VisitType = Context.getObjCClassType();
1339    break;
1340
1341  case BuiltinType::ObjCSel:
1342    VisitType = Context.getObjCSelType();
1343    break;
1344  }
1345
1346  if (!VisitType.isNull()) {
1347    if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
1348      return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
1349                                     TU));
1350  }
1351
1352  return false;
1353}
1354
1355bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
1356  return Visit(MakeCursorTypeRef(TL.getTypedefNameDecl(), TL.getNameLoc(), TU));
1357}
1358
1359bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
1360  return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1361}
1362
1363bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
1364  if (TL.isDefinition())
1365    return Visit(MakeCXCursor(TL.getDecl(), TU, RegionOfInterest));
1366
1367  return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1368}
1369
1370bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
1371  return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1372}
1373
1374bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
1375  if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
1376    return true;
1377
1378  return false;
1379}
1380
1381bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
1382  if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
1383    return true;
1384
1385  for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1386    if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1387                                        TU)))
1388      return true;
1389  }
1390
1391  return false;
1392}
1393
1394bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
1395  return Visit(TL.getPointeeLoc());
1396}
1397
1398bool CursorVisitor::VisitParenTypeLoc(ParenTypeLoc TL) {
1399  return Visit(TL.getInnerLoc());
1400}
1401
1402bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
1403  return Visit(TL.getPointeeLoc());
1404}
1405
1406bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1407  return Visit(TL.getPointeeLoc());
1408}
1409
1410bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1411  return Visit(TL.getPointeeLoc());
1412}
1413
1414bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
1415  return Visit(TL.getPointeeLoc());
1416}
1417
1418bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
1419  return Visit(TL.getPointeeLoc());
1420}
1421
1422bool CursorVisitor::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
1423  return Visit(TL.getModifiedLoc());
1424}
1425
1426bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL,
1427                                         bool SkipResultType) {
1428  if (!SkipResultType && Visit(TL.getResultLoc()))
1429    return true;
1430
1431  for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1432    if (Decl *D = TL.getArg(I))
1433      if (Visit(MakeCXCursor(D, TU, RegionOfInterest)))
1434        return true;
1435
1436  return false;
1437}
1438
1439bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
1440  if (Visit(TL.getElementLoc()))
1441    return true;
1442
1443  if (Expr *Size = TL.getSizeExpr())
1444    return Visit(MakeCXCursor(Size, StmtParent, TU, RegionOfInterest));
1445
1446  return false;
1447}
1448
1449bool CursorVisitor::VisitTemplateSpecializationTypeLoc(
1450                                             TemplateSpecializationTypeLoc TL) {
1451  // Visit the template name.
1452  if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1453                        TL.getTemplateNameLoc()))
1454    return true;
1455
1456  // Visit the template arguments.
1457  for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1458    if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1459      return true;
1460
1461  return false;
1462}
1463
1464bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
1465  return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
1466}
1467
1468bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
1469  if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1470    return Visit(TSInfo->getTypeLoc());
1471
1472  return false;
1473}
1474
1475bool CursorVisitor::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
1476  if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1477    return Visit(TSInfo->getTypeLoc());
1478
1479  return false;
1480}
1481
1482bool CursorVisitor::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
1483  if (VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1484    return true;
1485
1486  return false;
1487}
1488
1489bool CursorVisitor::VisitDependentTemplateSpecializationTypeLoc(
1490                                    DependentTemplateSpecializationTypeLoc TL) {
1491  // Visit the nested-name-specifier, if there is one.
1492  if (TL.getQualifierLoc() &&
1493      VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1494    return true;
1495
1496  // Visit the template arguments.
1497  for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1498    if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1499      return true;
1500
1501  return false;
1502}
1503
1504bool CursorVisitor::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
1505  if (VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1506    return true;
1507
1508  return Visit(TL.getNamedTypeLoc());
1509}
1510
1511bool CursorVisitor::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
1512  return Visit(TL.getPatternLoc());
1513}
1514
1515bool CursorVisitor::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
1516  if (Expr *E = TL.getUnderlyingExpr())
1517    return Visit(MakeCXCursor(E, StmtParent, TU));
1518
1519  return false;
1520}
1521
1522bool CursorVisitor::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
1523  return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1524}
1525
1526bool CursorVisitor::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
1527  return Visit(TL.getValueLoc());
1528}
1529
1530#define DEFAULT_TYPELOC_IMPL(CLASS, PARENT) \
1531bool CursorVisitor::Visit##CLASS##TypeLoc(CLASS##TypeLoc TL) { \
1532  return Visit##PARENT##Loc(TL); \
1533}
1534
1535DEFAULT_TYPELOC_IMPL(Complex, Type)
1536DEFAULT_TYPELOC_IMPL(ConstantArray, ArrayType)
1537DEFAULT_TYPELOC_IMPL(IncompleteArray, ArrayType)
1538DEFAULT_TYPELOC_IMPL(VariableArray, ArrayType)
1539DEFAULT_TYPELOC_IMPL(DependentSizedArray, ArrayType)
1540DEFAULT_TYPELOC_IMPL(DependentSizedExtVector, Type)
1541DEFAULT_TYPELOC_IMPL(Vector, Type)
1542DEFAULT_TYPELOC_IMPL(ExtVector, VectorType)
1543DEFAULT_TYPELOC_IMPL(FunctionProto, FunctionType)
1544DEFAULT_TYPELOC_IMPL(FunctionNoProto, FunctionType)
1545DEFAULT_TYPELOC_IMPL(Record, TagType)
1546DEFAULT_TYPELOC_IMPL(Enum, TagType)
1547DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParm, Type)
1548DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParmPack, Type)
1549DEFAULT_TYPELOC_IMPL(Auto, Type)
1550
1551bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
1552  // Visit the nested-name-specifier, if present.
1553  if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1554    if (VisitNestedNameSpecifierLoc(QualifierLoc))
1555      return true;
1556
1557  if (D->isCompleteDefinition()) {
1558    for (CXXRecordDecl::base_class_iterator I = D->bases_begin(),
1559         E = D->bases_end(); I != E; ++I) {
1560      if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(I, TU)))
1561        return true;
1562    }
1563  }
1564
1565  return VisitTagDecl(D);
1566}
1567
1568bool CursorVisitor::VisitAttributes(Decl *D) {
1569  for (AttrVec::const_iterator i = D->attr_begin(), e = D->attr_end();
1570       i != e; ++i)
1571    if (Visit(MakeCXCursor(*i, D, TU)))
1572        return true;
1573
1574  return false;
1575}
1576
1577//===----------------------------------------------------------------------===//
1578// Data-recursive visitor methods.
1579//===----------------------------------------------------------------------===//
1580
1581namespace {
1582#define DEF_JOB(NAME, DATA, KIND)\
1583class NAME : public VisitorJob {\
1584public:\
1585  NAME(DATA *d, CXCursor parent) : VisitorJob(parent, VisitorJob::KIND, d) {} \
1586  static bool classof(const VisitorJob *VJ) { return VJ->getKind() == KIND; }\
1587  DATA *get() const { return static_cast<DATA*>(data[0]); }\
1588};
1589
1590DEF_JOB(StmtVisit, Stmt, StmtVisitKind)
1591DEF_JOB(MemberExprParts, MemberExpr, MemberExprPartsKind)
1592DEF_JOB(DeclRefExprParts, DeclRefExpr, DeclRefExprPartsKind)
1593DEF_JOB(OverloadExprParts, OverloadExpr, OverloadExprPartsKind)
1594DEF_JOB(ExplicitTemplateArgsVisit, ASTTemplateArgumentListInfo,
1595        ExplicitTemplateArgsVisitKind)
1596DEF_JOB(SizeOfPackExprParts, SizeOfPackExpr, SizeOfPackExprPartsKind)
1597#undef DEF_JOB
1598
1599class DeclVisit : public VisitorJob {
1600public:
1601  DeclVisit(Decl *d, CXCursor parent, bool isFirst) :
1602    VisitorJob(parent, VisitorJob::DeclVisitKind,
1603               d, isFirst ? (void*) 1 : (void*) 0) {}
1604  static bool classof(const VisitorJob *VJ) {
1605    return VJ->getKind() == DeclVisitKind;
1606  }
1607  Decl *get() const { return static_cast<Decl*>(data[0]); }
1608  bool isFirst() const { return data[1] ? true : false; }
1609};
1610class TypeLocVisit : public VisitorJob {
1611public:
1612  TypeLocVisit(TypeLoc tl, CXCursor parent) :
1613    VisitorJob(parent, VisitorJob::TypeLocVisitKind,
1614               tl.getType().getAsOpaquePtr(), tl.getOpaqueData()) {}
1615
1616  static bool classof(const VisitorJob *VJ) {
1617    return VJ->getKind() == TypeLocVisitKind;
1618  }
1619
1620  TypeLoc get() const {
1621    QualType T = QualType::getFromOpaquePtr(data[0]);
1622    return TypeLoc(T, data[1]);
1623  }
1624};
1625
1626class LabelRefVisit : public VisitorJob {
1627public:
1628  LabelRefVisit(LabelDecl *LD, SourceLocation labelLoc, CXCursor parent)
1629    : VisitorJob(parent, VisitorJob::LabelRefVisitKind, LD,
1630                 labelLoc.getPtrEncoding()) {}
1631
1632  static bool classof(const VisitorJob *VJ) {
1633    return VJ->getKind() == VisitorJob::LabelRefVisitKind;
1634  }
1635  LabelDecl *get() const { return static_cast<LabelDecl*>(data[0]); }
1636  SourceLocation getLoc() const {
1637    return SourceLocation::getFromPtrEncoding(data[1]); }
1638};
1639
1640class NestedNameSpecifierLocVisit : public VisitorJob {
1641public:
1642  NestedNameSpecifierLocVisit(NestedNameSpecifierLoc Qualifier, CXCursor parent)
1643    : VisitorJob(parent, VisitorJob::NestedNameSpecifierLocVisitKind,
1644                 Qualifier.getNestedNameSpecifier(),
1645                 Qualifier.getOpaqueData()) { }
1646
1647  static bool classof(const VisitorJob *VJ) {
1648    return VJ->getKind() == VisitorJob::NestedNameSpecifierLocVisitKind;
1649  }
1650
1651  NestedNameSpecifierLoc get() const {
1652    return NestedNameSpecifierLoc(static_cast<NestedNameSpecifier*>(data[0]),
1653                                  data[1]);
1654  }
1655};
1656
1657class DeclarationNameInfoVisit : public VisitorJob {
1658public:
1659  DeclarationNameInfoVisit(Stmt *S, CXCursor parent)
1660    : VisitorJob(parent, VisitorJob::DeclarationNameInfoVisitKind, S) {}
1661  static bool classof(const VisitorJob *VJ) {
1662    return VJ->getKind() == VisitorJob::DeclarationNameInfoVisitKind;
1663  }
1664  DeclarationNameInfo get() const {
1665    Stmt *S = static_cast<Stmt*>(data[0]);
1666    switch (S->getStmtClass()) {
1667    default:
1668      llvm_unreachable("Unhandled Stmt");
1669    case clang::Stmt::MSDependentExistsStmtClass:
1670      return cast<MSDependentExistsStmt>(S)->getNameInfo();
1671    case Stmt::CXXDependentScopeMemberExprClass:
1672      return cast<CXXDependentScopeMemberExpr>(S)->getMemberNameInfo();
1673    case Stmt::DependentScopeDeclRefExprClass:
1674      return cast<DependentScopeDeclRefExpr>(S)->getNameInfo();
1675    }
1676  }
1677};
1678class MemberRefVisit : public VisitorJob {
1679public:
1680  MemberRefVisit(FieldDecl *D, SourceLocation L, CXCursor parent)
1681    : VisitorJob(parent, VisitorJob::MemberRefVisitKind, D,
1682                 L.getPtrEncoding()) {}
1683  static bool classof(const VisitorJob *VJ) {
1684    return VJ->getKind() == VisitorJob::MemberRefVisitKind;
1685  }
1686  FieldDecl *get() const {
1687    return static_cast<FieldDecl*>(data[0]);
1688  }
1689  SourceLocation getLoc() const {
1690    return SourceLocation::getFromRawEncoding((unsigned)(uintptr_t) data[1]);
1691  }
1692};
1693class EnqueueVisitor : public StmtVisitor<EnqueueVisitor, void> {
1694  VisitorWorkList &WL;
1695  CXCursor Parent;
1696public:
1697  EnqueueVisitor(VisitorWorkList &wl, CXCursor parent)
1698    : WL(wl), Parent(parent) {}
1699
1700  void VisitAddrLabelExpr(AddrLabelExpr *E);
1701  void VisitBlockExpr(BlockExpr *B);
1702  void VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
1703  void VisitCompoundStmt(CompoundStmt *S);
1704  void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { /* Do nothing. */ }
1705  void VisitMSDependentExistsStmt(MSDependentExistsStmt *S);
1706  void VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E);
1707  void VisitCXXNewExpr(CXXNewExpr *E);
1708  void VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
1709  void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E);
1710  void VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E);
1711  void VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E);
1712  void VisitCXXTypeidExpr(CXXTypeidExpr *E);
1713  void VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr *E);
1714  void VisitCXXUuidofExpr(CXXUuidofExpr *E);
1715  void VisitDeclRefExpr(DeclRefExpr *D);
1716  void VisitDeclStmt(DeclStmt *S);
1717  void VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E);
1718  void VisitDesignatedInitExpr(DesignatedInitExpr *E);
1719  void VisitExplicitCastExpr(ExplicitCastExpr *E);
1720  void VisitForStmt(ForStmt *FS);
1721  void VisitGotoStmt(GotoStmt *GS);
1722  void VisitIfStmt(IfStmt *If);
1723  void VisitInitListExpr(InitListExpr *IE);
1724  void VisitMemberExpr(MemberExpr *M);
1725  void VisitOffsetOfExpr(OffsetOfExpr *E);
1726  void VisitObjCEncodeExpr(ObjCEncodeExpr *E);
1727  void VisitObjCMessageExpr(ObjCMessageExpr *M);
1728  void VisitOverloadExpr(OverloadExpr *E);
1729  void VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E);
1730  void VisitStmt(Stmt *S);
1731  void VisitSwitchStmt(SwitchStmt *S);
1732  void VisitWhileStmt(WhileStmt *W);
1733  void VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E);
1734  void VisitBinaryTypeTraitExpr(BinaryTypeTraitExpr *E);
1735  void VisitArrayTypeTraitExpr(ArrayTypeTraitExpr *E);
1736  void VisitExpressionTraitExpr(ExpressionTraitExpr *E);
1737  void VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U);
1738  void VisitVAArgExpr(VAArgExpr *E);
1739  void VisitSizeOfPackExpr(SizeOfPackExpr *E);
1740  void VisitPseudoObjectExpr(PseudoObjectExpr *E);
1741  void VisitOpaqueValueExpr(OpaqueValueExpr *E);
1742
1743private:
1744  void AddDeclarationNameInfo(Stmt *S);
1745  void AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier);
1746  void AddExplicitTemplateArgs(const ASTTemplateArgumentListInfo *A);
1747  void AddMemberRef(FieldDecl *D, SourceLocation L);
1748  void AddStmt(Stmt *S);
1749  void AddDecl(Decl *D, bool isFirst = true);
1750  void AddTypeLoc(TypeSourceInfo *TI);
1751  void EnqueueChildren(Stmt *S);
1752};
1753} // end anonyous namespace
1754
1755void EnqueueVisitor::AddDeclarationNameInfo(Stmt *S) {
1756  // 'S' should always be non-null, since it comes from the
1757  // statement we are visiting.
1758  WL.push_back(DeclarationNameInfoVisit(S, Parent));
1759}
1760
1761void
1762EnqueueVisitor::AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
1763  if (Qualifier)
1764    WL.push_back(NestedNameSpecifierLocVisit(Qualifier, Parent));
1765}
1766
1767void EnqueueVisitor::AddStmt(Stmt *S) {
1768  if (S)
1769    WL.push_back(StmtVisit(S, Parent));
1770}
1771void EnqueueVisitor::AddDecl(Decl *D, bool isFirst) {
1772  if (D)
1773    WL.push_back(DeclVisit(D, Parent, isFirst));
1774}
1775void EnqueueVisitor::
1776  AddExplicitTemplateArgs(const ASTTemplateArgumentListInfo *A) {
1777  if (A)
1778    WL.push_back(ExplicitTemplateArgsVisit(
1779                        const_cast<ASTTemplateArgumentListInfo*>(A), Parent));
1780}
1781void EnqueueVisitor::AddMemberRef(FieldDecl *D, SourceLocation L) {
1782  if (D)
1783    WL.push_back(MemberRefVisit(D, L, Parent));
1784}
1785void EnqueueVisitor::AddTypeLoc(TypeSourceInfo *TI) {
1786  if (TI)
1787    WL.push_back(TypeLocVisit(TI->getTypeLoc(), Parent));
1788 }
1789void EnqueueVisitor::EnqueueChildren(Stmt *S) {
1790  unsigned size = WL.size();
1791  for (Stmt::child_range Child = S->children(); Child; ++Child) {
1792    AddStmt(*Child);
1793  }
1794  if (size == WL.size())
1795    return;
1796  // Now reverse the entries we just added.  This will match the DFS
1797  // ordering performed by the worklist.
1798  VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1799  std::reverse(I, E);
1800}
1801void EnqueueVisitor::VisitAddrLabelExpr(AddrLabelExpr *E) {
1802  WL.push_back(LabelRefVisit(E->getLabel(), E->getLabelLoc(), Parent));
1803}
1804void EnqueueVisitor::VisitBlockExpr(BlockExpr *B) {
1805  AddDecl(B->getBlockDecl());
1806}
1807void EnqueueVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
1808  EnqueueChildren(E);
1809  AddTypeLoc(E->getTypeSourceInfo());
1810}
1811void EnqueueVisitor::VisitCompoundStmt(CompoundStmt *S) {
1812  for (CompoundStmt::reverse_body_iterator I = S->body_rbegin(),
1813        E = S->body_rend(); I != E; ++I) {
1814    AddStmt(*I);
1815  }
1816}
1817void EnqueueVisitor::
1818VisitMSDependentExistsStmt(MSDependentExistsStmt *S) {
1819  AddStmt(S->getSubStmt());
1820  AddDeclarationNameInfo(S);
1821  if (NestedNameSpecifierLoc QualifierLoc = S->getQualifierLoc())
1822    AddNestedNameSpecifierLoc(QualifierLoc);
1823}
1824
1825void EnqueueVisitor::
1826VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E) {
1827  AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
1828  AddDeclarationNameInfo(E);
1829  if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
1830    AddNestedNameSpecifierLoc(QualifierLoc);
1831  if (!E->isImplicitAccess())
1832    AddStmt(E->getBase());
1833}
1834void EnqueueVisitor::VisitCXXNewExpr(CXXNewExpr *E) {
1835  // Enqueue the initializer or constructor arguments.
1836  for (unsigned I = E->getNumConstructorArgs(); I > 0; --I)
1837    AddStmt(E->getConstructorArg(I-1));
1838  // Enqueue the array size, if any.
1839  AddStmt(E->getArraySize());
1840  // Enqueue the allocated type.
1841  AddTypeLoc(E->getAllocatedTypeSourceInfo());
1842  // Enqueue the placement arguments.
1843  for (unsigned I = E->getNumPlacementArgs(); I > 0; --I)
1844    AddStmt(E->getPlacementArg(I-1));
1845}
1846void EnqueueVisitor::VisitCXXOperatorCallExpr(CXXOperatorCallExpr *CE) {
1847  for (unsigned I = CE->getNumArgs(); I > 1 /* Yes, this is 1 */; --I)
1848    AddStmt(CE->getArg(I-1));
1849  AddStmt(CE->getCallee());
1850  AddStmt(CE->getArg(0));
1851}
1852void EnqueueVisitor::VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E) {
1853  // Visit the name of the type being destroyed.
1854  AddTypeLoc(E->getDestroyedTypeInfo());
1855  // Visit the scope type that looks disturbingly like the nested-name-specifier
1856  // but isn't.
1857  AddTypeLoc(E->getScopeTypeInfo());
1858  // Visit the nested-name-specifier.
1859  if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
1860    AddNestedNameSpecifierLoc(QualifierLoc);
1861  // Visit base expression.
1862  AddStmt(E->getBase());
1863}
1864void EnqueueVisitor::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
1865  AddTypeLoc(E->getTypeSourceInfo());
1866}
1867void EnqueueVisitor::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E) {
1868  EnqueueChildren(E);
1869  AddTypeLoc(E->getTypeSourceInfo());
1870}
1871void EnqueueVisitor::VisitCXXTypeidExpr(CXXTypeidExpr *E) {
1872  EnqueueChildren(E);
1873  if (E->isTypeOperand())
1874    AddTypeLoc(E->getTypeOperandSourceInfo());
1875}
1876
1877void EnqueueVisitor::VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr
1878                                                     *E) {
1879  EnqueueChildren(E);
1880  AddTypeLoc(E->getTypeSourceInfo());
1881}
1882void EnqueueVisitor::VisitCXXUuidofExpr(CXXUuidofExpr *E) {
1883  EnqueueChildren(E);
1884  if (E->isTypeOperand())
1885    AddTypeLoc(E->getTypeOperandSourceInfo());
1886}
1887void EnqueueVisitor::VisitDeclRefExpr(DeclRefExpr *DR) {
1888  if (DR->hasExplicitTemplateArgs()) {
1889    AddExplicitTemplateArgs(&DR->getExplicitTemplateArgs());
1890  }
1891  WL.push_back(DeclRefExprParts(DR, Parent));
1892}
1893void EnqueueVisitor::VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E) {
1894  AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
1895  AddDeclarationNameInfo(E);
1896  AddNestedNameSpecifierLoc(E->getQualifierLoc());
1897}
1898void EnqueueVisitor::VisitDeclStmt(DeclStmt *S) {
1899  unsigned size = WL.size();
1900  bool isFirst = true;
1901  for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
1902       D != DEnd; ++D) {
1903    AddDecl(*D, isFirst);
1904    isFirst = false;
1905  }
1906  if (size == WL.size())
1907    return;
1908  // Now reverse the entries we just added.  This will match the DFS
1909  // ordering performed by the worklist.
1910  VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1911  std::reverse(I, E);
1912}
1913void EnqueueVisitor::VisitDesignatedInitExpr(DesignatedInitExpr *E) {
1914  AddStmt(E->getInit());
1915  typedef DesignatedInitExpr::Designator Designator;
1916  for (DesignatedInitExpr::reverse_designators_iterator
1917         D = E->designators_rbegin(), DEnd = E->designators_rend();
1918         D != DEnd; ++D) {
1919    if (D->isFieldDesignator()) {
1920      if (FieldDecl *Field = D->getField())
1921        AddMemberRef(Field, D->getFieldLoc());
1922      continue;
1923    }
1924    if (D->isArrayDesignator()) {
1925      AddStmt(E->getArrayIndex(*D));
1926      continue;
1927    }
1928    assert(D->isArrayRangeDesignator() && "Unknown designator kind");
1929    AddStmt(E->getArrayRangeEnd(*D));
1930    AddStmt(E->getArrayRangeStart(*D));
1931  }
1932}
1933void EnqueueVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
1934  EnqueueChildren(E);
1935  AddTypeLoc(E->getTypeInfoAsWritten());
1936}
1937void EnqueueVisitor::VisitForStmt(ForStmt *FS) {
1938  AddStmt(FS->getBody());
1939  AddStmt(FS->getInc());
1940  AddStmt(FS->getCond());
1941  AddDecl(FS->getConditionVariable());
1942  AddStmt(FS->getInit());
1943}
1944void EnqueueVisitor::VisitGotoStmt(GotoStmt *GS) {
1945  WL.push_back(LabelRefVisit(GS->getLabel(), GS->getLabelLoc(), Parent));
1946}
1947void EnqueueVisitor::VisitIfStmt(IfStmt *If) {
1948  AddStmt(If->getElse());
1949  AddStmt(If->getThen());
1950  AddStmt(If->getCond());
1951  AddDecl(If->getConditionVariable());
1952}
1953void EnqueueVisitor::VisitInitListExpr(InitListExpr *IE) {
1954  // We care about the syntactic form of the initializer list, only.
1955  if (InitListExpr *Syntactic = IE->getSyntacticForm())
1956    IE = Syntactic;
1957  EnqueueChildren(IE);
1958}
1959void EnqueueVisitor::VisitMemberExpr(MemberExpr *M) {
1960  WL.push_back(MemberExprParts(M, Parent));
1961
1962  // If the base of the member access expression is an implicit 'this', don't
1963  // visit it.
1964  // FIXME: If we ever want to show these implicit accesses, this will be
1965  // unfortunate. However, clang_getCursor() relies on this behavior.
1966  if (!M->isImplicitAccess())
1967    AddStmt(M->getBase());
1968}
1969void EnqueueVisitor::VisitObjCEncodeExpr(ObjCEncodeExpr *E) {
1970  AddTypeLoc(E->getEncodedTypeSourceInfo());
1971}
1972void EnqueueVisitor::VisitObjCMessageExpr(ObjCMessageExpr *M) {
1973  EnqueueChildren(M);
1974  AddTypeLoc(M->getClassReceiverTypeInfo());
1975}
1976void EnqueueVisitor::VisitOffsetOfExpr(OffsetOfExpr *E) {
1977  // Visit the components of the offsetof expression.
1978  for (unsigned N = E->getNumComponents(), I = N; I > 0; --I) {
1979    typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
1980    const OffsetOfNode &Node = E->getComponent(I-1);
1981    switch (Node.getKind()) {
1982    case OffsetOfNode::Array:
1983      AddStmt(E->getIndexExpr(Node.getArrayExprIndex()));
1984      break;
1985    case OffsetOfNode::Field:
1986      AddMemberRef(Node.getField(), Node.getSourceRange().getEnd());
1987      break;
1988    case OffsetOfNode::Identifier:
1989    case OffsetOfNode::Base:
1990      continue;
1991    }
1992  }
1993  // Visit the type into which we're computing the offset.
1994  AddTypeLoc(E->getTypeSourceInfo());
1995}
1996void EnqueueVisitor::VisitOverloadExpr(OverloadExpr *E) {
1997  AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
1998  WL.push_back(OverloadExprParts(E, Parent));
1999}
2000void EnqueueVisitor::VisitUnaryExprOrTypeTraitExpr(
2001                                              UnaryExprOrTypeTraitExpr *E) {
2002  EnqueueChildren(E);
2003  if (E->isArgumentType())
2004    AddTypeLoc(E->getArgumentTypeInfo());
2005}
2006void EnqueueVisitor::VisitStmt(Stmt *S) {
2007  EnqueueChildren(S);
2008}
2009void EnqueueVisitor::VisitSwitchStmt(SwitchStmt *S) {
2010  AddStmt(S->getBody());
2011  AddStmt(S->getCond());
2012  AddDecl(S->getConditionVariable());
2013}
2014
2015void EnqueueVisitor::VisitWhileStmt(WhileStmt *W) {
2016  AddStmt(W->getBody());
2017  AddStmt(W->getCond());
2018  AddDecl(W->getConditionVariable());
2019}
2020
2021void EnqueueVisitor::VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E) {
2022  AddTypeLoc(E->getQueriedTypeSourceInfo());
2023}
2024
2025void EnqueueVisitor::VisitBinaryTypeTraitExpr(BinaryTypeTraitExpr *E) {
2026  AddTypeLoc(E->getRhsTypeSourceInfo());
2027  AddTypeLoc(E->getLhsTypeSourceInfo());
2028}
2029
2030void EnqueueVisitor::VisitArrayTypeTraitExpr(ArrayTypeTraitExpr *E) {
2031  AddTypeLoc(E->getQueriedTypeSourceInfo());
2032}
2033
2034void EnqueueVisitor::VisitExpressionTraitExpr(ExpressionTraitExpr *E) {
2035  EnqueueChildren(E);
2036}
2037
2038void EnqueueVisitor::VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U) {
2039  VisitOverloadExpr(U);
2040  if (!U->isImplicitAccess())
2041    AddStmt(U->getBase());
2042}
2043void EnqueueVisitor::VisitVAArgExpr(VAArgExpr *E) {
2044  AddStmt(E->getSubExpr());
2045  AddTypeLoc(E->getWrittenTypeInfo());
2046}
2047void EnqueueVisitor::VisitSizeOfPackExpr(SizeOfPackExpr *E) {
2048  WL.push_back(SizeOfPackExprParts(E, Parent));
2049}
2050void EnqueueVisitor::VisitOpaqueValueExpr(OpaqueValueExpr *E) {
2051  // If the opaque value has a source expression, just transparently
2052  // visit that.  This is useful for (e.g.) pseudo-object expressions.
2053  if (Expr *SourceExpr = E->getSourceExpr())
2054    return Visit(SourceExpr);
2055  AddStmt(E);
2056}
2057void EnqueueVisitor::VisitPseudoObjectExpr(PseudoObjectExpr *E) {
2058  // Treat the expression like its syntactic form.
2059  Visit(E->getSyntacticForm());
2060}
2061
2062void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, Stmt *S) {
2063  EnqueueVisitor(WL, MakeCXCursor(S, StmtParent, TU,RegionOfInterest)).Visit(S);
2064}
2065
2066bool CursorVisitor::IsInRegionOfInterest(CXCursor C) {
2067  if (RegionOfInterest.isValid()) {
2068    SourceRange Range = getRawCursorExtent(C);
2069    if (Range.isInvalid() || CompareRegionOfInterest(Range))
2070      return false;
2071  }
2072  return true;
2073}
2074
2075bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) {
2076  while (!WL.empty()) {
2077    // Dequeue the worklist item.
2078    VisitorJob LI = WL.back();
2079    WL.pop_back();
2080
2081    // Set the Parent field, then back to its old value once we're done.
2082    SetParentRAII SetParent(Parent, StmtParent, LI.getParent());
2083
2084    switch (LI.getKind()) {
2085      case VisitorJob::DeclVisitKind: {
2086        Decl *D = cast<DeclVisit>(&LI)->get();
2087        if (!D)
2088          continue;
2089
2090        // For now, perform default visitation for Decls.
2091        if (Visit(MakeCXCursor(D, TU, RegionOfInterest,
2092                               cast<DeclVisit>(&LI)->isFirst())))
2093            return true;
2094
2095        continue;
2096      }
2097      case VisitorJob::ExplicitTemplateArgsVisitKind: {
2098        const ASTTemplateArgumentListInfo *ArgList =
2099          cast<ExplicitTemplateArgsVisit>(&LI)->get();
2100        for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
2101               *ArgEnd = Arg + ArgList->NumTemplateArgs;
2102               Arg != ArgEnd; ++Arg) {
2103          if (VisitTemplateArgumentLoc(*Arg))
2104            return true;
2105        }
2106        continue;
2107      }
2108      case VisitorJob::TypeLocVisitKind: {
2109        // Perform default visitation for TypeLocs.
2110        if (Visit(cast<TypeLocVisit>(&LI)->get()))
2111          return true;
2112        continue;
2113      }
2114      case VisitorJob::LabelRefVisitKind: {
2115        LabelDecl *LS = cast<LabelRefVisit>(&LI)->get();
2116        if (LabelStmt *stmt = LS->getStmt()) {
2117          if (Visit(MakeCursorLabelRef(stmt, cast<LabelRefVisit>(&LI)->getLoc(),
2118                                       TU))) {
2119            return true;
2120          }
2121        }
2122        continue;
2123      }
2124
2125      case VisitorJob::NestedNameSpecifierLocVisitKind: {
2126        NestedNameSpecifierLocVisit *V = cast<NestedNameSpecifierLocVisit>(&LI);
2127        if (VisitNestedNameSpecifierLoc(V->get()))
2128          return true;
2129        continue;
2130      }
2131
2132      case VisitorJob::DeclarationNameInfoVisitKind: {
2133        if (VisitDeclarationNameInfo(cast<DeclarationNameInfoVisit>(&LI)
2134                                     ->get()))
2135          return true;
2136        continue;
2137      }
2138      case VisitorJob::MemberRefVisitKind: {
2139        MemberRefVisit *V = cast<MemberRefVisit>(&LI);
2140        if (Visit(MakeCursorMemberRef(V->get(), V->getLoc(), TU)))
2141          return true;
2142        continue;
2143      }
2144      case VisitorJob::StmtVisitKind: {
2145        Stmt *S = cast<StmtVisit>(&LI)->get();
2146        if (!S)
2147          continue;
2148
2149        // Update the current cursor.
2150        CXCursor Cursor = MakeCXCursor(S, StmtParent, TU, RegionOfInterest);
2151        if (!IsInRegionOfInterest(Cursor))
2152          continue;
2153        switch (Visitor(Cursor, Parent, ClientData)) {
2154          case CXChildVisit_Break: return true;
2155          case CXChildVisit_Continue: break;
2156          case CXChildVisit_Recurse:
2157            EnqueueWorkList(WL, S);
2158            break;
2159        }
2160        continue;
2161      }
2162      case VisitorJob::MemberExprPartsKind: {
2163        // Handle the other pieces in the MemberExpr besides the base.
2164        MemberExpr *M = cast<MemberExprParts>(&LI)->get();
2165
2166        // Visit the nested-name-specifier
2167        if (NestedNameSpecifierLoc QualifierLoc = M->getQualifierLoc())
2168          if (VisitNestedNameSpecifierLoc(QualifierLoc))
2169            return true;
2170
2171        // Visit the declaration name.
2172        if (VisitDeclarationNameInfo(M->getMemberNameInfo()))
2173          return true;
2174
2175        // Visit the explicitly-specified template arguments, if any.
2176        if (M->hasExplicitTemplateArgs()) {
2177          for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(),
2178               *ArgEnd = Arg + M->getNumTemplateArgs();
2179               Arg != ArgEnd; ++Arg) {
2180            if (VisitTemplateArgumentLoc(*Arg))
2181              return true;
2182          }
2183        }
2184        continue;
2185      }
2186      case VisitorJob::DeclRefExprPartsKind: {
2187        DeclRefExpr *DR = cast<DeclRefExprParts>(&LI)->get();
2188        // Visit nested-name-specifier, if present.
2189        if (NestedNameSpecifierLoc QualifierLoc = DR->getQualifierLoc())
2190          if (VisitNestedNameSpecifierLoc(QualifierLoc))
2191            return true;
2192        // Visit declaration name.
2193        if (VisitDeclarationNameInfo(DR->getNameInfo()))
2194          return true;
2195        continue;
2196      }
2197      case VisitorJob::OverloadExprPartsKind: {
2198        OverloadExpr *O = cast<OverloadExprParts>(&LI)->get();
2199        // Visit the nested-name-specifier.
2200        if (NestedNameSpecifierLoc QualifierLoc = O->getQualifierLoc())
2201          if (VisitNestedNameSpecifierLoc(QualifierLoc))
2202            return true;
2203        // Visit the declaration name.
2204        if (VisitDeclarationNameInfo(O->getNameInfo()))
2205          return true;
2206        // Visit the overloaded declaration reference.
2207        if (Visit(MakeCursorOverloadedDeclRef(O, TU)))
2208          return true;
2209        continue;
2210      }
2211      case VisitorJob::SizeOfPackExprPartsKind: {
2212        SizeOfPackExpr *E = cast<SizeOfPackExprParts>(&LI)->get();
2213        NamedDecl *Pack = E->getPack();
2214        if (isa<TemplateTypeParmDecl>(Pack)) {
2215          if (Visit(MakeCursorTypeRef(cast<TemplateTypeParmDecl>(Pack),
2216                                      E->getPackLoc(), TU)))
2217            return true;
2218
2219          continue;
2220        }
2221
2222        if (isa<TemplateTemplateParmDecl>(Pack)) {
2223          if (Visit(MakeCursorTemplateRef(cast<TemplateTemplateParmDecl>(Pack),
2224                                          E->getPackLoc(), TU)))
2225            return true;
2226
2227          continue;
2228        }
2229
2230        // Non-type template parameter packs and function parameter packs are
2231        // treated like DeclRefExpr cursors.
2232        continue;
2233      }
2234    }
2235  }
2236  return false;
2237}
2238
2239bool CursorVisitor::Visit(Stmt *S) {
2240  VisitorWorkList *WL = 0;
2241  if (!WorkListFreeList.empty()) {
2242    WL = WorkListFreeList.back();
2243    WL->clear();
2244    WorkListFreeList.pop_back();
2245  }
2246  else {
2247    WL = new VisitorWorkList();
2248    WorkListCache.push_back(WL);
2249  }
2250  EnqueueWorkList(*WL, S);
2251  bool result = RunVisitorWorkList(*WL);
2252  WorkListFreeList.push_back(WL);
2253  return result;
2254}
2255
2256namespace {
2257typedef llvm::SmallVector<SourceRange, 4> RefNamePieces;
2258RefNamePieces buildPieces(unsigned NameFlags, bool IsMemberRefExpr,
2259                          const DeclarationNameInfo &NI,
2260                          const SourceRange &QLoc,
2261                          const ASTTemplateArgumentListInfo *TemplateArgs = 0){
2262  const bool WantQualifier = NameFlags & CXNameRange_WantQualifier;
2263  const bool WantTemplateArgs = NameFlags & CXNameRange_WantTemplateArgs;
2264  const bool WantSinglePiece = NameFlags & CXNameRange_WantSinglePiece;
2265
2266  const DeclarationName::NameKind Kind = NI.getName().getNameKind();
2267
2268  RefNamePieces Pieces;
2269
2270  if (WantQualifier && QLoc.isValid())
2271    Pieces.push_back(QLoc);
2272
2273  if (Kind != DeclarationName::CXXOperatorName || IsMemberRefExpr)
2274    Pieces.push_back(NI.getLoc());
2275
2276  if (WantTemplateArgs && TemplateArgs)
2277    Pieces.push_back(SourceRange(TemplateArgs->LAngleLoc,
2278                                 TemplateArgs->RAngleLoc));
2279
2280  if (Kind == DeclarationName::CXXOperatorName) {
2281    Pieces.push_back(SourceLocation::getFromRawEncoding(
2282                       NI.getInfo().CXXOperatorName.BeginOpNameLoc));
2283    Pieces.push_back(SourceLocation::getFromRawEncoding(
2284                       NI.getInfo().CXXOperatorName.EndOpNameLoc));
2285  }
2286
2287  if (WantSinglePiece) {
2288    SourceRange R(Pieces.front().getBegin(), Pieces.back().getEnd());
2289    Pieces.clear();
2290    Pieces.push_back(R);
2291  }
2292
2293  return Pieces;
2294}
2295}
2296
2297//===----------------------------------------------------------------------===//
2298// Misc. API hooks.
2299//===----------------------------------------------------------------------===//
2300
2301static llvm::sys::Mutex EnableMultithreadingMutex;
2302static bool EnabledMultithreading;
2303
2304extern "C" {
2305CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
2306                          int displayDiagnostics) {
2307  // Disable pretty stack trace functionality, which will otherwise be a very
2308  // poor citizen of the world and set up all sorts of signal handlers.
2309  llvm::DisablePrettyStackTrace = true;
2310
2311  // We use crash recovery to make some of our APIs more reliable, implicitly
2312  // enable it.
2313  llvm::CrashRecoveryContext::Enable();
2314
2315  // Enable support for multithreading in LLVM.
2316  {
2317    llvm::sys::ScopedLock L(EnableMultithreadingMutex);
2318    if (!EnabledMultithreading) {
2319      llvm::llvm_start_multithreaded();
2320      EnabledMultithreading = true;
2321    }
2322  }
2323
2324  CIndexer *CIdxr = new CIndexer();
2325  if (excludeDeclarationsFromPCH)
2326    CIdxr->setOnlyLocalDecls();
2327  if (displayDiagnostics)
2328    CIdxr->setDisplayDiagnostics();
2329  return CIdxr;
2330}
2331
2332void clang_disposeIndex(CXIndex CIdx) {
2333  if (CIdx)
2334    delete static_cast<CIndexer *>(CIdx);
2335}
2336
2337void clang_toggleCrashRecovery(unsigned isEnabled) {
2338  if (isEnabled)
2339    llvm::CrashRecoveryContext::Enable();
2340  else
2341    llvm::CrashRecoveryContext::Disable();
2342}
2343
2344CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
2345                                              const char *ast_filename) {
2346  if (!CIdx)
2347    return 0;
2348
2349  CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
2350  FileSystemOptions FileSystemOpts;
2351  FileSystemOpts.WorkingDir = CXXIdx->getWorkingDirectory();
2352
2353  llvm::IntrusiveRefCntPtr<DiagnosticsEngine> Diags;
2354  ASTUnit *TU = ASTUnit::LoadFromASTFile(ast_filename, Diags, FileSystemOpts,
2355                                  CXXIdx->getOnlyLocalDecls(),
2356                                  0, 0, true);
2357  return MakeCXTranslationUnit(TU);
2358}
2359
2360unsigned clang_defaultEditingTranslationUnitOptions() {
2361  return CXTranslationUnit_PrecompiledPreamble |
2362         CXTranslationUnit_CacheCompletionResults;
2363}
2364
2365CXTranslationUnit
2366clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
2367                                          const char *source_filename,
2368                                          int num_command_line_args,
2369                                          const char * const *command_line_args,
2370                                          unsigned num_unsaved_files,
2371                                          struct CXUnsavedFile *unsaved_files) {
2372  unsigned Options = CXTranslationUnit_DetailedPreprocessingRecord |
2373                     CXTranslationUnit_NestedMacroExpansions;
2374  return clang_parseTranslationUnit(CIdx, source_filename,
2375                                    command_line_args, num_command_line_args,
2376                                    unsaved_files, num_unsaved_files,
2377                                    Options);
2378}
2379
2380struct ParseTranslationUnitInfo {
2381  CXIndex CIdx;
2382  const char *source_filename;
2383  const char *const *command_line_args;
2384  int num_command_line_args;
2385  struct CXUnsavedFile *unsaved_files;
2386  unsigned num_unsaved_files;
2387  unsigned options;
2388  CXTranslationUnit result;
2389};
2390static void clang_parseTranslationUnit_Impl(void *UserData) {
2391  ParseTranslationUnitInfo *PTUI =
2392    static_cast<ParseTranslationUnitInfo*>(UserData);
2393  CXIndex CIdx = PTUI->CIdx;
2394  const char *source_filename = PTUI->source_filename;
2395  const char * const *command_line_args = PTUI->command_line_args;
2396  int num_command_line_args = PTUI->num_command_line_args;
2397  struct CXUnsavedFile *unsaved_files = PTUI->unsaved_files;
2398  unsigned num_unsaved_files = PTUI->num_unsaved_files;
2399  unsigned options = PTUI->options;
2400  PTUI->result = 0;
2401
2402  if (!CIdx)
2403    return;
2404
2405  CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
2406
2407  bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
2408  // FIXME: Add a flag for modules.
2409  TranslationUnitKind TUKind
2410    = (options & CXTranslationUnit_Incomplete)? TU_Prefix : TU_Complete;
2411  bool CacheCodeCompetionResults
2412    = options & CXTranslationUnit_CacheCompletionResults;
2413
2414  // Configure the diagnostics.
2415  DiagnosticOptions DiagOpts;
2416  llvm::IntrusiveRefCntPtr<DiagnosticsEngine>
2417    Diags(CompilerInstance::createDiagnostics(DiagOpts, num_command_line_args,
2418                                                command_line_args));
2419
2420  // Recover resources if we crash before exiting this function.
2421  llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
2422    llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
2423    DiagCleanup(Diags.getPtr());
2424
2425  llvm::OwningPtr<std::vector<ASTUnit::RemappedFile> >
2426    RemappedFiles(new std::vector<ASTUnit::RemappedFile>());
2427
2428  // Recover resources if we crash before exiting this function.
2429  llvm::CrashRecoveryContextCleanupRegistrar<
2430    std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
2431
2432  for (unsigned I = 0; I != num_unsaved_files; ++I) {
2433    StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
2434    const llvm::MemoryBuffer *Buffer
2435      = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
2436    RemappedFiles->push_back(std::make_pair(unsaved_files[I].Filename,
2437                                            Buffer));
2438  }
2439
2440  llvm::OwningPtr<std::vector<const char *> >
2441    Args(new std::vector<const char*>());
2442
2443  // Recover resources if we crash before exiting this method.
2444  llvm::CrashRecoveryContextCleanupRegistrar<std::vector<const char*> >
2445    ArgsCleanup(Args.get());
2446
2447  // Since the Clang C library is primarily used by batch tools dealing with
2448  // (often very broken) source code, where spell-checking can have a
2449  // significant negative impact on performance (particularly when
2450  // precompiled headers are involved), we disable it by default.
2451  // Only do this if we haven't found a spell-checking-related argument.
2452  bool FoundSpellCheckingArgument = false;
2453  for (int I = 0; I != num_command_line_args; ++I) {
2454    if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
2455        strcmp(command_line_args[I], "-fspell-checking") == 0) {
2456      FoundSpellCheckingArgument = true;
2457      break;
2458    }
2459  }
2460  if (!FoundSpellCheckingArgument)
2461    Args->push_back("-fno-spell-checking");
2462
2463  Args->insert(Args->end(), command_line_args,
2464               command_line_args + num_command_line_args);
2465
2466  // The 'source_filename' argument is optional.  If the caller does not
2467  // specify it then it is assumed that the source file is specified
2468  // in the actual argument list.
2469  // Put the source file after command_line_args otherwise if '-x' flag is
2470  // present it will be unused.
2471  if (source_filename)
2472    Args->push_back(source_filename);
2473
2474  // Do we need the detailed preprocessing record?
2475  bool NestedMacroExpansions = false;
2476  if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
2477    Args->push_back("-Xclang");
2478    Args->push_back("-detailed-preprocessing-record");
2479    NestedMacroExpansions
2480      = (options & CXTranslationUnit_NestedMacroExpansions);
2481  }
2482
2483  unsigned NumErrors = Diags->getClient()->getNumErrors();
2484  llvm::OwningPtr<ASTUnit> Unit(
2485    ASTUnit::LoadFromCommandLine(Args->size() ? &(*Args)[0] : 0
2486                                 /* vector::data() not portable */,
2487                                 Args->size() ? (&(*Args)[0] + Args->size()) :0,
2488                                 Diags,
2489                                 CXXIdx->getClangResourcesPath(),
2490                                 CXXIdx->getOnlyLocalDecls(),
2491                                 /*CaptureDiagnostics=*/true,
2492                                 RemappedFiles->size() ? &(*RemappedFiles)[0]:0,
2493                                 RemappedFiles->size(),
2494                                 /*RemappedFilesKeepOriginalName=*/true,
2495                                 PrecompilePreamble,
2496                                 TUKind,
2497                                 CacheCodeCompetionResults,
2498                                 NestedMacroExpansions));
2499
2500  if (NumErrors != Diags->getClient()->getNumErrors()) {
2501    // Make sure to check that 'Unit' is non-NULL.
2502    if (CXXIdx->getDisplayDiagnostics() && Unit.get()) {
2503      for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
2504                                      DEnd = Unit->stored_diag_end();
2505           D != DEnd; ++D) {
2506        CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOptions());
2507        CXString Msg = clang_formatDiagnostic(&Diag,
2508                                    clang_defaultDiagnosticDisplayOptions());
2509        fprintf(stderr, "%s\n", clang_getCString(Msg));
2510        clang_disposeString(Msg);
2511      }
2512#ifdef LLVM_ON_WIN32
2513      // On Windows, force a flush, since there may be multiple copies of
2514      // stderr and stdout in the file system, all with different buffers
2515      // but writing to the same device.
2516      fflush(stderr);
2517#endif
2518    }
2519  }
2520
2521  PTUI->result = MakeCXTranslationUnit(Unit.take());
2522}
2523CXTranslationUnit clang_parseTranslationUnit(CXIndex CIdx,
2524                                             const char *source_filename,
2525                                         const char * const *command_line_args,
2526                                             int num_command_line_args,
2527                                            struct CXUnsavedFile *unsaved_files,
2528                                             unsigned num_unsaved_files,
2529                                             unsigned options) {
2530  ParseTranslationUnitInfo PTUI = { CIdx, source_filename, command_line_args,
2531                                    num_command_line_args, unsaved_files,
2532                                    num_unsaved_files, options, 0 };
2533  llvm::CrashRecoveryContext CRC;
2534
2535  if (!RunSafely(CRC, clang_parseTranslationUnit_Impl, &PTUI)) {
2536    fprintf(stderr, "libclang: crash detected during parsing: {\n");
2537    fprintf(stderr, "  'source_filename' : '%s'\n", source_filename);
2538    fprintf(stderr, "  'command_line_args' : [");
2539    for (int i = 0; i != num_command_line_args; ++i) {
2540      if (i)
2541        fprintf(stderr, ", ");
2542      fprintf(stderr, "'%s'", command_line_args[i]);
2543    }
2544    fprintf(stderr, "],\n");
2545    fprintf(stderr, "  'unsaved_files' : [");
2546    for (unsigned i = 0; i != num_unsaved_files; ++i) {
2547      if (i)
2548        fprintf(stderr, ", ");
2549      fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
2550              unsaved_files[i].Length);
2551    }
2552    fprintf(stderr, "],\n");
2553    fprintf(stderr, "  'options' : %d,\n", options);
2554    fprintf(stderr, "}\n");
2555
2556    return 0;
2557  } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
2558    PrintLibclangResourceUsage(PTUI.result);
2559  }
2560
2561  return PTUI.result;
2562}
2563
2564unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
2565  return CXSaveTranslationUnit_None;
2566}
2567
2568int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
2569                              unsigned options) {
2570  if (!TU)
2571    return CXSaveError_InvalidTU;
2572
2573  CXSaveError result = static_cast<ASTUnit *>(TU->TUData)->Save(FileName);
2574  if (getenv("LIBCLANG_RESOURCE_USAGE"))
2575    PrintLibclangResourceUsage(TU);
2576  return result;
2577}
2578
2579void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
2580  if (CTUnit) {
2581    // If the translation unit has been marked as unsafe to free, just discard
2582    // it.
2583    if (static_cast<ASTUnit *>(CTUnit->TUData)->isUnsafeToFree())
2584      return;
2585
2586    delete static_cast<ASTUnit *>(CTUnit->TUData);
2587    disposeCXStringPool(CTUnit->StringPool);
2588    delete static_cast<CXDiagnosticSetImpl *>(CTUnit->Diagnostics);
2589    delete CTUnit;
2590  }
2591}
2592
2593unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
2594  return CXReparse_None;
2595}
2596
2597struct ReparseTranslationUnitInfo {
2598  CXTranslationUnit TU;
2599  unsigned num_unsaved_files;
2600  struct CXUnsavedFile *unsaved_files;
2601  unsigned options;
2602  int result;
2603};
2604
2605static void clang_reparseTranslationUnit_Impl(void *UserData) {
2606  ReparseTranslationUnitInfo *RTUI =
2607    static_cast<ReparseTranslationUnitInfo*>(UserData);
2608  CXTranslationUnit TU = RTUI->TU;
2609
2610  // Reset the associated diagnostics.
2611  delete static_cast<CXDiagnosticSetImpl*>(TU->Diagnostics);
2612  TU->Diagnostics = 0;
2613
2614  unsigned num_unsaved_files = RTUI->num_unsaved_files;
2615  struct CXUnsavedFile *unsaved_files = RTUI->unsaved_files;
2616  unsigned options = RTUI->options;
2617  (void) options;
2618  RTUI->result = 1;
2619
2620  if (!TU)
2621    return;
2622
2623  ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
2624  ASTUnit::ConcurrencyCheck Check(*CXXUnit);
2625
2626  llvm::OwningPtr<std::vector<ASTUnit::RemappedFile> >
2627    RemappedFiles(new std::vector<ASTUnit::RemappedFile>());
2628
2629  // Recover resources if we crash before exiting this function.
2630  llvm::CrashRecoveryContextCleanupRegistrar<
2631    std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
2632
2633  for (unsigned I = 0; I != num_unsaved_files; ++I) {
2634    StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
2635    const llvm::MemoryBuffer *Buffer
2636      = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
2637    RemappedFiles->push_back(std::make_pair(unsaved_files[I].Filename,
2638                                            Buffer));
2639  }
2640
2641  if (!CXXUnit->Reparse(RemappedFiles->size() ? &(*RemappedFiles)[0] : 0,
2642                        RemappedFiles->size()))
2643    RTUI->result = 0;
2644}
2645
2646int clang_reparseTranslationUnit(CXTranslationUnit TU,
2647                                 unsigned num_unsaved_files,
2648                                 struct CXUnsavedFile *unsaved_files,
2649                                 unsigned options) {
2650  ReparseTranslationUnitInfo RTUI = { TU, num_unsaved_files, unsaved_files,
2651                                      options, 0 };
2652
2653  if (getenv("LIBCLANG_NOTHREADS")) {
2654    clang_reparseTranslationUnit_Impl(&RTUI);
2655    return RTUI.result;
2656  }
2657
2658  llvm::CrashRecoveryContext CRC;
2659
2660  if (!RunSafely(CRC, clang_reparseTranslationUnit_Impl, &RTUI)) {
2661    fprintf(stderr, "libclang: crash detected during reparsing\n");
2662    static_cast<ASTUnit *>(TU->TUData)->setUnsafeToFree(true);
2663    return 1;
2664  } else if (getenv("LIBCLANG_RESOURCE_USAGE"))
2665    PrintLibclangResourceUsage(TU);
2666
2667  return RTUI.result;
2668}
2669
2670
2671CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
2672  if (!CTUnit)
2673    return createCXString("");
2674
2675  ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit->TUData);
2676  return createCXString(CXXUnit->getOriginalSourceFileName(), true);
2677}
2678
2679CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
2680  CXCursor Result = { CXCursor_TranslationUnit, 0, { 0, 0, TU } };
2681  return Result;
2682}
2683
2684} // end: extern "C"
2685
2686//===----------------------------------------------------------------------===//
2687// CXFile Operations.
2688//===----------------------------------------------------------------------===//
2689
2690extern "C" {
2691CXString clang_getFileName(CXFile SFile) {
2692  if (!SFile)
2693    return createCXString((const char*)NULL);
2694
2695  FileEntry *FEnt = static_cast<FileEntry *>(SFile);
2696  return createCXString(FEnt->getName());
2697}
2698
2699time_t clang_getFileTime(CXFile SFile) {
2700  if (!SFile)
2701    return 0;
2702
2703  FileEntry *FEnt = static_cast<FileEntry *>(SFile);
2704  return FEnt->getModificationTime();
2705}
2706
2707CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
2708  if (!tu)
2709    return 0;
2710
2711  ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
2712
2713  FileManager &FMgr = CXXUnit->getFileManager();
2714  return const_cast<FileEntry *>(FMgr.getFile(file_name));
2715}
2716
2717unsigned clang_isFileMultipleIncludeGuarded(CXTranslationUnit tu, CXFile file) {
2718  if (!tu || !file)
2719    return 0;
2720
2721  ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
2722  FileEntry *FEnt = static_cast<FileEntry *>(file);
2723  return CXXUnit->getPreprocessor().getHeaderSearchInfo()
2724                                          .isFileMultipleIncludeGuarded(FEnt);
2725}
2726
2727} // end: extern "C"
2728
2729//===----------------------------------------------------------------------===//
2730// CXCursor Operations.
2731//===----------------------------------------------------------------------===//
2732
2733static Decl *getDeclFromExpr(Stmt *E) {
2734  if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
2735    return getDeclFromExpr(CE->getSubExpr());
2736
2737  if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
2738    return RefExpr->getDecl();
2739  if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2740    return RefExpr->getDecl();
2741  if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
2742    return ME->getMemberDecl();
2743  if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
2744    return RE->getDecl();
2745  if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E))
2746    return PRE->isExplicitProperty() ? PRE->getExplicitProperty() : 0;
2747  if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
2748    return getDeclFromExpr(POE->getSyntacticForm());
2749  if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
2750    if (Expr *Src = OVE->getSourceExpr())
2751      return getDeclFromExpr(Src);
2752
2753  if (CallExpr *CE = dyn_cast<CallExpr>(E))
2754    return getDeclFromExpr(CE->getCallee());
2755  if (CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(E))
2756    if (!CE->isElidable())
2757    return CE->getConstructor();
2758  if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
2759    return OME->getMethodDecl();
2760
2761  if (ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
2762    return PE->getProtocol();
2763  if (SubstNonTypeTemplateParmPackExpr *NTTP
2764                              = dyn_cast<SubstNonTypeTemplateParmPackExpr>(E))
2765    return NTTP->getParameterPack();
2766  if (SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
2767    if (isa<NonTypeTemplateParmDecl>(SizeOfPack->getPack()) ||
2768        isa<ParmVarDecl>(SizeOfPack->getPack()))
2769      return SizeOfPack->getPack();
2770
2771  return 0;
2772}
2773
2774static SourceLocation getLocationFromExpr(Expr *E) {
2775  if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
2776    return getLocationFromExpr(CE->getSubExpr());
2777
2778  if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
2779    return /*FIXME:*/Msg->getLeftLoc();
2780  if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
2781    return DRE->getLocation();
2782  if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2783    return RefExpr->getLocation();
2784  if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
2785    return Member->getMemberLoc();
2786  if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
2787    return Ivar->getLocation();
2788  if (SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
2789    return SizeOfPack->getPackLoc();
2790
2791  return E->getLocStart();
2792}
2793
2794extern "C" {
2795
2796unsigned clang_visitChildren(CXCursor parent,
2797                             CXCursorVisitor visitor,
2798                             CXClientData client_data) {
2799  CursorVisitor CursorVis(getCursorTU(parent), visitor, client_data,
2800                          /*VisitPreprocessorLast=*/false);
2801  return CursorVis.VisitChildren(parent);
2802}
2803
2804#ifndef __has_feature
2805#define __has_feature(x) 0
2806#endif
2807#if __has_feature(blocks)
2808typedef enum CXChildVisitResult
2809     (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent);
2810
2811static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
2812    CXClientData client_data) {
2813  CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
2814  return block(cursor, parent);
2815}
2816#else
2817// If we are compiled with a compiler that doesn't have native blocks support,
2818// define and call the block manually, so the
2819typedef struct _CXChildVisitResult
2820{
2821	void *isa;
2822	int flags;
2823	int reserved;
2824	enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor,
2825                                         CXCursor);
2826} *CXCursorVisitorBlock;
2827
2828static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
2829    CXClientData client_data) {
2830  CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
2831  return block->invoke(block, cursor, parent);
2832}
2833#endif
2834
2835
2836unsigned clang_visitChildrenWithBlock(CXCursor parent,
2837                                      CXCursorVisitorBlock block) {
2838  return clang_visitChildren(parent, visitWithBlock, block);
2839}
2840
2841static CXString getDeclSpelling(Decl *D) {
2842  NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
2843  if (!ND) {
2844    if (ObjCPropertyImplDecl *PropImpl =dyn_cast<ObjCPropertyImplDecl>(D))
2845      if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
2846        return createCXString(Property->getIdentifier()->getName());
2847
2848    return createCXString("");
2849  }
2850
2851  if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
2852    return createCXString(OMD->getSelector().getAsString());
2853
2854  if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
2855    // No, this isn't the same as the code below. getIdentifier() is non-virtual
2856    // and returns different names. NamedDecl returns the class name and
2857    // ObjCCategoryImplDecl returns the category name.
2858    return createCXString(CIMP->getIdentifier()->getNameStart());
2859
2860  if (isa<UsingDirectiveDecl>(D))
2861    return createCXString("");
2862
2863  llvm::SmallString<1024> S;
2864  llvm::raw_svector_ostream os(S);
2865  ND->printName(os);
2866
2867  return createCXString(os.str());
2868}
2869
2870CXString clang_getCursorSpelling(CXCursor C) {
2871  if (clang_isTranslationUnit(C.kind))
2872    return clang_getTranslationUnitSpelling(
2873                            static_cast<CXTranslationUnit>(C.data[2]));
2874
2875  if (clang_isReference(C.kind)) {
2876    switch (C.kind) {
2877    case CXCursor_ObjCSuperClassRef: {
2878      ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
2879      return createCXString(Super->getIdentifier()->getNameStart());
2880    }
2881    case CXCursor_ObjCClassRef: {
2882      ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
2883      return createCXString(Class->getIdentifier()->getNameStart());
2884    }
2885    case CXCursor_ObjCProtocolRef: {
2886      ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
2887      assert(OID && "getCursorSpelling(): Missing protocol decl");
2888      return createCXString(OID->getIdentifier()->getNameStart());
2889    }
2890    case CXCursor_CXXBaseSpecifier: {
2891      CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
2892      return createCXString(B->getType().getAsString());
2893    }
2894    case CXCursor_TypeRef: {
2895      TypeDecl *Type = getCursorTypeRef(C).first;
2896      assert(Type && "Missing type decl");
2897
2898      return createCXString(getCursorContext(C).getTypeDeclType(Type).
2899                              getAsString());
2900    }
2901    case CXCursor_TemplateRef: {
2902      TemplateDecl *Template = getCursorTemplateRef(C).first;
2903      assert(Template && "Missing template decl");
2904
2905      return createCXString(Template->getNameAsString());
2906    }
2907
2908    case CXCursor_NamespaceRef: {
2909      NamedDecl *NS = getCursorNamespaceRef(C).first;
2910      assert(NS && "Missing namespace decl");
2911
2912      return createCXString(NS->getNameAsString());
2913    }
2914
2915    case CXCursor_MemberRef: {
2916      FieldDecl *Field = getCursorMemberRef(C).first;
2917      assert(Field && "Missing member decl");
2918
2919      return createCXString(Field->getNameAsString());
2920    }
2921
2922    case CXCursor_LabelRef: {
2923      LabelStmt *Label = getCursorLabelRef(C).first;
2924      assert(Label && "Missing label");
2925
2926      return createCXString(Label->getName());
2927    }
2928
2929    case CXCursor_OverloadedDeclRef: {
2930      OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
2931      if (Decl *D = Storage.dyn_cast<Decl *>()) {
2932        if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
2933          return createCXString(ND->getNameAsString());
2934        return createCXString("");
2935      }
2936      if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
2937        return createCXString(E->getName().getAsString());
2938      OverloadedTemplateStorage *Ovl
2939        = Storage.get<OverloadedTemplateStorage*>();
2940      if (Ovl->size() == 0)
2941        return createCXString("");
2942      return createCXString((*Ovl->begin())->getNameAsString());
2943    }
2944
2945    default:
2946      return createCXString("<not implemented>");
2947    }
2948  }
2949
2950  if (clang_isExpression(C.kind)) {
2951    Decl *D = getDeclFromExpr(getCursorExpr(C));
2952    if (D)
2953      return getDeclSpelling(D);
2954    return createCXString("");
2955  }
2956
2957  if (clang_isStatement(C.kind)) {
2958    Stmt *S = getCursorStmt(C);
2959    if (LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
2960      return createCXString(Label->getName());
2961
2962    return createCXString("");
2963  }
2964
2965  if (C.kind == CXCursor_MacroExpansion)
2966    return createCXString(getCursorMacroExpansion(C)->getName()
2967                                                           ->getNameStart());
2968
2969  if (C.kind == CXCursor_MacroDefinition)
2970    return createCXString(getCursorMacroDefinition(C)->getName()
2971                                                           ->getNameStart());
2972
2973  if (C.kind == CXCursor_InclusionDirective)
2974    return createCXString(getCursorInclusionDirective(C)->getFileName());
2975
2976  if (clang_isDeclaration(C.kind))
2977    return getDeclSpelling(getCursorDecl(C));
2978
2979  if (C.kind == CXCursor_AnnotateAttr) {
2980    AnnotateAttr *AA = cast<AnnotateAttr>(cxcursor::getCursorAttr(C));
2981    return createCXString(AA->getAnnotation());
2982  }
2983
2984  return createCXString("");
2985}
2986
2987CXString clang_getCursorDisplayName(CXCursor C) {
2988  if (!clang_isDeclaration(C.kind))
2989    return clang_getCursorSpelling(C);
2990
2991  Decl *D = getCursorDecl(C);
2992  if (!D)
2993    return createCXString("");
2994
2995  PrintingPolicy Policy = getCursorContext(C).getPrintingPolicy();
2996  if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
2997    D = FunTmpl->getTemplatedDecl();
2998
2999  if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
3000    llvm::SmallString<64> Str;
3001    llvm::raw_svector_ostream OS(Str);
3002    OS << Function->getNameAsString();
3003    if (Function->getPrimaryTemplate())
3004      OS << "<>";
3005    OS << "(";
3006    for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
3007      if (I)
3008        OS << ", ";
3009      OS << Function->getParamDecl(I)->getType().getAsString(Policy);
3010    }
3011
3012    if (Function->isVariadic()) {
3013      if (Function->getNumParams())
3014        OS << ", ";
3015      OS << "...";
3016    }
3017    OS << ")";
3018    return createCXString(OS.str());
3019  }
3020
3021  if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
3022    llvm::SmallString<64> Str;
3023    llvm::raw_svector_ostream OS(Str);
3024    OS << ClassTemplate->getNameAsString();
3025    OS << "<";
3026    TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
3027    for (unsigned I = 0, N = Params->size(); I != N; ++I) {
3028      if (I)
3029        OS << ", ";
3030
3031      NamedDecl *Param = Params->getParam(I);
3032      if (Param->getIdentifier()) {
3033        OS << Param->getIdentifier()->getName();
3034        continue;
3035      }
3036
3037      // There is no parameter name, which makes this tricky. Try to come up
3038      // with something useful that isn't too long.
3039      if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
3040        OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
3041      else if (NonTypeTemplateParmDecl *NTTP
3042                                    = dyn_cast<NonTypeTemplateParmDecl>(Param))
3043        OS << NTTP->getType().getAsString(Policy);
3044      else
3045        OS << "template<...> class";
3046    }
3047
3048    OS << ">";
3049    return createCXString(OS.str());
3050  }
3051
3052  if (ClassTemplateSpecializationDecl *ClassSpec
3053                              = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
3054    // If the type was explicitly written, use that.
3055    if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
3056      return createCXString(TSInfo->getType().getAsString(Policy));
3057
3058    llvm::SmallString<64> Str;
3059    llvm::raw_svector_ostream OS(Str);
3060    OS << ClassSpec->getNameAsString();
3061    OS << TemplateSpecializationType::PrintTemplateArgumentList(
3062                                      ClassSpec->getTemplateArgs().data(),
3063                                      ClassSpec->getTemplateArgs().size(),
3064                                                                Policy);
3065    return createCXString(OS.str());
3066  }
3067
3068  return clang_getCursorSpelling(C);
3069}
3070
3071CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
3072  switch (Kind) {
3073  case CXCursor_FunctionDecl:
3074      return createCXString("FunctionDecl");
3075  case CXCursor_TypedefDecl:
3076      return createCXString("TypedefDecl");
3077  case CXCursor_EnumDecl:
3078      return createCXString("EnumDecl");
3079  case CXCursor_EnumConstantDecl:
3080      return createCXString("EnumConstantDecl");
3081  case CXCursor_StructDecl:
3082      return createCXString("StructDecl");
3083  case CXCursor_UnionDecl:
3084      return createCXString("UnionDecl");
3085  case CXCursor_ClassDecl:
3086      return createCXString("ClassDecl");
3087  case CXCursor_FieldDecl:
3088      return createCXString("FieldDecl");
3089  case CXCursor_VarDecl:
3090      return createCXString("VarDecl");
3091  case CXCursor_ParmDecl:
3092      return createCXString("ParmDecl");
3093  case CXCursor_ObjCInterfaceDecl:
3094      return createCXString("ObjCInterfaceDecl");
3095  case CXCursor_ObjCCategoryDecl:
3096      return createCXString("ObjCCategoryDecl");
3097  case CXCursor_ObjCProtocolDecl:
3098      return createCXString("ObjCProtocolDecl");
3099  case CXCursor_ObjCPropertyDecl:
3100      return createCXString("ObjCPropertyDecl");
3101  case CXCursor_ObjCIvarDecl:
3102      return createCXString("ObjCIvarDecl");
3103  case CXCursor_ObjCInstanceMethodDecl:
3104      return createCXString("ObjCInstanceMethodDecl");
3105  case CXCursor_ObjCClassMethodDecl:
3106      return createCXString("ObjCClassMethodDecl");
3107  case CXCursor_ObjCImplementationDecl:
3108      return createCXString("ObjCImplementationDecl");
3109  case CXCursor_ObjCCategoryImplDecl:
3110      return createCXString("ObjCCategoryImplDecl");
3111  case CXCursor_CXXMethod:
3112      return createCXString("CXXMethod");
3113  case CXCursor_UnexposedDecl:
3114      return createCXString("UnexposedDecl");
3115  case CXCursor_ObjCSuperClassRef:
3116      return createCXString("ObjCSuperClassRef");
3117  case CXCursor_ObjCProtocolRef:
3118      return createCXString("ObjCProtocolRef");
3119  case CXCursor_ObjCClassRef:
3120      return createCXString("ObjCClassRef");
3121  case CXCursor_TypeRef:
3122      return createCXString("TypeRef");
3123  case CXCursor_TemplateRef:
3124      return createCXString("TemplateRef");
3125  case CXCursor_NamespaceRef:
3126    return createCXString("NamespaceRef");
3127  case CXCursor_MemberRef:
3128    return createCXString("MemberRef");
3129  case CXCursor_LabelRef:
3130    return createCXString("LabelRef");
3131  case CXCursor_OverloadedDeclRef:
3132    return createCXString("OverloadedDeclRef");
3133  case CXCursor_IntegerLiteral:
3134      return createCXString("IntegerLiteral");
3135  case CXCursor_FloatingLiteral:
3136      return createCXString("FloatingLiteral");
3137  case CXCursor_ImaginaryLiteral:
3138      return createCXString("ImaginaryLiteral");
3139  case CXCursor_StringLiteral:
3140      return createCXString("StringLiteral");
3141  case CXCursor_CharacterLiteral:
3142      return createCXString("CharacterLiteral");
3143  case CXCursor_ParenExpr:
3144      return createCXString("ParenExpr");
3145  case CXCursor_UnaryOperator:
3146      return createCXString("UnaryOperator");
3147  case CXCursor_ArraySubscriptExpr:
3148      return createCXString("ArraySubscriptExpr");
3149  case CXCursor_BinaryOperator:
3150      return createCXString("BinaryOperator");
3151  case CXCursor_CompoundAssignOperator:
3152      return createCXString("CompoundAssignOperator");
3153  case CXCursor_ConditionalOperator:
3154      return createCXString("ConditionalOperator");
3155  case CXCursor_CStyleCastExpr:
3156      return createCXString("CStyleCastExpr");
3157  case CXCursor_CompoundLiteralExpr:
3158      return createCXString("CompoundLiteralExpr");
3159  case CXCursor_InitListExpr:
3160      return createCXString("InitListExpr");
3161  case CXCursor_AddrLabelExpr:
3162      return createCXString("AddrLabelExpr");
3163  case CXCursor_StmtExpr:
3164      return createCXString("StmtExpr");
3165  case CXCursor_GenericSelectionExpr:
3166      return createCXString("GenericSelectionExpr");
3167  case CXCursor_GNUNullExpr:
3168      return createCXString("GNUNullExpr");
3169  case CXCursor_CXXStaticCastExpr:
3170      return createCXString("CXXStaticCastExpr");
3171  case CXCursor_CXXDynamicCastExpr:
3172      return createCXString("CXXDynamicCastExpr");
3173  case CXCursor_CXXReinterpretCastExpr:
3174      return createCXString("CXXReinterpretCastExpr");
3175  case CXCursor_CXXConstCastExpr:
3176      return createCXString("CXXConstCastExpr");
3177  case CXCursor_CXXFunctionalCastExpr:
3178      return createCXString("CXXFunctionalCastExpr");
3179  case CXCursor_CXXTypeidExpr:
3180      return createCXString("CXXTypeidExpr");
3181  case CXCursor_CXXBoolLiteralExpr:
3182      return createCXString("CXXBoolLiteralExpr");
3183  case CXCursor_CXXNullPtrLiteralExpr:
3184      return createCXString("CXXNullPtrLiteralExpr");
3185  case CXCursor_CXXThisExpr:
3186      return createCXString("CXXThisExpr");
3187  case CXCursor_CXXThrowExpr:
3188      return createCXString("CXXThrowExpr");
3189  case CXCursor_CXXNewExpr:
3190      return createCXString("CXXNewExpr");
3191  case CXCursor_CXXDeleteExpr:
3192      return createCXString("CXXDeleteExpr");
3193  case CXCursor_UnaryExpr:
3194      return createCXString("UnaryExpr");
3195  case CXCursor_ObjCStringLiteral:
3196      return createCXString("ObjCStringLiteral");
3197  case CXCursor_ObjCEncodeExpr:
3198      return createCXString("ObjCEncodeExpr");
3199  case CXCursor_ObjCSelectorExpr:
3200      return createCXString("ObjCSelectorExpr");
3201  case CXCursor_ObjCProtocolExpr:
3202      return createCXString("ObjCProtocolExpr");
3203  case CXCursor_ObjCBridgedCastExpr:
3204      return createCXString("ObjCBridgedCastExpr");
3205  case CXCursor_BlockExpr:
3206      return createCXString("BlockExpr");
3207  case CXCursor_PackExpansionExpr:
3208      return createCXString("PackExpansionExpr");
3209  case CXCursor_SizeOfPackExpr:
3210      return createCXString("SizeOfPackExpr");
3211  case CXCursor_UnexposedExpr:
3212      return createCXString("UnexposedExpr");
3213  case CXCursor_DeclRefExpr:
3214      return createCXString("DeclRefExpr");
3215  case CXCursor_MemberRefExpr:
3216      return createCXString("MemberRefExpr");
3217  case CXCursor_CallExpr:
3218      return createCXString("CallExpr");
3219  case CXCursor_ObjCMessageExpr:
3220      return createCXString("ObjCMessageExpr");
3221  case CXCursor_UnexposedStmt:
3222      return createCXString("UnexposedStmt");
3223  case CXCursor_DeclStmt:
3224      return createCXString("DeclStmt");
3225  case CXCursor_LabelStmt:
3226      return createCXString("LabelStmt");
3227  case CXCursor_CompoundStmt:
3228      return createCXString("CompoundStmt");
3229  case CXCursor_CaseStmt:
3230      return createCXString("CaseStmt");
3231  case CXCursor_DefaultStmt:
3232      return createCXString("DefaultStmt");
3233  case CXCursor_IfStmt:
3234      return createCXString("IfStmt");
3235  case CXCursor_SwitchStmt:
3236      return createCXString("SwitchStmt");
3237  case CXCursor_WhileStmt:
3238      return createCXString("WhileStmt");
3239  case CXCursor_DoStmt:
3240      return createCXString("DoStmt");
3241  case CXCursor_ForStmt:
3242      return createCXString("ForStmt");
3243  case CXCursor_GotoStmt:
3244      return createCXString("GotoStmt");
3245  case CXCursor_IndirectGotoStmt:
3246      return createCXString("IndirectGotoStmt");
3247  case CXCursor_ContinueStmt:
3248      return createCXString("ContinueStmt");
3249  case CXCursor_BreakStmt:
3250      return createCXString("BreakStmt");
3251  case CXCursor_ReturnStmt:
3252      return createCXString("ReturnStmt");
3253  case CXCursor_AsmStmt:
3254      return createCXString("AsmStmt");
3255  case CXCursor_ObjCAtTryStmt:
3256      return createCXString("ObjCAtTryStmt");
3257  case CXCursor_ObjCAtCatchStmt:
3258      return createCXString("ObjCAtCatchStmt");
3259  case CXCursor_ObjCAtFinallyStmt:
3260      return createCXString("ObjCAtFinallyStmt");
3261  case CXCursor_ObjCAtThrowStmt:
3262      return createCXString("ObjCAtThrowStmt");
3263  case CXCursor_ObjCAtSynchronizedStmt:
3264      return createCXString("ObjCAtSynchronizedStmt");
3265  case CXCursor_ObjCAutoreleasePoolStmt:
3266      return createCXString("ObjCAutoreleasePoolStmt");
3267  case CXCursor_ObjCForCollectionStmt:
3268      return createCXString("ObjCForCollectionStmt");
3269  case CXCursor_CXXCatchStmt:
3270      return createCXString("CXXCatchStmt");
3271  case CXCursor_CXXTryStmt:
3272      return createCXString("CXXTryStmt");
3273  case CXCursor_CXXForRangeStmt:
3274      return createCXString("CXXForRangeStmt");
3275  case CXCursor_SEHTryStmt:
3276      return createCXString("SEHTryStmt");
3277  case CXCursor_SEHExceptStmt:
3278      return createCXString("SEHExceptStmt");
3279  case CXCursor_SEHFinallyStmt:
3280      return createCXString("SEHFinallyStmt");
3281  case CXCursor_NullStmt:
3282      return createCXString("NullStmt");
3283  case CXCursor_InvalidFile:
3284      return createCXString("InvalidFile");
3285  case CXCursor_InvalidCode:
3286    return createCXString("InvalidCode");
3287  case CXCursor_NoDeclFound:
3288      return createCXString("NoDeclFound");
3289  case CXCursor_NotImplemented:
3290      return createCXString("NotImplemented");
3291  case CXCursor_TranslationUnit:
3292      return createCXString("TranslationUnit");
3293  case CXCursor_UnexposedAttr:
3294      return createCXString("UnexposedAttr");
3295  case CXCursor_IBActionAttr:
3296      return createCXString("attribute(ibaction)");
3297  case CXCursor_IBOutletAttr:
3298     return createCXString("attribute(iboutlet)");
3299  case CXCursor_IBOutletCollectionAttr:
3300      return createCXString("attribute(iboutletcollection)");
3301  case CXCursor_CXXFinalAttr:
3302      return createCXString("attribute(final)");
3303  case CXCursor_CXXOverrideAttr:
3304      return createCXString("attribute(override)");
3305  case CXCursor_AnnotateAttr:
3306    return createCXString("attribute(annotate)");
3307  case CXCursor_PreprocessingDirective:
3308    return createCXString("preprocessing directive");
3309  case CXCursor_MacroDefinition:
3310    return createCXString("macro definition");
3311  case CXCursor_MacroExpansion:
3312    return createCXString("macro expansion");
3313  case CXCursor_InclusionDirective:
3314    return createCXString("inclusion directive");
3315  case CXCursor_Namespace:
3316    return createCXString("Namespace");
3317  case CXCursor_LinkageSpec:
3318    return createCXString("LinkageSpec");
3319  case CXCursor_CXXBaseSpecifier:
3320    return createCXString("C++ base class specifier");
3321  case CXCursor_Constructor:
3322    return createCXString("CXXConstructor");
3323  case CXCursor_Destructor:
3324    return createCXString("CXXDestructor");
3325  case CXCursor_ConversionFunction:
3326    return createCXString("CXXConversion");
3327  case CXCursor_TemplateTypeParameter:
3328    return createCXString("TemplateTypeParameter");
3329  case CXCursor_NonTypeTemplateParameter:
3330    return createCXString("NonTypeTemplateParameter");
3331  case CXCursor_TemplateTemplateParameter:
3332    return createCXString("TemplateTemplateParameter");
3333  case CXCursor_FunctionTemplate:
3334    return createCXString("FunctionTemplate");
3335  case CXCursor_ClassTemplate:
3336    return createCXString("ClassTemplate");
3337  case CXCursor_ClassTemplatePartialSpecialization:
3338    return createCXString("ClassTemplatePartialSpecialization");
3339  case CXCursor_NamespaceAlias:
3340    return createCXString("NamespaceAlias");
3341  case CXCursor_UsingDirective:
3342    return createCXString("UsingDirective");
3343  case CXCursor_UsingDeclaration:
3344    return createCXString("UsingDeclaration");
3345  case CXCursor_TypeAliasDecl:
3346    return createCXString("TypeAliasDecl");
3347  case CXCursor_ObjCSynthesizeDecl:
3348    return createCXString("ObjCSynthesizeDecl");
3349  case CXCursor_ObjCDynamicDecl:
3350    return createCXString("ObjCDynamicDecl");
3351  case CXCursor_CXXAccessSpecifier:
3352    return createCXString("CXXAccessSpecifier");
3353  }
3354
3355  llvm_unreachable("Unhandled CXCursorKind");
3356  return createCXString((const char*) 0);
3357}
3358
3359struct GetCursorData {
3360  SourceLocation TokenBeginLoc;
3361  bool PointsAtMacroArgExpansion;
3362  CXCursor &BestCursor;
3363
3364  GetCursorData(SourceManager &SM,
3365                SourceLocation tokenBegin, CXCursor &outputCursor)
3366    : TokenBeginLoc(tokenBegin), BestCursor(outputCursor) {
3367    PointsAtMacroArgExpansion = SM.isMacroArgExpansion(tokenBegin);
3368  }
3369};
3370
3371static enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
3372                                                CXCursor parent,
3373                                                CXClientData client_data) {
3374  GetCursorData *Data = static_cast<GetCursorData *>(client_data);
3375  CXCursor *BestCursor = &Data->BestCursor;
3376
3377  // If we point inside a macro argument we should provide info of what the
3378  // token is so use the actual cursor, don't replace it with a macro expansion
3379  // cursor.
3380  if (cursor.kind == CXCursor_MacroExpansion && Data->PointsAtMacroArgExpansion)
3381    return CXChildVisit_Recurse;
3382
3383  if (clang_isDeclaration(cursor.kind)) {
3384    // Avoid having the implicit methods override the property decls.
3385    if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(getCursorDecl(cursor)))
3386      if (MD->isImplicit())
3387        return CXChildVisit_Break;
3388  }
3389
3390  if (clang_isExpression(cursor.kind) &&
3391      clang_isDeclaration(BestCursor->kind)) {
3392    Decl *D = getCursorDecl(*BestCursor);
3393
3394    // Avoid having the cursor of an expression replace the declaration cursor
3395    // when the expression source range overlaps the declaration range.
3396    // This can happen for C++ constructor expressions whose range generally
3397    // include the variable declaration, e.g.:
3398    //  MyCXXClass foo; // Make sure pointing at 'foo' returns a VarDecl cursor.
3399    if (D->getLocation().isValid() && Data->TokenBeginLoc.isValid() &&
3400        D->getLocation() == Data->TokenBeginLoc)
3401      return CXChildVisit_Break;
3402  }
3403
3404  // If our current best cursor is the construction of a temporary object,
3405  // don't replace that cursor with a type reference, because we want
3406  // clang_getCursor() to point at the constructor.
3407  if (clang_isExpression(BestCursor->kind) &&
3408      isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
3409      cursor.kind == CXCursor_TypeRef) {
3410    // Keep the cursor pointing at CXXTemporaryObjectExpr but also mark it
3411    // as having the actual point on the type reference.
3412    *BestCursor = getTypeRefedCallExprCursor(*BestCursor);
3413    return CXChildVisit_Recurse;
3414  }
3415
3416  *BestCursor = cursor;
3417  return CXChildVisit_Recurse;
3418}
3419
3420CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
3421  if (!TU)
3422    return clang_getNullCursor();
3423
3424  ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
3425  ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3426
3427  SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
3428  CXCursor Result = cxcursor::getCursor(TU, SLoc);
3429
3430  bool Logging = getenv("LIBCLANG_LOGGING");
3431  if (Logging) {
3432    CXFile SearchFile;
3433    unsigned SearchLine, SearchColumn;
3434    CXFile ResultFile;
3435    unsigned ResultLine, ResultColumn;
3436    CXString SearchFileName, ResultFileName, KindSpelling, USR;
3437    const char *IsDef = clang_isCursorDefinition(Result)? " (Definition)" : "";
3438    CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
3439
3440    clang_getExpansionLocation(Loc, &SearchFile, &SearchLine, &SearchColumn, 0);
3441    clang_getExpansionLocation(ResultLoc, &ResultFile, &ResultLine,
3442                               &ResultColumn, 0);
3443    SearchFileName = clang_getFileName(SearchFile);
3444    ResultFileName = clang_getFileName(ResultFile);
3445    KindSpelling = clang_getCursorKindSpelling(Result.kind);
3446    USR = clang_getCursorUSR(Result);
3447    fprintf(stderr, "clang_getCursor(%s:%d:%d) = %s(%s:%d:%d):%s%s\n",
3448            clang_getCString(SearchFileName), SearchLine, SearchColumn,
3449            clang_getCString(KindSpelling),
3450            clang_getCString(ResultFileName), ResultLine, ResultColumn,
3451            clang_getCString(USR), IsDef);
3452    clang_disposeString(SearchFileName);
3453    clang_disposeString(ResultFileName);
3454    clang_disposeString(KindSpelling);
3455    clang_disposeString(USR);
3456
3457    CXCursor Definition = clang_getCursorDefinition(Result);
3458    if (!clang_equalCursors(Definition, clang_getNullCursor())) {
3459      CXSourceLocation DefinitionLoc = clang_getCursorLocation(Definition);
3460      CXString DefinitionKindSpelling
3461                                = clang_getCursorKindSpelling(Definition.kind);
3462      CXFile DefinitionFile;
3463      unsigned DefinitionLine, DefinitionColumn;
3464      clang_getExpansionLocation(DefinitionLoc, &DefinitionFile,
3465                                 &DefinitionLine, &DefinitionColumn, 0);
3466      CXString DefinitionFileName = clang_getFileName(DefinitionFile);
3467      fprintf(stderr, "  -> %s(%s:%d:%d)\n",
3468              clang_getCString(DefinitionKindSpelling),
3469              clang_getCString(DefinitionFileName),
3470              DefinitionLine, DefinitionColumn);
3471      clang_disposeString(DefinitionFileName);
3472      clang_disposeString(DefinitionKindSpelling);
3473    }
3474  }
3475
3476  return Result;
3477}
3478
3479CXCursor clang_getNullCursor(void) {
3480  return MakeCXCursorInvalid(CXCursor_InvalidFile);
3481}
3482
3483unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
3484  return X == Y;
3485}
3486
3487unsigned clang_hashCursor(CXCursor C) {
3488  unsigned Index = 0;
3489  if (clang_isExpression(C.kind) || clang_isStatement(C.kind))
3490    Index = 1;
3491
3492  return llvm::DenseMapInfo<std::pair<unsigned, void*> >::getHashValue(
3493                                        std::make_pair(C.kind, C.data[Index]));
3494}
3495
3496unsigned clang_isInvalid(enum CXCursorKind K) {
3497  return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
3498}
3499
3500unsigned clang_isDeclaration(enum CXCursorKind K) {
3501  return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
3502}
3503
3504unsigned clang_isReference(enum CXCursorKind K) {
3505  return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
3506}
3507
3508unsigned clang_isExpression(enum CXCursorKind K) {
3509  return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
3510}
3511
3512unsigned clang_isStatement(enum CXCursorKind K) {
3513  return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
3514}
3515
3516unsigned clang_isAttribute(enum CXCursorKind K) {
3517    return K >= CXCursor_FirstAttr && K <= CXCursor_LastAttr;
3518}
3519
3520unsigned clang_isTranslationUnit(enum CXCursorKind K) {
3521  return K == CXCursor_TranslationUnit;
3522}
3523
3524unsigned clang_isPreprocessing(enum CXCursorKind K) {
3525  return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
3526}
3527
3528unsigned clang_isUnexposed(enum CXCursorKind K) {
3529  switch (K) {
3530    case CXCursor_UnexposedDecl:
3531    case CXCursor_UnexposedExpr:
3532    case CXCursor_UnexposedStmt:
3533    case CXCursor_UnexposedAttr:
3534      return true;
3535    default:
3536      return false;
3537  }
3538}
3539
3540CXCursorKind clang_getCursorKind(CXCursor C) {
3541  return C.kind;
3542}
3543
3544CXSourceLocation clang_getCursorLocation(CXCursor C) {
3545  if (clang_isReference(C.kind)) {
3546    switch (C.kind) {
3547    case CXCursor_ObjCSuperClassRef: {
3548      std::pair<ObjCInterfaceDecl *, SourceLocation> P
3549        = getCursorObjCSuperClassRef(C);
3550      return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3551    }
3552
3553    case CXCursor_ObjCProtocolRef: {
3554      std::pair<ObjCProtocolDecl *, SourceLocation> P
3555        = getCursorObjCProtocolRef(C);
3556      return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3557    }
3558
3559    case CXCursor_ObjCClassRef: {
3560      std::pair<ObjCInterfaceDecl *, SourceLocation> P
3561        = getCursorObjCClassRef(C);
3562      return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3563    }
3564
3565    case CXCursor_TypeRef: {
3566      std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
3567      return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3568    }
3569
3570    case CXCursor_TemplateRef: {
3571      std::pair<TemplateDecl *, SourceLocation> P = getCursorTemplateRef(C);
3572      return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3573    }
3574
3575    case CXCursor_NamespaceRef: {
3576      std::pair<NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
3577      return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3578    }
3579
3580    case CXCursor_MemberRef: {
3581      std::pair<FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
3582      return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3583    }
3584
3585    case CXCursor_CXXBaseSpecifier: {
3586      CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
3587      if (!BaseSpec)
3588        return clang_getNullLocation();
3589
3590      if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
3591        return cxloc::translateSourceLocation(getCursorContext(C),
3592                                            TSInfo->getTypeLoc().getBeginLoc());
3593
3594      return cxloc::translateSourceLocation(getCursorContext(C),
3595                                        BaseSpec->getSourceRange().getBegin());
3596    }
3597
3598    case CXCursor_LabelRef: {
3599      std::pair<LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
3600      return cxloc::translateSourceLocation(getCursorContext(C), P.second);
3601    }
3602
3603    case CXCursor_OverloadedDeclRef:
3604      return cxloc::translateSourceLocation(getCursorContext(C),
3605                                          getCursorOverloadedDeclRef(C).second);
3606
3607    default:
3608      // FIXME: Need a way to enumerate all non-reference cases.
3609      llvm_unreachable("Missed a reference kind");
3610    }
3611  }
3612
3613  if (clang_isExpression(C.kind))
3614    return cxloc::translateSourceLocation(getCursorContext(C),
3615                                   getLocationFromExpr(getCursorExpr(C)));
3616
3617  if (clang_isStatement(C.kind))
3618    return cxloc::translateSourceLocation(getCursorContext(C),
3619                                          getCursorStmt(C)->getLocStart());
3620
3621  if (C.kind == CXCursor_PreprocessingDirective) {
3622    SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
3623    return cxloc::translateSourceLocation(getCursorContext(C), L);
3624  }
3625
3626  if (C.kind == CXCursor_MacroExpansion) {
3627    SourceLocation L
3628      = cxcursor::getCursorMacroExpansion(C)->getSourceRange().getBegin();
3629    return cxloc::translateSourceLocation(getCursorContext(C), L);
3630  }
3631
3632  if (C.kind == CXCursor_MacroDefinition) {
3633    SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
3634    return cxloc::translateSourceLocation(getCursorContext(C), L);
3635  }
3636
3637  if (C.kind == CXCursor_InclusionDirective) {
3638    SourceLocation L
3639      = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
3640    return cxloc::translateSourceLocation(getCursorContext(C), L);
3641  }
3642
3643  if (C.kind < CXCursor_FirstDecl || C.kind > CXCursor_LastDecl)
3644    return clang_getNullLocation();
3645
3646  Decl *D = getCursorDecl(C);
3647  SourceLocation Loc = D->getLocation();
3648  // FIXME: Multiple variables declared in a single declaration
3649  // currently lack the information needed to correctly determine their
3650  // ranges when accounting for the type-specifier.  We use context
3651  // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3652  // and if so, whether it is the first decl.
3653  if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3654    if (!cxcursor::isFirstInDeclGroup(C))
3655      Loc = VD->getLocation();
3656  }
3657
3658  return cxloc::translateSourceLocation(getCursorContext(C), Loc);
3659}
3660
3661} // end extern "C"
3662
3663CXCursor cxcursor::getCursor(CXTranslationUnit TU, SourceLocation SLoc) {
3664  assert(TU);
3665
3666  // Guard against an invalid SourceLocation, or we may assert in one
3667  // of the following calls.
3668  if (SLoc.isInvalid())
3669    return clang_getNullCursor();
3670
3671  ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
3672
3673  // Translate the given source location to make it point at the beginning of
3674  // the token under the cursor.
3675  SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
3676                                    CXXUnit->getASTContext().getLangOptions());
3677
3678  CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
3679  if (SLoc.isValid()) {
3680    GetCursorData ResultData(CXXUnit->getSourceManager(), SLoc, Result);
3681    CursorVisitor CursorVis(TU, GetCursorVisitor, &ResultData,
3682                            /*VisitPreprocessorLast=*/true,
3683                            /*VisitIncludedEntities=*/false,
3684                            SourceLocation(SLoc));
3685    CursorVis.visitFileRegion();
3686  }
3687
3688  return Result;
3689}
3690
3691static SourceRange getRawCursorExtent(CXCursor C) {
3692  if (clang_isReference(C.kind)) {
3693    switch (C.kind) {
3694    case CXCursor_ObjCSuperClassRef:
3695      return  getCursorObjCSuperClassRef(C).second;
3696
3697    case CXCursor_ObjCProtocolRef:
3698      return getCursorObjCProtocolRef(C).second;
3699
3700    case CXCursor_ObjCClassRef:
3701      return getCursorObjCClassRef(C).second;
3702
3703    case CXCursor_TypeRef:
3704      return getCursorTypeRef(C).second;
3705
3706    case CXCursor_TemplateRef:
3707      return getCursorTemplateRef(C).second;
3708
3709    case CXCursor_NamespaceRef:
3710      return getCursorNamespaceRef(C).second;
3711
3712    case CXCursor_MemberRef:
3713      return getCursorMemberRef(C).second;
3714
3715    case CXCursor_CXXBaseSpecifier:
3716      return getCursorCXXBaseSpecifier(C)->getSourceRange();
3717
3718    case CXCursor_LabelRef:
3719      return getCursorLabelRef(C).second;
3720
3721    case CXCursor_OverloadedDeclRef:
3722      return getCursorOverloadedDeclRef(C).second;
3723
3724    default:
3725      // FIXME: Need a way to enumerate all non-reference cases.
3726      llvm_unreachable("Missed a reference kind");
3727    }
3728  }
3729
3730  if (clang_isExpression(C.kind))
3731    return getCursorExpr(C)->getSourceRange();
3732
3733  if (clang_isStatement(C.kind))
3734    return getCursorStmt(C)->getSourceRange();
3735
3736  if (clang_isAttribute(C.kind))
3737    return getCursorAttr(C)->getRange();
3738
3739  if (C.kind == CXCursor_PreprocessingDirective)
3740    return cxcursor::getCursorPreprocessingDirective(C);
3741
3742  if (C.kind == CXCursor_MacroExpansion) {
3743    ASTUnit *TU = getCursorASTUnit(C);
3744    SourceRange Range = cxcursor::getCursorMacroExpansion(C)->getSourceRange();
3745    return TU->mapRangeFromPreamble(Range);
3746  }
3747
3748  if (C.kind == CXCursor_MacroDefinition) {
3749    ASTUnit *TU = getCursorASTUnit(C);
3750    SourceRange Range = cxcursor::getCursorMacroDefinition(C)->getSourceRange();
3751    return TU->mapRangeFromPreamble(Range);
3752  }
3753
3754  if (C.kind == CXCursor_InclusionDirective) {
3755    ASTUnit *TU = getCursorASTUnit(C);
3756    SourceRange Range = cxcursor::getCursorInclusionDirective(C)->getSourceRange();
3757    return TU->mapRangeFromPreamble(Range);
3758  }
3759
3760  if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
3761    Decl *D = cxcursor::getCursorDecl(C);
3762    SourceRange R = D->getSourceRange();
3763    // FIXME: Multiple variables declared in a single declaration
3764    // currently lack the information needed to correctly determine their
3765    // ranges when accounting for the type-specifier.  We use context
3766    // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3767    // and if so, whether it is the first decl.
3768    if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3769      if (!cxcursor::isFirstInDeclGroup(C))
3770        R.setBegin(VD->getLocation());
3771    }
3772    return R;
3773  }
3774  return SourceRange();
3775}
3776
3777/// \brief Retrieves the "raw" cursor extent, which is then extended to include
3778/// the decl-specifier-seq for declarations.
3779static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr) {
3780  if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
3781    Decl *D = cxcursor::getCursorDecl(C);
3782    SourceRange R = D->getSourceRange();
3783
3784    // Adjust the start of the location for declarations preceded by
3785    // declaration specifiers.
3786    SourceLocation StartLoc;
3787    if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
3788      if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
3789        StartLoc = TI->getTypeLoc().getSourceRange().getBegin();
3790    } else if (TypedefDecl *Typedef = dyn_cast<TypedefDecl>(D)) {
3791      if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
3792        StartLoc = TI->getTypeLoc().getSourceRange().getBegin();
3793    }
3794
3795    if (StartLoc.isValid() && R.getBegin().isValid() &&
3796        SrcMgr.isBeforeInTranslationUnit(StartLoc, R.getBegin()))
3797      R.setBegin(StartLoc);
3798
3799    // FIXME: Multiple variables declared in a single declaration
3800    // currently lack the information needed to correctly determine their
3801    // ranges when accounting for the type-specifier.  We use context
3802    // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3803    // and if so, whether it is the first decl.
3804    if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3805      if (!cxcursor::isFirstInDeclGroup(C))
3806        R.setBegin(VD->getLocation());
3807    }
3808
3809    return R;
3810  }
3811
3812  return getRawCursorExtent(C);
3813}
3814
3815extern "C" {
3816
3817CXSourceRange clang_getCursorExtent(CXCursor C) {
3818  SourceRange R = getRawCursorExtent(C);
3819  if (R.isInvalid())
3820    return clang_getNullRange();
3821
3822  return cxloc::translateSourceRange(getCursorContext(C), R);
3823}
3824
3825CXCursor clang_getCursorReferenced(CXCursor C) {
3826  if (clang_isInvalid(C.kind))
3827    return clang_getNullCursor();
3828
3829  CXTranslationUnit tu = getCursorTU(C);
3830  if (clang_isDeclaration(C.kind)) {
3831    Decl *D = getCursorDecl(C);
3832    if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
3833      return MakeCursorOverloadedDeclRef(Using, D->getLocation(), tu);
3834    if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
3835      return MakeCursorOverloadedDeclRef(Classes, D->getLocation(), tu);
3836    if (ObjCForwardProtocolDecl *Protocols
3837                                        = dyn_cast<ObjCForwardProtocolDecl>(D))
3838      return MakeCursorOverloadedDeclRef(Protocols, D->getLocation(), tu);
3839    if (ObjCPropertyImplDecl *PropImpl =dyn_cast<ObjCPropertyImplDecl>(D))
3840      if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
3841        return MakeCXCursor(Property, tu);
3842
3843    return C;
3844  }
3845
3846  if (clang_isExpression(C.kind)) {
3847    Expr *E = getCursorExpr(C);
3848    Decl *D = getDeclFromExpr(E);
3849    if (D) {
3850      CXCursor declCursor = MakeCXCursor(D, tu);
3851      declCursor = getSelectorIdentifierCursor(getSelectorIdentifierIndex(C),
3852                                               declCursor);
3853      return declCursor;
3854    }
3855
3856    if (OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
3857      return MakeCursorOverloadedDeclRef(Ovl, tu);
3858
3859    return clang_getNullCursor();
3860  }
3861
3862  if (clang_isStatement(C.kind)) {
3863    Stmt *S = getCursorStmt(C);
3864    if (GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
3865      if (LabelDecl *label = Goto->getLabel())
3866        if (LabelStmt *labelS = label->getStmt())
3867        return MakeCXCursor(labelS, getCursorDecl(C), tu);
3868
3869    return clang_getNullCursor();
3870  }
3871
3872  if (C.kind == CXCursor_MacroExpansion) {
3873    if (MacroDefinition *Def = getCursorMacroExpansion(C)->getDefinition())
3874      return MakeMacroDefinitionCursor(Def, tu);
3875  }
3876
3877  if (!clang_isReference(C.kind))
3878    return clang_getNullCursor();
3879
3880  switch (C.kind) {
3881    case CXCursor_ObjCSuperClassRef:
3882      return MakeCXCursor(getCursorObjCSuperClassRef(C).first, tu);
3883
3884    case CXCursor_ObjCProtocolRef: {
3885      return MakeCXCursor(getCursorObjCProtocolRef(C).first, tu);
3886
3887    case CXCursor_ObjCClassRef:
3888      return MakeCXCursor(getCursorObjCClassRef(C).first, tu );
3889
3890    case CXCursor_TypeRef:
3891      return MakeCXCursor(getCursorTypeRef(C).first, tu );
3892
3893    case CXCursor_TemplateRef:
3894      return MakeCXCursor(getCursorTemplateRef(C).first, tu );
3895
3896    case CXCursor_NamespaceRef:
3897      return MakeCXCursor(getCursorNamespaceRef(C).first, tu );
3898
3899    case CXCursor_MemberRef:
3900      return MakeCXCursor(getCursorMemberRef(C).first, tu );
3901
3902    case CXCursor_CXXBaseSpecifier: {
3903      CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
3904      return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
3905                                                         tu ));
3906    }
3907
3908    case CXCursor_LabelRef:
3909      // FIXME: We end up faking the "parent" declaration here because we
3910      // don't want to make CXCursor larger.
3911      return MakeCXCursor(getCursorLabelRef(C).first,
3912               static_cast<ASTUnit*>(tu->TUData)->getASTContext()
3913                          .getTranslationUnitDecl(),
3914                          tu);
3915
3916    case CXCursor_OverloadedDeclRef:
3917      return C;
3918
3919    default:
3920      // We would prefer to enumerate all non-reference cursor kinds here.
3921      llvm_unreachable("Unhandled reference cursor kind");
3922      break;
3923    }
3924  }
3925
3926  return clang_getNullCursor();
3927}
3928
3929CXCursor clang_getCursorDefinition(CXCursor C) {
3930  if (clang_isInvalid(C.kind))
3931    return clang_getNullCursor();
3932
3933  CXTranslationUnit TU = getCursorTU(C);
3934
3935  bool WasReference = false;
3936  if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
3937    C = clang_getCursorReferenced(C);
3938    WasReference = true;
3939  }
3940
3941  if (C.kind == CXCursor_MacroExpansion)
3942    return clang_getCursorReferenced(C);
3943
3944  if (!clang_isDeclaration(C.kind))
3945    return clang_getNullCursor();
3946
3947  Decl *D = getCursorDecl(C);
3948  if (!D)
3949    return clang_getNullCursor();
3950
3951  switch (D->getKind()) {
3952  // Declaration kinds that don't really separate the notions of
3953  // declaration and definition.
3954  case Decl::Namespace:
3955  case Decl::Typedef:
3956  case Decl::TypeAlias:
3957  case Decl::TypeAliasTemplate:
3958  case Decl::TemplateTypeParm:
3959  case Decl::EnumConstant:
3960  case Decl::Field:
3961  case Decl::IndirectField:
3962  case Decl::ObjCIvar:
3963  case Decl::ObjCAtDefsField:
3964  case Decl::ImplicitParam:
3965  case Decl::ParmVar:
3966  case Decl::NonTypeTemplateParm:
3967  case Decl::TemplateTemplateParm:
3968  case Decl::ObjCCategoryImpl:
3969  case Decl::ObjCImplementation:
3970  case Decl::AccessSpec:
3971  case Decl::LinkageSpec:
3972  case Decl::ObjCPropertyImpl:
3973  case Decl::FileScopeAsm:
3974  case Decl::StaticAssert:
3975  case Decl::Block:
3976  case Decl::Label:  // FIXME: Is this right??
3977  case Decl::ClassScopeFunctionSpecialization:
3978    return C;
3979
3980  // Declaration kinds that don't make any sense here, but are
3981  // nonetheless harmless.
3982  case Decl::TranslationUnit:
3983    break;
3984
3985  // Declaration kinds for which the definition is not resolvable.
3986  case Decl::UnresolvedUsingTypename:
3987  case Decl::UnresolvedUsingValue:
3988    break;
3989
3990  case Decl::UsingDirective:
3991    return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
3992                        TU);
3993
3994  case Decl::NamespaceAlias:
3995    return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), TU);
3996
3997  case Decl::Enum:
3998  case Decl::Record:
3999  case Decl::CXXRecord:
4000  case Decl::ClassTemplateSpecialization:
4001  case Decl::ClassTemplatePartialSpecialization:
4002    if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
4003      return MakeCXCursor(Def, TU);
4004    return clang_getNullCursor();
4005
4006  case Decl::Function:
4007  case Decl::CXXMethod:
4008  case Decl::CXXConstructor:
4009  case Decl::CXXDestructor:
4010  case Decl::CXXConversion: {
4011    const FunctionDecl *Def = 0;
4012    if (cast<FunctionDecl>(D)->getBody(Def))
4013      return MakeCXCursor(const_cast<FunctionDecl *>(Def), TU);
4014    return clang_getNullCursor();
4015  }
4016
4017  case Decl::Var: {
4018    // Ask the variable if it has a definition.
4019    if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
4020      return MakeCXCursor(Def, TU);
4021    return clang_getNullCursor();
4022  }
4023
4024  case Decl::FunctionTemplate: {
4025    const FunctionDecl *Def = 0;
4026    if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
4027      return MakeCXCursor(Def->getDescribedFunctionTemplate(), TU);
4028    return clang_getNullCursor();
4029  }
4030
4031  case Decl::ClassTemplate: {
4032    if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
4033                                                            ->getDefinition())
4034      return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
4035                          TU);
4036    return clang_getNullCursor();
4037  }
4038
4039  case Decl::Using:
4040    return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
4041                                       D->getLocation(), TU);
4042
4043  case Decl::UsingShadow:
4044    return clang_getCursorDefinition(
4045                       MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
4046                                    TU));
4047
4048  case Decl::ObjCMethod: {
4049    ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
4050    if (Method->isThisDeclarationADefinition())
4051      return C;
4052
4053    // Dig out the method definition in the associated
4054    // @implementation, if we have it.
4055    // FIXME: The ASTs should make finding the definition easier.
4056    if (ObjCInterfaceDecl *Class
4057                       = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
4058      if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
4059        if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
4060                                                  Method->isInstanceMethod()))
4061          if (Def->isThisDeclarationADefinition())
4062            return MakeCXCursor(Def, TU);
4063
4064    return clang_getNullCursor();
4065  }
4066
4067  case Decl::ObjCCategory:
4068    if (ObjCCategoryImplDecl *Impl
4069                               = cast<ObjCCategoryDecl>(D)->getImplementation())
4070      return MakeCXCursor(Impl, TU);
4071    return clang_getNullCursor();
4072
4073  case Decl::ObjCProtocol:
4074    if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
4075      return C;
4076    return clang_getNullCursor();
4077
4078  case Decl::ObjCInterface:
4079    // There are two notions of a "definition" for an Objective-C
4080    // class: the interface and its implementation. When we resolved a
4081    // reference to an Objective-C class, produce the @interface as
4082    // the definition; when we were provided with the interface,
4083    // produce the @implementation as the definition.
4084    if (WasReference) {
4085      if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
4086        return C;
4087    } else if (ObjCImplementationDecl *Impl
4088                              = cast<ObjCInterfaceDecl>(D)->getImplementation())
4089      return MakeCXCursor(Impl, TU);
4090    return clang_getNullCursor();
4091
4092  case Decl::ObjCProperty:
4093    // FIXME: We don't really know where to find the
4094    // ObjCPropertyImplDecls that implement this property.
4095    return clang_getNullCursor();
4096
4097  case Decl::ObjCCompatibleAlias:
4098    if (ObjCInterfaceDecl *Class
4099          = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
4100      if (!Class->isForwardDecl())
4101        return MakeCXCursor(Class, TU);
4102
4103    return clang_getNullCursor();
4104
4105  case Decl::ObjCForwardProtocol:
4106    return MakeCursorOverloadedDeclRef(cast<ObjCForwardProtocolDecl>(D),
4107                                       D->getLocation(), TU);
4108
4109  case Decl::ObjCClass:
4110    return MakeCursorOverloadedDeclRef(cast<ObjCClassDecl>(D), D->getLocation(),
4111                                       TU);
4112
4113  case Decl::Friend:
4114    if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
4115      return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
4116    return clang_getNullCursor();
4117
4118  case Decl::FriendTemplate:
4119    if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
4120      return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
4121    return clang_getNullCursor();
4122  }
4123
4124  return clang_getNullCursor();
4125}
4126
4127unsigned clang_isCursorDefinition(CXCursor C) {
4128  if (!clang_isDeclaration(C.kind))
4129    return 0;
4130
4131  return clang_getCursorDefinition(C) == C;
4132}
4133
4134CXCursor clang_getCanonicalCursor(CXCursor C) {
4135  if (!clang_isDeclaration(C.kind))
4136    return C;
4137
4138  if (Decl *D = getCursorDecl(C)) {
4139    if (ObjCCategoryImplDecl *CatImplD = dyn_cast<ObjCCategoryImplDecl>(D))
4140      if (ObjCCategoryDecl *CatD = CatImplD->getCategoryDecl())
4141        return MakeCXCursor(CatD, getCursorTU(C));
4142
4143    if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
4144      if (ObjCInterfaceDecl *IFD = ImplD->getClassInterface())
4145        return MakeCXCursor(IFD, getCursorTU(C));
4146
4147    return MakeCXCursor(D->getCanonicalDecl(), getCursorTU(C));
4148  }
4149
4150  return C;
4151}
4152
4153unsigned clang_getNumOverloadedDecls(CXCursor C) {
4154  if (C.kind != CXCursor_OverloadedDeclRef)
4155    return 0;
4156
4157  OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
4158  if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
4159    return E->getNumDecls();
4160
4161  if (OverloadedTemplateStorage *S
4162                              = Storage.dyn_cast<OverloadedTemplateStorage*>())
4163    return S->size();
4164
4165  Decl *D = Storage.get<Decl*>();
4166  if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
4167    return Using->shadow_size();
4168  if (isa<ObjCClassDecl>(D))
4169    return 1;
4170  if (ObjCForwardProtocolDecl *Protocols =dyn_cast<ObjCForwardProtocolDecl>(D))
4171    return Protocols->protocol_size();
4172
4173  return 0;
4174}
4175
4176CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
4177  if (cursor.kind != CXCursor_OverloadedDeclRef)
4178    return clang_getNullCursor();
4179
4180  if (index >= clang_getNumOverloadedDecls(cursor))
4181    return clang_getNullCursor();
4182
4183  CXTranslationUnit TU = getCursorTU(cursor);
4184  OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
4185  if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
4186    return MakeCXCursor(E->decls_begin()[index], TU);
4187
4188  if (OverloadedTemplateStorage *S
4189                              = Storage.dyn_cast<OverloadedTemplateStorage*>())
4190    return MakeCXCursor(S->begin()[index], TU);
4191
4192  Decl *D = Storage.get<Decl*>();
4193  if (UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
4194    // FIXME: This is, unfortunately, linear time.
4195    UsingDecl::shadow_iterator Pos = Using->shadow_begin();
4196    std::advance(Pos, index);
4197    return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), TU);
4198  }
4199  if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
4200    return MakeCXCursor(Classes->getForwardInterfaceDecl(), TU);
4201  if (ObjCForwardProtocolDecl *Protocols = dyn_cast<ObjCForwardProtocolDecl>(D))
4202    return MakeCXCursor(Protocols->protocol_begin()[index], TU);
4203
4204  return clang_getNullCursor();
4205}
4206
4207void clang_getDefinitionSpellingAndExtent(CXCursor C,
4208                                          const char **startBuf,
4209                                          const char **endBuf,
4210                                          unsigned *startLine,
4211                                          unsigned *startColumn,
4212                                          unsigned *endLine,
4213                                          unsigned *endColumn) {
4214  assert(getCursorDecl(C) && "CXCursor has null decl");
4215  NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
4216  FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
4217  CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
4218
4219  SourceManager &SM = FD->getASTContext().getSourceManager();
4220  *startBuf = SM.getCharacterData(Body->getLBracLoc());
4221  *endBuf = SM.getCharacterData(Body->getRBracLoc());
4222  *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
4223  *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
4224  *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
4225  *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
4226}
4227
4228
4229CXSourceRange clang_getCursorReferenceNameRange(CXCursor C, unsigned NameFlags,
4230                                                unsigned PieceIndex) {
4231  RefNamePieces Pieces;
4232
4233  switch (C.kind) {
4234  case CXCursor_MemberRefExpr:
4235    if (MemberExpr *E = dyn_cast<MemberExpr>(getCursorExpr(C)))
4236      Pieces = buildPieces(NameFlags, true, E->getMemberNameInfo(),
4237                           E->getQualifierLoc().getSourceRange());
4238    break;
4239
4240  case CXCursor_DeclRefExpr:
4241    if (DeclRefExpr *E = dyn_cast<DeclRefExpr>(getCursorExpr(C)))
4242      Pieces = buildPieces(NameFlags, false, E->getNameInfo(),
4243                           E->getQualifierLoc().getSourceRange(),
4244                           E->getExplicitTemplateArgsOpt());
4245    break;
4246
4247  case CXCursor_CallExpr:
4248    if (CXXOperatorCallExpr *OCE =
4249        dyn_cast<CXXOperatorCallExpr>(getCursorExpr(C))) {
4250      Expr *Callee = OCE->getCallee();
4251      if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Callee))
4252        Callee = ICE->getSubExpr();
4253
4254      if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Callee))
4255        Pieces = buildPieces(NameFlags, false, DRE->getNameInfo(),
4256                             DRE->getQualifierLoc().getSourceRange());
4257    }
4258    break;
4259
4260  default:
4261    break;
4262  }
4263
4264  if (Pieces.empty()) {
4265    if (PieceIndex == 0)
4266      return clang_getCursorExtent(C);
4267  } else if (PieceIndex < Pieces.size()) {
4268      SourceRange R = Pieces[PieceIndex];
4269      if (R.isValid())
4270        return cxloc::translateSourceRange(getCursorContext(C), R);
4271  }
4272
4273  return clang_getNullRange();
4274}
4275
4276void clang_enableStackTraces(void) {
4277  llvm::sys::PrintStackTraceOnErrorSignal();
4278}
4279
4280void clang_executeOnThread(void (*fn)(void*), void *user_data,
4281                           unsigned stack_size) {
4282  llvm::llvm_execute_on_thread(fn, user_data, stack_size);
4283}
4284
4285} // end: extern "C"
4286
4287//===----------------------------------------------------------------------===//
4288// Token-based Operations.
4289//===----------------------------------------------------------------------===//
4290
4291/* CXToken layout:
4292 *   int_data[0]: a CXTokenKind
4293 *   int_data[1]: starting token location
4294 *   int_data[2]: token length
4295 *   int_data[3]: reserved
4296 *   ptr_data: for identifiers and keywords, an IdentifierInfo*.
4297 *   otherwise unused.
4298 */
4299extern "C" {
4300
4301CXTokenKind clang_getTokenKind(CXToken CXTok) {
4302  return static_cast<CXTokenKind>(CXTok.int_data[0]);
4303}
4304
4305CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
4306  switch (clang_getTokenKind(CXTok)) {
4307  case CXToken_Identifier:
4308  case CXToken_Keyword:
4309    // We know we have an IdentifierInfo*, so use that.
4310    return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
4311                            ->getNameStart());
4312
4313  case CXToken_Literal: {
4314    // We have stashed the starting pointer in the ptr_data field. Use it.
4315    const char *Text = static_cast<const char *>(CXTok.ptr_data);
4316    return createCXString(StringRef(Text, CXTok.int_data[2]));
4317  }
4318
4319  case CXToken_Punctuation:
4320  case CXToken_Comment:
4321    break;
4322  }
4323
4324  // We have to find the starting buffer pointer the hard way, by
4325  // deconstructing the source location.
4326  ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
4327  if (!CXXUnit)
4328    return createCXString("");
4329
4330  SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
4331  std::pair<FileID, unsigned> LocInfo
4332    = CXXUnit->getSourceManager().getDecomposedSpellingLoc(Loc);
4333  bool Invalid = false;
4334  StringRef Buffer
4335    = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
4336  if (Invalid)
4337    return createCXString("");
4338
4339  return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
4340}
4341
4342CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
4343  ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
4344  if (!CXXUnit)
4345    return clang_getNullLocation();
4346
4347  return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
4348                        SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
4349}
4350
4351CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
4352  ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
4353  if (!CXXUnit)
4354    return clang_getNullRange();
4355
4356  return cxloc::translateSourceRange(CXXUnit->getASTContext(),
4357                        SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
4358}
4359
4360static void getTokens(ASTUnit *CXXUnit, SourceRange Range,
4361                      SmallVectorImpl<CXToken> &CXTokens) {
4362  SourceManager &SourceMgr = CXXUnit->getSourceManager();
4363  std::pair<FileID, unsigned> BeginLocInfo
4364    = SourceMgr.getDecomposedLoc(Range.getBegin());
4365  std::pair<FileID, unsigned> EndLocInfo
4366    = SourceMgr.getDecomposedLoc(Range.getEnd());
4367
4368  // Cannot tokenize across files.
4369  if (BeginLocInfo.first != EndLocInfo.first)
4370    return;
4371
4372  // Create a lexer
4373  bool Invalid = false;
4374  StringRef Buffer
4375    = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
4376  if (Invalid)
4377    return;
4378
4379  Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
4380            CXXUnit->getASTContext().getLangOptions(),
4381            Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
4382  Lex.SetCommentRetentionState(true);
4383
4384  // Lex tokens until we hit the end of the range.
4385  const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
4386  Token Tok;
4387  bool previousWasAt = false;
4388  do {
4389    // Lex the next token
4390    Lex.LexFromRawLexer(Tok);
4391    if (Tok.is(tok::eof))
4392      break;
4393
4394    // Initialize the CXToken.
4395    CXToken CXTok;
4396
4397    //   - Common fields
4398    CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
4399    CXTok.int_data[2] = Tok.getLength();
4400    CXTok.int_data[3] = 0;
4401
4402    //   - Kind-specific fields
4403    if (Tok.isLiteral()) {
4404      CXTok.int_data[0] = CXToken_Literal;
4405      CXTok.ptr_data = (void *)Tok.getLiteralData();
4406    } else if (Tok.is(tok::raw_identifier)) {
4407      // Lookup the identifier to determine whether we have a keyword.
4408      IdentifierInfo *II
4409        = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok);
4410
4411      if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
4412        CXTok.int_data[0] = CXToken_Keyword;
4413      }
4414      else {
4415        CXTok.int_data[0] = Tok.is(tok::identifier)
4416          ? CXToken_Identifier
4417          : CXToken_Keyword;
4418      }
4419      CXTok.ptr_data = II;
4420    } else if (Tok.is(tok::comment)) {
4421      CXTok.int_data[0] = CXToken_Comment;
4422      CXTok.ptr_data = 0;
4423    } else {
4424      CXTok.int_data[0] = CXToken_Punctuation;
4425      CXTok.ptr_data = 0;
4426    }
4427    CXTokens.push_back(CXTok);
4428    previousWasAt = Tok.is(tok::at);
4429  } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
4430}
4431
4432void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
4433                    CXToken **Tokens, unsigned *NumTokens) {
4434  if (Tokens)
4435    *Tokens = 0;
4436  if (NumTokens)
4437    *NumTokens = 0;
4438
4439  ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
4440  if (!CXXUnit || !Tokens || !NumTokens)
4441    return;
4442
4443  ASTUnit::ConcurrencyCheck Check(*CXXUnit);
4444
4445  SourceRange R = cxloc::translateCXSourceRange(Range);
4446  if (R.isInvalid())
4447    return;
4448
4449  SmallVector<CXToken, 32> CXTokens;
4450  getTokens(CXXUnit, R, CXTokens);
4451
4452  if (CXTokens.empty())
4453    return;
4454
4455  *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
4456  memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
4457  *NumTokens = CXTokens.size();
4458}
4459
4460void clang_disposeTokens(CXTranslationUnit TU,
4461                         CXToken *Tokens, unsigned NumTokens) {
4462  free(Tokens);
4463}
4464
4465} // end: extern "C"
4466
4467//===----------------------------------------------------------------------===//
4468// Token annotation APIs.
4469//===----------------------------------------------------------------------===//
4470
4471typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
4472static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
4473                                                     CXCursor parent,
4474                                                     CXClientData client_data);
4475namespace {
4476class AnnotateTokensWorker {
4477  AnnotateTokensData &Annotated;
4478  CXToken *Tokens;
4479  CXCursor *Cursors;
4480  unsigned NumTokens;
4481  unsigned TokIdx;
4482  unsigned PreprocessingTokIdx;
4483  CursorVisitor AnnotateVis;
4484  SourceManager &SrcMgr;
4485  bool HasContextSensitiveKeywords;
4486
4487  bool MoreTokens() const { return TokIdx < NumTokens; }
4488  unsigned NextToken() const { return TokIdx; }
4489  void AdvanceToken() { ++TokIdx; }
4490  SourceLocation GetTokenLoc(unsigned tokI) {
4491    return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
4492  }
4493  bool isFunctionMacroToken(unsigned tokI) const {
4494    return Tokens[tokI].int_data[3] != 0;
4495  }
4496  SourceLocation getFunctionMacroTokenLoc(unsigned tokI) const {
4497    return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[3]);
4498  }
4499
4500  void annotateAndAdvanceTokens(CXCursor, RangeComparisonResult, SourceRange);
4501  void annotateAndAdvanceFunctionMacroTokens(CXCursor, RangeComparisonResult,
4502                                             SourceRange);
4503
4504public:
4505  AnnotateTokensWorker(AnnotateTokensData &annotated,
4506                       CXToken *tokens, CXCursor *cursors, unsigned numTokens,
4507                       CXTranslationUnit tu, SourceRange RegionOfInterest)
4508    : Annotated(annotated), Tokens(tokens), Cursors(cursors),
4509      NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0),
4510      AnnotateVis(tu,
4511                  AnnotateTokensVisitor, this,
4512                  /*VisitPreprocessorLast=*/true,
4513                  /*VisitIncludedEntities=*/false,
4514                  RegionOfInterest),
4515      SrcMgr(static_cast<ASTUnit*>(tu->TUData)->getSourceManager()),
4516      HasContextSensitiveKeywords(false) { }
4517
4518  void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
4519  enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
4520  void AnnotateTokens(CXCursor parent);
4521  void AnnotateTokens() {
4522    AnnotateTokens(clang_getTranslationUnitCursor(AnnotateVis.getTU()));
4523  }
4524
4525  /// \brief Determine whether the annotator saw any cursors that have
4526  /// context-sensitive keywords.
4527  bool hasContextSensitiveKeywords() const {
4528    return HasContextSensitiveKeywords;
4529  }
4530};
4531}
4532
4533void AnnotateTokensWorker::AnnotateTokens(CXCursor parent) {
4534  // Walk the AST within the region of interest, annotating tokens
4535  // along the way.
4536  VisitChildren(parent);
4537
4538  for (unsigned I = 0 ; I < TokIdx ; ++I) {
4539    AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
4540    if (Pos != Annotated.end() &&
4541        (clang_isInvalid(Cursors[I].kind) ||
4542         Pos->second.kind != CXCursor_PreprocessingDirective))
4543      Cursors[I] = Pos->second;
4544  }
4545
4546  // Finish up annotating any tokens left.
4547  if (!MoreTokens())
4548    return;
4549
4550  const CXCursor &C = clang_getNullCursor();
4551  for (unsigned I = TokIdx ; I < NumTokens ; ++I) {
4552    AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
4553    Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second;
4554  }
4555}
4556
4557/// \brief It annotates and advances tokens with a cursor until the comparison
4558//// between the cursor location and the source range is the same as
4559/// \arg compResult.
4560///
4561/// Pass RangeBefore to annotate tokens with a cursor until a range is reached.
4562/// Pass RangeOverlap to annotate tokens inside a range.
4563void AnnotateTokensWorker::annotateAndAdvanceTokens(CXCursor updateC,
4564                                               RangeComparisonResult compResult,
4565                                               SourceRange range) {
4566  while (MoreTokens()) {
4567    const unsigned I = NextToken();
4568    if (isFunctionMacroToken(I))
4569      return annotateAndAdvanceFunctionMacroTokens(updateC, compResult, range);
4570
4571    SourceLocation TokLoc = GetTokenLoc(I);
4572    if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
4573      Cursors[I] = updateC;
4574      AdvanceToken();
4575      continue;
4576    }
4577    break;
4578  }
4579}
4580
4581/// \brief Special annotation handling for macro argument tokens.
4582void AnnotateTokensWorker::annotateAndAdvanceFunctionMacroTokens(
4583                                               CXCursor updateC,
4584                                               RangeComparisonResult compResult,
4585                                               SourceRange range) {
4586  assert(MoreTokens());
4587  assert(isFunctionMacroToken(NextToken()) &&
4588         "Should be called only for macro arg tokens");
4589
4590  // This works differently than annotateAndAdvanceTokens; because expanded
4591  // macro arguments can have arbitrary translation-unit source order, we do not
4592  // advance the token index one by one until a token fails the range test.
4593  // We only advance once past all of the macro arg tokens if all of them
4594  // pass the range test. If one of them fails we keep the token index pointing
4595  // at the start of the macro arg tokens so that the failing token will be
4596  // annotated by a subsequent annotation try.
4597
4598  bool atLeastOneCompFail = false;
4599
4600  unsigned I = NextToken();
4601  for (; I < NumTokens && isFunctionMacroToken(I); ++I) {
4602    SourceLocation TokLoc = getFunctionMacroTokenLoc(I);
4603    if (TokLoc.isFileID())
4604      continue; // not macro arg token, it's parens or comma.
4605    if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
4606      if (clang_isInvalid(clang_getCursorKind(Cursors[I])))
4607        Cursors[I] = updateC;
4608    } else
4609      atLeastOneCompFail = true;
4610  }
4611
4612  if (!atLeastOneCompFail)
4613    TokIdx = I; // All of the tokens were handled, advance beyond all of them.
4614}
4615
4616enum CXChildVisitResult
4617AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
4618  CXSourceLocation Loc = clang_getCursorLocation(cursor);
4619  SourceRange cursorRange = getRawCursorExtent(cursor);
4620  if (cursorRange.isInvalid())
4621    return CXChildVisit_Recurse;
4622
4623  if (!HasContextSensitiveKeywords) {
4624    // Objective-C properties can have context-sensitive keywords.
4625    if (cursor.kind == CXCursor_ObjCPropertyDecl) {
4626      if (ObjCPropertyDecl *Property
4627                  = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(cursor)))
4628        HasContextSensitiveKeywords = Property->getPropertyAttributesAsWritten() != 0;
4629    }
4630    // Objective-C methods can have context-sensitive keywords.
4631    else if (cursor.kind == CXCursor_ObjCInstanceMethodDecl ||
4632             cursor.kind == CXCursor_ObjCClassMethodDecl) {
4633      if (ObjCMethodDecl *Method
4634            = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
4635        if (Method->getObjCDeclQualifier())
4636          HasContextSensitiveKeywords = true;
4637        else {
4638          for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
4639                                           PEnd = Method->param_end();
4640               P != PEnd; ++P) {
4641            if ((*P)->getObjCDeclQualifier()) {
4642              HasContextSensitiveKeywords = true;
4643              break;
4644            }
4645          }
4646        }
4647      }
4648    }
4649    // C++ methods can have context-sensitive keywords.
4650    else if (cursor.kind == CXCursor_CXXMethod) {
4651      if (CXXMethodDecl *Method
4652                  = dyn_cast_or_null<CXXMethodDecl>(getCursorDecl(cursor))) {
4653        if (Method->hasAttr<FinalAttr>() || Method->hasAttr<OverrideAttr>())
4654          HasContextSensitiveKeywords = true;
4655      }
4656    }
4657    // C++ classes can have context-sensitive keywords.
4658    else if (cursor.kind == CXCursor_StructDecl ||
4659             cursor.kind == CXCursor_ClassDecl ||
4660             cursor.kind == CXCursor_ClassTemplate ||
4661             cursor.kind == CXCursor_ClassTemplatePartialSpecialization) {
4662      if (Decl *D = getCursorDecl(cursor))
4663        if (D->hasAttr<FinalAttr>())
4664          HasContextSensitiveKeywords = true;
4665    }
4666  }
4667
4668  if (clang_isPreprocessing(cursor.kind)) {
4669    // For macro expansions, just note where the beginning of the macro
4670    // expansion occurs.
4671    if (cursor.kind == CXCursor_MacroExpansion) {
4672      Annotated[Loc.int_data] = cursor;
4673      return CXChildVisit_Recurse;
4674    }
4675
4676    // Items in the preprocessing record are kept separate from items in
4677    // declarations, so we keep a separate token index.
4678    unsigned SavedTokIdx = TokIdx;
4679    TokIdx = PreprocessingTokIdx;
4680
4681    // Skip tokens up until we catch up to the beginning of the preprocessing
4682    // entry.
4683    while (MoreTokens()) {
4684      const unsigned I = NextToken();
4685      SourceLocation TokLoc = GetTokenLoc(I);
4686      switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4687      case RangeBefore:
4688        AdvanceToken();
4689        continue;
4690      case RangeAfter:
4691      case RangeOverlap:
4692        break;
4693      }
4694      break;
4695    }
4696
4697    // Look at all of the tokens within this range.
4698    while (MoreTokens()) {
4699      const unsigned I = NextToken();
4700      SourceLocation TokLoc = GetTokenLoc(I);
4701      switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4702      case RangeBefore:
4703        llvm_unreachable("Infeasible");
4704      case RangeAfter:
4705        break;
4706      case RangeOverlap:
4707        Cursors[I] = cursor;
4708        AdvanceToken();
4709        continue;
4710      }
4711      break;
4712    }
4713
4714    // Save the preprocessing token index; restore the non-preprocessing
4715    // token index.
4716    PreprocessingTokIdx = TokIdx;
4717    TokIdx = SavedTokIdx;
4718    return CXChildVisit_Recurse;
4719  }
4720
4721  if (cursorRange.isInvalid())
4722    return CXChildVisit_Continue;
4723
4724  SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data);
4725
4726  // Adjust the annotated range based specific declarations.
4727  const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
4728  if (cursorK >= CXCursor_FirstDecl && cursorK <= CXCursor_LastDecl) {
4729    Decl *D = cxcursor::getCursorDecl(cursor);
4730
4731    SourceLocation StartLoc;
4732    if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
4733      if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
4734        StartLoc = TI->getTypeLoc().getSourceRange().getBegin();
4735    } else if (TypedefDecl *Typedef = dyn_cast<TypedefDecl>(D)) {
4736      if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
4737        StartLoc = TI->getTypeLoc().getSourceRange().getBegin();
4738    }
4739
4740    if (StartLoc.isValid() && L.isValid() &&
4741        SrcMgr.isBeforeInTranslationUnit(StartLoc, L))
4742      cursorRange.setBegin(StartLoc);
4743  }
4744
4745  // If the location of the cursor occurs within a macro instantiation, record
4746  // the spelling location of the cursor in our annotation map.  We can then
4747  // paper over the token labelings during a post-processing step to try and
4748  // get cursor mappings for tokens that are the *arguments* of a macro
4749  // instantiation.
4750  if (L.isMacroID()) {
4751    unsigned rawEncoding = SrcMgr.getSpellingLoc(L).getRawEncoding();
4752    // Only invalidate the old annotation if it isn't part of a preprocessing
4753    // directive.  Here we assume that the default construction of CXCursor
4754    // results in CXCursor.kind being an initialized value (i.e., 0).  If
4755    // this isn't the case, we can fix by doing lookup + insertion.
4756
4757    CXCursor &oldC = Annotated[rawEncoding];
4758    if (!clang_isPreprocessing(oldC.kind))
4759      oldC = cursor;
4760  }
4761
4762  const enum CXCursorKind K = clang_getCursorKind(parent);
4763  const CXCursor updateC =
4764    (clang_isInvalid(K) || K == CXCursor_TranslationUnit)
4765     ? clang_getNullCursor() : parent;
4766
4767  annotateAndAdvanceTokens(updateC, RangeBefore, cursorRange);
4768
4769  // Avoid having the cursor of an expression "overwrite" the annotation of the
4770  // variable declaration that it belongs to.
4771  // This can happen for C++ constructor expressions whose range generally
4772  // include the variable declaration, e.g.:
4773  //  MyCXXClass foo; // Make sure we don't annotate 'foo' as a CallExpr cursor.
4774  if (clang_isExpression(cursorK)) {
4775    Expr *E = getCursorExpr(cursor);
4776    if (Decl *D = getCursorParentDecl(cursor)) {
4777      const unsigned I = NextToken();
4778      if (E->getLocStart().isValid() && D->getLocation().isValid() &&
4779          E->getLocStart() == D->getLocation() &&
4780          E->getLocStart() == GetTokenLoc(I)) {
4781        Cursors[I] = updateC;
4782        AdvanceToken();
4783      }
4784    }
4785  }
4786
4787  // Visit children to get their cursor information.
4788  const unsigned BeforeChildren = NextToken();
4789  VisitChildren(cursor);
4790  const unsigned AfterChildren = NextToken();
4791
4792  // Scan the tokens that are at the end of the cursor, but are not captured
4793  // but the child cursors.
4794  annotateAndAdvanceTokens(cursor, RangeOverlap, cursorRange);
4795
4796  // Scan the tokens that are at the beginning of the cursor, but are not
4797  // capture by the child cursors.
4798  for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
4799    if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
4800      break;
4801
4802    Cursors[I] = cursor;
4803  }
4804
4805  return CXChildVisit_Continue;
4806}
4807
4808static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
4809                                                     CXCursor parent,
4810                                                     CXClientData client_data) {
4811  return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
4812}
4813
4814namespace {
4815
4816/// \brief Uses the macro expansions in the preprocessing record to find
4817/// and mark tokens that are macro arguments. This info is used by the
4818/// AnnotateTokensWorker.
4819class MarkMacroArgTokensVisitor {
4820  SourceManager &SM;
4821  CXToken *Tokens;
4822  unsigned NumTokens;
4823  unsigned CurIdx;
4824
4825public:
4826  MarkMacroArgTokensVisitor(SourceManager &SM,
4827                            CXToken *tokens, unsigned numTokens)
4828    : SM(SM), Tokens(tokens), NumTokens(numTokens), CurIdx(0) { }
4829
4830  CXChildVisitResult visit(CXCursor cursor, CXCursor parent) {
4831    if (cursor.kind != CXCursor_MacroExpansion)
4832      return CXChildVisit_Continue;
4833
4834    SourceRange macroRange = getCursorMacroExpansion(cursor)->getSourceRange();
4835    if (macroRange.getBegin() == macroRange.getEnd())
4836      return CXChildVisit_Continue; // it's not a function macro.
4837
4838    for (; CurIdx < NumTokens; ++CurIdx) {
4839      if (!SM.isBeforeInTranslationUnit(getTokenLoc(CurIdx),
4840                                        macroRange.getBegin()))
4841        break;
4842    }
4843
4844    if (CurIdx == NumTokens)
4845      return CXChildVisit_Break;
4846
4847    for (; CurIdx < NumTokens; ++CurIdx) {
4848      SourceLocation tokLoc = getTokenLoc(CurIdx);
4849      if (!SM.isBeforeInTranslationUnit(tokLoc, macroRange.getEnd()))
4850        break;
4851
4852      setFunctionMacroTokenLoc(CurIdx, SM.getMacroArgExpandedLocation(tokLoc));
4853    }
4854
4855    if (CurIdx == NumTokens)
4856      return CXChildVisit_Break;
4857
4858    return CXChildVisit_Continue;
4859  }
4860
4861private:
4862  SourceLocation getTokenLoc(unsigned tokI) {
4863    return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
4864  }
4865
4866  void setFunctionMacroTokenLoc(unsigned tokI, SourceLocation loc) {
4867    // The third field is reserved and currently not used. Use it here
4868    // to mark macro arg expanded tokens with their expanded locations.
4869    Tokens[tokI].int_data[3] = loc.getRawEncoding();
4870  }
4871};
4872
4873} // end anonymous namespace
4874
4875static CXChildVisitResult
4876MarkMacroArgTokensVisitorDelegate(CXCursor cursor, CXCursor parent,
4877                                  CXClientData client_data) {
4878  return static_cast<MarkMacroArgTokensVisitor*>(client_data)->visit(cursor,
4879                                                                     parent);
4880}
4881
4882namespace {
4883  struct clang_annotateTokens_Data {
4884    CXTranslationUnit TU;
4885    ASTUnit *CXXUnit;
4886    CXToken *Tokens;
4887    unsigned NumTokens;
4888    CXCursor *Cursors;
4889  };
4890}
4891
4892static void annotatePreprocessorTokens(CXTranslationUnit TU,
4893                                       SourceRange RegionOfInterest,
4894                                       AnnotateTokensData &Annotated) {
4895  ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
4896
4897  SourceManager &SourceMgr = CXXUnit->getSourceManager();
4898  std::pair<FileID, unsigned> BeginLocInfo
4899    = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
4900  std::pair<FileID, unsigned> EndLocInfo
4901    = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
4902
4903  if (BeginLocInfo.first != EndLocInfo.first)
4904    return;
4905
4906  StringRef Buffer;
4907  bool Invalid = false;
4908  Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
4909  if (Buffer.empty() || Invalid)
4910    return;
4911
4912  Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
4913            CXXUnit->getASTContext().getLangOptions(),
4914            Buffer.begin(), Buffer.data() + BeginLocInfo.second,
4915            Buffer.end());
4916  Lex.SetCommentRetentionState(true);
4917
4918  // Lex tokens in raw mode until we hit the end of the range, to avoid
4919  // entering #includes or expanding macros.
4920  while (true) {
4921    Token Tok;
4922    Lex.LexFromRawLexer(Tok);
4923
4924  reprocess:
4925    if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
4926      // We have found a preprocessing directive. Gobble it up so that we
4927      // don't see it while preprocessing these tokens later, but keep track
4928      // of all of the token locations inside this preprocessing directive so
4929      // that we can annotate them appropriately.
4930      //
4931      // FIXME: Some simple tests here could identify macro definitions and
4932      // #undefs, to provide specific cursor kinds for those.
4933      SmallVector<SourceLocation, 32> Locations;
4934      do {
4935        Locations.push_back(Tok.getLocation());
4936        Lex.LexFromRawLexer(Tok);
4937      } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
4938
4939      using namespace cxcursor;
4940      CXCursor Cursor
4941      = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
4942                                                     Locations.back()),
4943                                         TU);
4944      for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
4945        Annotated[Locations[I].getRawEncoding()] = Cursor;
4946      }
4947
4948      if (Tok.isAtStartOfLine())
4949        goto reprocess;
4950
4951      continue;
4952    }
4953
4954    if (Tok.is(tok::eof))
4955      break;
4956  }
4957}
4958
4959// This gets run a separate thread to avoid stack blowout.
4960static void clang_annotateTokensImpl(void *UserData) {
4961  CXTranslationUnit TU = ((clang_annotateTokens_Data*)UserData)->TU;
4962  ASTUnit *CXXUnit = ((clang_annotateTokens_Data*)UserData)->CXXUnit;
4963  CXToken *Tokens = ((clang_annotateTokens_Data*)UserData)->Tokens;
4964  const unsigned NumTokens = ((clang_annotateTokens_Data*)UserData)->NumTokens;
4965  CXCursor *Cursors = ((clang_annotateTokens_Data*)UserData)->Cursors;
4966
4967  // Determine the region of interest, which contains all of the tokens.
4968  SourceRange RegionOfInterest;
4969  RegionOfInterest.setBegin(
4970    cxloc::translateSourceLocation(clang_getTokenLocation(TU, Tokens[0])));
4971  RegionOfInterest.setEnd(
4972    cxloc::translateSourceLocation(clang_getTokenLocation(TU,
4973                                                         Tokens[NumTokens-1])));
4974
4975  // A mapping from the source locations found when re-lexing or traversing the
4976  // region of interest to the corresponding cursors.
4977  AnnotateTokensData Annotated;
4978
4979  // Relex the tokens within the source range to look for preprocessing
4980  // directives.
4981  annotatePreprocessorTokens(TU, RegionOfInterest, Annotated);
4982
4983  if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
4984    // Search and mark tokens that are macro argument expansions.
4985    MarkMacroArgTokensVisitor Visitor(CXXUnit->getSourceManager(),
4986                                      Tokens, NumTokens);
4987    CursorVisitor MacroArgMarker(TU,
4988                                 MarkMacroArgTokensVisitorDelegate, &Visitor,
4989                                 /*VisitPreprocessorLast=*/true,
4990                                 /*VisitIncludedEntities=*/false,
4991                                 RegionOfInterest);
4992    MacroArgMarker.visitPreprocessedEntitiesInRegion();
4993  }
4994
4995  // Annotate all of the source locations in the region of interest that map to
4996  // a specific cursor.
4997  AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens,
4998                         TU, RegionOfInterest);
4999
5000  // FIXME: We use a ridiculous stack size here because the data-recursion
5001  // algorithm uses a large stack frame than the non-data recursive version,
5002  // and AnnotationTokensWorker currently transforms the data-recursion
5003  // algorithm back into a traditional recursion by explicitly calling
5004  // VisitChildren().  We will need to remove this explicit recursive call.
5005  W.AnnotateTokens();
5006
5007  // If we ran into any entities that involve context-sensitive keywords,
5008  // take another pass through the tokens to mark them as such.
5009  if (W.hasContextSensitiveKeywords()) {
5010    for (unsigned I = 0; I != NumTokens; ++I) {
5011      if (clang_getTokenKind(Tokens[I]) != CXToken_Identifier)
5012        continue;
5013
5014      if (Cursors[I].kind == CXCursor_ObjCPropertyDecl) {
5015        IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
5016        if (ObjCPropertyDecl *Property
5017            = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(Cursors[I]))) {
5018          if (Property->getPropertyAttributesAsWritten() != 0 &&
5019              llvm::StringSwitch<bool>(II->getName())
5020              .Case("readonly", true)
5021              .Case("assign", true)
5022              .Case("unsafe_unretained", true)
5023              .Case("readwrite", true)
5024              .Case("retain", true)
5025              .Case("copy", true)
5026              .Case("nonatomic", true)
5027              .Case("atomic", true)
5028              .Case("getter", true)
5029              .Case("setter", true)
5030              .Case("strong", true)
5031              .Case("weak", true)
5032              .Default(false))
5033            Tokens[I].int_data[0] = CXToken_Keyword;
5034        }
5035        continue;
5036      }
5037
5038      if (Cursors[I].kind == CXCursor_ObjCInstanceMethodDecl ||
5039          Cursors[I].kind == CXCursor_ObjCClassMethodDecl) {
5040        IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
5041        if (llvm::StringSwitch<bool>(II->getName())
5042            .Case("in", true)
5043            .Case("out", true)
5044            .Case("inout", true)
5045            .Case("oneway", true)
5046            .Case("bycopy", true)
5047            .Case("byref", true)
5048            .Default(false))
5049          Tokens[I].int_data[0] = CXToken_Keyword;
5050        continue;
5051      }
5052
5053      if (Cursors[I].kind == CXCursor_CXXFinalAttr ||
5054          Cursors[I].kind == CXCursor_CXXOverrideAttr) {
5055        Tokens[I].int_data[0] = CXToken_Keyword;
5056        continue;
5057      }
5058    }
5059  }
5060}
5061
5062extern "C" {
5063
5064void clang_annotateTokens(CXTranslationUnit TU,
5065                          CXToken *Tokens, unsigned NumTokens,
5066                          CXCursor *Cursors) {
5067
5068  if (NumTokens == 0 || !Tokens || !Cursors)
5069    return;
5070
5071  // Any token we don't specifically annotate will have a NULL cursor.
5072  CXCursor C = clang_getNullCursor();
5073  for (unsigned I = 0; I != NumTokens; ++I)
5074    Cursors[I] = C;
5075
5076  ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
5077  if (!CXXUnit)
5078    return;
5079
5080  ASTUnit::ConcurrencyCheck Check(*CXXUnit);
5081
5082  clang_annotateTokens_Data data = { TU, CXXUnit, Tokens, NumTokens, Cursors };
5083  llvm::CrashRecoveryContext CRC;
5084  if (!RunSafely(CRC, clang_annotateTokensImpl, &data,
5085                 GetSafetyThreadStackSize() * 2)) {
5086    fprintf(stderr, "libclang: crash detected while annotating tokens\n");
5087  }
5088}
5089
5090} // end: extern "C"
5091
5092//===----------------------------------------------------------------------===//
5093// Operations for querying linkage of a cursor.
5094//===----------------------------------------------------------------------===//
5095
5096extern "C" {
5097CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
5098  if (!clang_isDeclaration(cursor.kind))
5099    return CXLinkage_Invalid;
5100
5101  Decl *D = cxcursor::getCursorDecl(cursor);
5102  if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
5103    switch (ND->getLinkage()) {
5104      case NoLinkage: return CXLinkage_NoLinkage;
5105      case InternalLinkage: return CXLinkage_Internal;
5106      case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
5107      case ExternalLinkage: return CXLinkage_External;
5108    };
5109
5110  return CXLinkage_Invalid;
5111}
5112} // end: extern "C"
5113
5114//===----------------------------------------------------------------------===//
5115// Operations for querying language of a cursor.
5116//===----------------------------------------------------------------------===//
5117
5118static CXLanguageKind getDeclLanguage(const Decl *D) {
5119  switch (D->getKind()) {
5120    default:
5121      break;
5122    case Decl::ImplicitParam:
5123    case Decl::ObjCAtDefsField:
5124    case Decl::ObjCCategory:
5125    case Decl::ObjCCategoryImpl:
5126    case Decl::ObjCClass:
5127    case Decl::ObjCCompatibleAlias:
5128    case Decl::ObjCForwardProtocol:
5129    case Decl::ObjCImplementation:
5130    case Decl::ObjCInterface:
5131    case Decl::ObjCIvar:
5132    case Decl::ObjCMethod:
5133    case Decl::ObjCProperty:
5134    case Decl::ObjCPropertyImpl:
5135    case Decl::ObjCProtocol:
5136      return CXLanguage_ObjC;
5137    case Decl::CXXConstructor:
5138    case Decl::CXXConversion:
5139    case Decl::CXXDestructor:
5140    case Decl::CXXMethod:
5141    case Decl::CXXRecord:
5142    case Decl::ClassTemplate:
5143    case Decl::ClassTemplatePartialSpecialization:
5144    case Decl::ClassTemplateSpecialization:
5145    case Decl::Friend:
5146    case Decl::FriendTemplate:
5147    case Decl::FunctionTemplate:
5148    case Decl::LinkageSpec:
5149    case Decl::Namespace:
5150    case Decl::NamespaceAlias:
5151    case Decl::NonTypeTemplateParm:
5152    case Decl::StaticAssert:
5153    case Decl::TemplateTemplateParm:
5154    case Decl::TemplateTypeParm:
5155    case Decl::UnresolvedUsingTypename:
5156    case Decl::UnresolvedUsingValue:
5157    case Decl::Using:
5158    case Decl::UsingDirective:
5159    case Decl::UsingShadow:
5160      return CXLanguage_CPlusPlus;
5161  }
5162
5163  return CXLanguage_C;
5164}
5165
5166extern "C" {
5167
5168enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
5169  if (clang_isDeclaration(cursor.kind))
5170    if (Decl *D = cxcursor::getCursorDecl(cursor)) {
5171      if (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted())
5172        return CXAvailability_Available;
5173
5174      switch (D->getAvailability()) {
5175      case AR_Available:
5176      case AR_NotYetIntroduced:
5177        return CXAvailability_Available;
5178
5179      case AR_Deprecated:
5180        return CXAvailability_Deprecated;
5181
5182      case AR_Unavailable:
5183        return CXAvailability_NotAvailable;
5184      }
5185    }
5186
5187  return CXAvailability_Available;
5188}
5189
5190CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
5191  if (clang_isDeclaration(cursor.kind))
5192    return getDeclLanguage(cxcursor::getCursorDecl(cursor));
5193
5194  return CXLanguage_Invalid;
5195}
5196
5197 /// \brief If the given cursor is the "templated" declaration
5198 /// descibing a class or function template, return the class or
5199 /// function template.
5200static Decl *maybeGetTemplateCursor(Decl *D) {
5201  if (!D)
5202    return 0;
5203
5204  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
5205    if (FunctionTemplateDecl *FunTmpl = FD->getDescribedFunctionTemplate())
5206      return FunTmpl;
5207
5208  if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
5209    if (ClassTemplateDecl *ClassTmpl = RD->getDescribedClassTemplate())
5210      return ClassTmpl;
5211
5212  return D;
5213}
5214
5215CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
5216  if (clang_isDeclaration(cursor.kind)) {
5217    if (Decl *D = getCursorDecl(cursor)) {
5218      DeclContext *DC = D->getDeclContext();
5219      if (!DC)
5220        return clang_getNullCursor();
5221
5222      return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
5223                          getCursorTU(cursor));
5224    }
5225  }
5226
5227  if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
5228    if (Decl *D = getCursorDecl(cursor))
5229      return MakeCXCursor(D, getCursorTU(cursor));
5230  }
5231
5232  return clang_getNullCursor();
5233}
5234
5235CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
5236  if (clang_isDeclaration(cursor.kind)) {
5237    if (Decl *D = getCursorDecl(cursor)) {
5238      DeclContext *DC = D->getLexicalDeclContext();
5239      if (!DC)
5240        return clang_getNullCursor();
5241
5242      return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
5243                          getCursorTU(cursor));
5244    }
5245  }
5246
5247  // FIXME: Note that we can't easily compute the lexical context of a
5248  // statement or expression, so we return nothing.
5249  return clang_getNullCursor();
5250}
5251
5252void clang_getOverriddenCursors(CXCursor cursor,
5253                                CXCursor **overridden,
5254                                unsigned *num_overridden) {
5255  if (overridden)
5256    *overridden = 0;
5257  if (num_overridden)
5258    *num_overridden = 0;
5259  if (!overridden || !num_overridden)
5260    return;
5261
5262  SmallVector<CXCursor, 8> Overridden;
5263  cxcursor::getOverriddenCursors(cursor, Overridden);
5264
5265  // Don't allocate memory if we have no overriden cursors.
5266  if (Overridden.size() == 0)
5267    return;
5268
5269  *num_overridden = Overridden.size();
5270  *overridden = new CXCursor [Overridden.size()];
5271  std::copy(Overridden.begin(), Overridden.end(), *overridden);
5272}
5273
5274void clang_disposeOverriddenCursors(CXCursor *overridden) {
5275  delete [] overridden;
5276}
5277
5278CXFile clang_getIncludedFile(CXCursor cursor) {
5279  if (cursor.kind != CXCursor_InclusionDirective)
5280    return 0;
5281
5282  InclusionDirective *ID = getCursorInclusionDirective(cursor);
5283  return (void *)ID->getFile();
5284}
5285
5286} // end: extern "C"
5287
5288
5289//===----------------------------------------------------------------------===//
5290// C++ AST instrospection.
5291//===----------------------------------------------------------------------===//
5292
5293extern "C" {
5294unsigned clang_CXXMethod_isStatic(CXCursor C) {
5295  if (!clang_isDeclaration(C.kind))
5296    return 0;
5297
5298  CXXMethodDecl *Method = 0;
5299  Decl *D = cxcursor::getCursorDecl(C);
5300  if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
5301    Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
5302  else
5303    Method = dyn_cast_or_null<CXXMethodDecl>(D);
5304  return (Method && Method->isStatic()) ? 1 : 0;
5305}
5306
5307unsigned clang_CXXMethod_isVirtual(CXCursor C) {
5308  if (!clang_isDeclaration(C.kind))
5309    return 0;
5310
5311  CXXMethodDecl *Method = 0;
5312  Decl *D = cxcursor::getCursorDecl(C);
5313  if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
5314    Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
5315  else
5316    Method = dyn_cast_or_null<CXXMethodDecl>(D);
5317  return (Method && Method->isVirtual()) ? 1 : 0;
5318}
5319} // end: extern "C"
5320
5321//===----------------------------------------------------------------------===//
5322// Attribute introspection.
5323//===----------------------------------------------------------------------===//
5324
5325extern "C" {
5326CXType clang_getIBOutletCollectionType(CXCursor C) {
5327  if (C.kind != CXCursor_IBOutletCollectionAttr)
5328    return cxtype::MakeCXType(QualType(), cxcursor::getCursorTU(C));
5329
5330  IBOutletCollectionAttr *A =
5331    cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
5332
5333  return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorTU(C));
5334}
5335} // end: extern "C"
5336
5337//===----------------------------------------------------------------------===//
5338// Inspecting memory usage.
5339//===----------------------------------------------------------------------===//
5340
5341typedef std::vector<CXTUResourceUsageEntry> MemUsageEntries;
5342
5343static inline void createCXTUResourceUsageEntry(MemUsageEntries &entries,
5344                                              enum CXTUResourceUsageKind k,
5345                                              unsigned long amount) {
5346  CXTUResourceUsageEntry entry = { k, amount };
5347  entries.push_back(entry);
5348}
5349
5350extern "C" {
5351
5352const char *clang_getTUResourceUsageName(CXTUResourceUsageKind kind) {
5353  const char *str = "";
5354  switch (kind) {
5355    case CXTUResourceUsage_AST:
5356      str = "ASTContext: expressions, declarations, and types";
5357      break;
5358    case CXTUResourceUsage_Identifiers:
5359      str = "ASTContext: identifiers";
5360      break;
5361    case CXTUResourceUsage_Selectors:
5362      str = "ASTContext: selectors";
5363      break;
5364    case CXTUResourceUsage_GlobalCompletionResults:
5365      str = "Code completion: cached global results";
5366      break;
5367    case CXTUResourceUsage_SourceManagerContentCache:
5368      str = "SourceManager: content cache allocator";
5369      break;
5370    case CXTUResourceUsage_AST_SideTables:
5371      str = "ASTContext: side tables";
5372      break;
5373    case CXTUResourceUsage_SourceManager_Membuffer_Malloc:
5374      str = "SourceManager: malloc'ed memory buffers";
5375      break;
5376    case CXTUResourceUsage_SourceManager_Membuffer_MMap:
5377      str = "SourceManager: mmap'ed memory buffers";
5378      break;
5379    case CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc:
5380      str = "ExternalASTSource: malloc'ed memory buffers";
5381      break;
5382    case CXTUResourceUsage_ExternalASTSource_Membuffer_MMap:
5383      str = "ExternalASTSource: mmap'ed memory buffers";
5384      break;
5385    case CXTUResourceUsage_Preprocessor:
5386      str = "Preprocessor: malloc'ed memory";
5387      break;
5388    case CXTUResourceUsage_PreprocessingRecord:
5389      str = "Preprocessor: PreprocessingRecord";
5390      break;
5391    case CXTUResourceUsage_SourceManager_DataStructures:
5392      str = "SourceManager: data structures and tables";
5393      break;
5394    case CXTUResourceUsage_Preprocessor_HeaderSearch:
5395      str = "Preprocessor: header search tables";
5396      break;
5397  }
5398  return str;
5399}
5400
5401CXTUResourceUsage clang_getCXTUResourceUsage(CXTranslationUnit TU) {
5402  if (!TU) {
5403    CXTUResourceUsage usage = { (void*) 0, 0, 0 };
5404    return usage;
5405  }
5406
5407  ASTUnit *astUnit = static_cast<ASTUnit*>(TU->TUData);
5408  llvm::OwningPtr<MemUsageEntries> entries(new MemUsageEntries());
5409  ASTContext &astContext = astUnit->getASTContext();
5410
5411  // How much memory is used by AST nodes and types?
5412  createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST,
5413    (unsigned long) astContext.getASTAllocatedMemory());
5414
5415  // How much memory is used by identifiers?
5416  createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Identifiers,
5417    (unsigned long) astContext.Idents.getAllocator().getTotalMemory());
5418
5419  // How much memory is used for selectors?
5420  createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Selectors,
5421    (unsigned long) astContext.Selectors.getTotalMemory());
5422
5423  // How much memory is used by ASTContext's side tables?
5424  createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST_SideTables,
5425    (unsigned long) astContext.getSideTableAllocatedMemory());
5426
5427  // How much memory is used for caching global code completion results?
5428  unsigned long completionBytes = 0;
5429  if (GlobalCodeCompletionAllocator *completionAllocator =
5430      astUnit->getCachedCompletionAllocator().getPtr()) {
5431    completionBytes = completionAllocator->getTotalMemory();
5432  }
5433  createCXTUResourceUsageEntry(*entries,
5434                               CXTUResourceUsage_GlobalCompletionResults,
5435                               completionBytes);
5436
5437  // How much memory is being used by SourceManager's content cache?
5438  createCXTUResourceUsageEntry(*entries,
5439          CXTUResourceUsage_SourceManagerContentCache,
5440          (unsigned long) astContext.getSourceManager().getContentCacheSize());
5441
5442  // How much memory is being used by the MemoryBuffer's in SourceManager?
5443  const SourceManager::MemoryBufferSizes &srcBufs =
5444    astUnit->getSourceManager().getMemoryBufferSizes();
5445
5446  createCXTUResourceUsageEntry(*entries,
5447                               CXTUResourceUsage_SourceManager_Membuffer_Malloc,
5448                               (unsigned long) srcBufs.malloc_bytes);
5449  createCXTUResourceUsageEntry(*entries,
5450                               CXTUResourceUsage_SourceManager_Membuffer_MMap,
5451                               (unsigned long) srcBufs.mmap_bytes);
5452  createCXTUResourceUsageEntry(*entries,
5453                               CXTUResourceUsage_SourceManager_DataStructures,
5454                               (unsigned long) astContext.getSourceManager()
5455                                .getDataStructureSizes());
5456
5457  // How much memory is being used by the ExternalASTSource?
5458  if (ExternalASTSource *esrc = astContext.getExternalSource()) {
5459    const ExternalASTSource::MemoryBufferSizes &sizes =
5460      esrc->getMemoryBufferSizes();
5461
5462    createCXTUResourceUsageEntry(*entries,
5463      CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc,
5464                                 (unsigned long) sizes.malloc_bytes);
5465    createCXTUResourceUsageEntry(*entries,
5466      CXTUResourceUsage_ExternalASTSource_Membuffer_MMap,
5467                                 (unsigned long) sizes.mmap_bytes);
5468  }
5469
5470  // How much memory is being used by the Preprocessor?
5471  Preprocessor &pp = astUnit->getPreprocessor();
5472  createCXTUResourceUsageEntry(*entries,
5473                               CXTUResourceUsage_Preprocessor,
5474                               pp.getTotalMemory());
5475
5476  if (PreprocessingRecord *pRec = pp.getPreprocessingRecord()) {
5477    createCXTUResourceUsageEntry(*entries,
5478                                 CXTUResourceUsage_PreprocessingRecord,
5479                                 pRec->getTotalMemory());
5480  }
5481
5482  createCXTUResourceUsageEntry(*entries,
5483                               CXTUResourceUsage_Preprocessor_HeaderSearch,
5484                               pp.getHeaderSearchInfo().getTotalMemory());
5485
5486  CXTUResourceUsage usage = { (void*) entries.get(),
5487                            (unsigned) entries->size(),
5488                            entries->size() ? &(*entries)[0] : 0 };
5489  entries.take();
5490  return usage;
5491}
5492
5493void clang_disposeCXTUResourceUsage(CXTUResourceUsage usage) {
5494  if (usage.data)
5495    delete (MemUsageEntries*) usage.data;
5496}
5497
5498} // end extern "C"
5499
5500void clang::PrintLibclangResourceUsage(CXTranslationUnit TU) {
5501  CXTUResourceUsage Usage = clang_getCXTUResourceUsage(TU);
5502  for (unsigned I = 0; I != Usage.numEntries; ++I)
5503    fprintf(stderr, "  %s: %lu\n",
5504            clang_getTUResourceUsageName(Usage.entries[I].kind),
5505            Usage.entries[I].amount);
5506
5507  clang_disposeCXTUResourceUsage(Usage);
5508}
5509
5510//===----------------------------------------------------------------------===//
5511// Misc. utility functions.
5512//===----------------------------------------------------------------------===//
5513
5514/// Default to using an 8 MB stack size on "safety" threads.
5515static unsigned SafetyStackThreadSize = 8 << 20;
5516
5517namespace clang {
5518
5519bool RunSafely(llvm::CrashRecoveryContext &CRC,
5520               void (*Fn)(void*), void *UserData,
5521               unsigned Size) {
5522  if (!Size)
5523    Size = GetSafetyThreadStackSize();
5524  if (Size)
5525    return CRC.RunSafelyOnThread(Fn, UserData, Size);
5526  return CRC.RunSafely(Fn, UserData);
5527}
5528
5529unsigned GetSafetyThreadStackSize() {
5530  return SafetyStackThreadSize;
5531}
5532
5533void SetSafetyThreadStackSize(unsigned Value) {
5534  SafetyStackThreadSize = Value;
5535}
5536
5537}
5538
5539extern "C" {
5540
5541CXString clang_getClangVersion() {
5542  return createCXString(getClangFullVersion());
5543}
5544
5545} // end: extern "C"
5546
5547