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