CIndex.cpp revision 6d0a00d9b02499d6c1253ea03d4dc7c32f8f289e
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 "CXString.h"
18#include "CXType.h"
19#include "CXSourceLocation.h"
20#include "CIndexDiagnostic.h"
21
22#include "clang/Basic/Version.h"
23
24#include "clang/AST/DeclVisitor.h"
25#include "clang/AST/StmtVisitor.h"
26#include "clang/AST/TypeLocVisitor.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/PreprocessingRecord.h"
33#include "clang/Lex/Preprocessor.h"
34#include "llvm/ADT/STLExtras.h"
35#include "llvm/ADT/Optional.h"
36#include "clang/Analysis/Support/SaveAndRestore.h"
37#include "llvm/Support/CrashRecoveryContext.h"
38#include "llvm/Support/PrettyStackTrace.h"
39#include "llvm/Support/MemoryBuffer.h"
40#include "llvm/Support/raw_ostream.h"
41#include "llvm/Support/Timer.h"
42#include "llvm/System/Mutex.h"
43#include "llvm/System/Program.h"
44#include "llvm/System/Signals.h"
45#include "llvm/System/Threading.h"
46#include "llvm/Support/Compiler.h"
47
48using namespace clang;
49using namespace clang::cxcursor;
50using namespace clang::cxstring;
51
52static CXTranslationUnit MakeCXTranslationUnit(ASTUnit *TU) {
53  if (!TU)
54    return 0;
55  CXTranslationUnit D = new CXTranslationUnitImpl();
56  D->TUData = TU;
57  D->StringPool = createCXStringPool();
58  return D;
59}
60
61/// \brief The result of comparing two source ranges.
62enum RangeComparisonResult {
63  /// \brief Either the ranges overlap or one of the ranges is invalid.
64  RangeOverlap,
65
66  /// \brief The first range ends before the second range starts.
67  RangeBefore,
68
69  /// \brief The first range starts after the second range ends.
70  RangeAfter
71};
72
73/// \brief Compare two source ranges to determine their relative position in
74/// the translation unit.
75static RangeComparisonResult RangeCompare(SourceManager &SM,
76                                          SourceRange R1,
77                                          SourceRange R2) {
78  assert(R1.isValid() && "First range is invalid?");
79  assert(R2.isValid() && "Second range is invalid?");
80  if (R1.getEnd() != R2.getBegin() &&
81      SM.isBeforeInTranslationUnit(R1.getEnd(), R2.getBegin()))
82    return RangeBefore;
83  if (R2.getEnd() != R1.getBegin() &&
84      SM.isBeforeInTranslationUnit(R2.getEnd(), R1.getBegin()))
85    return RangeAfter;
86  return RangeOverlap;
87}
88
89/// \brief Determine if a source location falls within, before, or after a
90///   a given source range.
91static RangeComparisonResult LocationCompare(SourceManager &SM,
92                                             SourceLocation L, SourceRange R) {
93  assert(R.isValid() && "First range is invalid?");
94  assert(L.isValid() && "Second range is invalid?");
95  if (L == R.getBegin() || L == R.getEnd())
96    return RangeOverlap;
97  if (SM.isBeforeInTranslationUnit(L, R.getBegin()))
98    return RangeBefore;
99  if (SM.isBeforeInTranslationUnit(R.getEnd(), L))
100    return RangeAfter;
101  return RangeOverlap;
102}
103
104/// \brief Translate a Clang source range into a CIndex source range.
105///
106/// Clang internally represents ranges where the end location points to the
107/// start of the token at the end. However, for external clients it is more
108/// useful to have a CXSourceRange be a proper half-open interval. This routine
109/// does the appropriate translation.
110CXSourceRange cxloc::translateSourceRange(const SourceManager &SM,
111                                          const LangOptions &LangOpts,
112                                          const CharSourceRange &R) {
113  // We want the last character in this location, so we will adjust the
114  // location accordingly.
115  SourceLocation EndLoc = R.getEnd();
116  if (EndLoc.isValid() && EndLoc.isMacroID())
117    EndLoc = SM.getSpellingLoc(EndLoc);
118  if (R.isTokenRange() && !EndLoc.isInvalid() && EndLoc.isFileID()) {
119    unsigned Length = Lexer::MeasureTokenLength(EndLoc, SM, LangOpts);
120    EndLoc = EndLoc.getFileLocWithOffset(Length);
121  }
122
123  CXSourceRange Result = { { (void *)&SM, (void *)&LangOpts },
124                           R.getBegin().getRawEncoding(),
125                           EndLoc.getRawEncoding() };
126  return Result;
127}
128
129//===----------------------------------------------------------------------===//
130// Cursor visitor.
131//===----------------------------------------------------------------------===//
132
133namespace {
134
135class VisitorJob {
136public:
137  enum Kind { DeclVisitKind, StmtVisitKind, MemberExprPartsKind,
138              TypeLocVisitKind, OverloadExprPartsKind,
139              DeclRefExprPartsKind, LabelRefVisitKind,
140              ExplicitTemplateArgsVisitKind };
141protected:
142  void *dataA;
143  void *dataB;
144  CXCursor parent;
145  Kind K;
146  VisitorJob(CXCursor C, Kind k, void *d1, void *d2 = 0)
147    : dataA(d1), dataB(d2), parent(C), K(k) {}
148public:
149  Kind getKind() const { return K; }
150  const CXCursor &getParent() const { return parent; }
151  static bool classof(VisitorJob *VJ) { return true; }
152};
153
154typedef llvm::SmallVector<VisitorJob, 10> VisitorWorkList;
155
156// Cursor visitor.
157class CursorVisitor : public DeclVisitor<CursorVisitor, bool>,
158                      public TypeLocVisitor<CursorVisitor, bool>,
159                      public StmtVisitor<CursorVisitor, bool>
160{
161  /// \brief The translation unit we are traversing.
162  CXTranslationUnit TU;
163  ASTUnit *AU;
164
165  /// \brief The parent cursor whose children we are traversing.
166  CXCursor Parent;
167
168  /// \brief The declaration that serves at the parent of any statement or
169  /// expression nodes.
170  Decl *StmtParent;
171
172  /// \brief The visitor function.
173  CXCursorVisitor Visitor;
174
175  /// \brief The opaque client data, to be passed along to the visitor.
176  CXClientData ClientData;
177
178  // MaxPCHLevel - the maximum PCH level of declarations that we will pass on
179  // to the visitor. Declarations with a PCH level greater than this value will
180  // be suppressed.
181  unsigned MaxPCHLevel;
182
183  /// \brief When valid, a source range to which the cursor should restrict
184  /// its search.
185  SourceRange RegionOfInterest;
186
187  // FIXME: Eventually remove.  This part of a hack to support proper
188  // iteration over all Decls contained lexically within an ObjC container.
189  DeclContext::decl_iterator *DI_current;
190  DeclContext::decl_iterator DE_current;
191
192  // Cache of pre-allocated worklists for data-recursion walk of Stmts.
193  llvm::SmallVector<VisitorWorkList*, 5> WorkListFreeList;
194  llvm::SmallVector<VisitorWorkList*, 5> WorkListCache;
195
196  using DeclVisitor<CursorVisitor, bool>::Visit;
197  using TypeLocVisitor<CursorVisitor, bool>::Visit;
198  using StmtVisitor<CursorVisitor, bool>::Visit;
199
200  /// \brief Determine whether this particular source range comes before, comes
201  /// after, or overlaps the region of interest.
202  ///
203  /// \param R a half-open source range retrieved from the abstract syntax tree.
204  RangeComparisonResult CompareRegionOfInterest(SourceRange R);
205
206  class SetParentRAII {
207    CXCursor &Parent;
208    Decl *&StmtParent;
209    CXCursor OldParent;
210
211  public:
212    SetParentRAII(CXCursor &Parent, Decl *&StmtParent, CXCursor NewParent)
213      : Parent(Parent), StmtParent(StmtParent), OldParent(Parent)
214    {
215      Parent = NewParent;
216      if (clang_isDeclaration(Parent.kind))
217        StmtParent = getCursorDecl(Parent);
218    }
219
220    ~SetParentRAII() {
221      Parent = OldParent;
222      if (clang_isDeclaration(Parent.kind))
223        StmtParent = getCursorDecl(Parent);
224    }
225  };
226
227public:
228  CursorVisitor(CXTranslationUnit TU, CXCursorVisitor Visitor,
229                CXClientData ClientData,
230                unsigned MaxPCHLevel,
231                SourceRange RegionOfInterest = SourceRange())
232    : TU(TU), AU(static_cast<ASTUnit*>(TU->TUData)),
233      Visitor(Visitor), ClientData(ClientData),
234      MaxPCHLevel(MaxPCHLevel), RegionOfInterest(RegionOfInterest),
235      DI_current(0)
236  {
237    Parent.kind = CXCursor_NoDeclFound;
238    Parent.data[0] = 0;
239    Parent.data[1] = 0;
240    Parent.data[2] = 0;
241    StmtParent = 0;
242  }
243
244  ~CursorVisitor() {
245    // Free the pre-allocated worklists for data-recursion.
246    for (llvm::SmallVectorImpl<VisitorWorkList*>::iterator
247          I = WorkListCache.begin(), E = WorkListCache.end(); I != E; ++I) {
248      delete *I;
249    }
250  }
251
252  ASTUnit *getASTUnit() const { return static_cast<ASTUnit*>(TU->TUData); }
253  CXTranslationUnit getTU() const { return TU; }
254
255  bool Visit(CXCursor Cursor, bool CheckedRegionOfInterest = false);
256
257  std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
258    getPreprocessedEntities();
259
260  bool VisitChildren(CXCursor Parent);
261
262  // Declaration visitors
263  bool VisitAttributes(Decl *D);
264  bool VisitBlockDecl(BlockDecl *B);
265  bool VisitCXXRecordDecl(CXXRecordDecl *D);
266  llvm::Optional<bool> shouldVisitCursor(CXCursor C);
267  bool VisitDeclContext(DeclContext *DC);
268  bool VisitTranslationUnitDecl(TranslationUnitDecl *D);
269  bool VisitTypedefDecl(TypedefDecl *D);
270  bool VisitTagDecl(TagDecl *D);
271  bool VisitClassTemplateSpecializationDecl(ClassTemplateSpecializationDecl *D);
272  bool VisitClassTemplatePartialSpecializationDecl(
273                                     ClassTemplatePartialSpecializationDecl *D);
274  bool VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
275  bool VisitEnumConstantDecl(EnumConstantDecl *D);
276  bool VisitDeclaratorDecl(DeclaratorDecl *DD);
277  bool VisitFunctionDecl(FunctionDecl *ND);
278  bool VisitFieldDecl(FieldDecl *D);
279  bool VisitVarDecl(VarDecl *);
280  bool VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D);
281  bool VisitFunctionTemplateDecl(FunctionTemplateDecl *D);
282  bool VisitClassTemplateDecl(ClassTemplateDecl *D);
283  bool VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D);
284  bool VisitObjCMethodDecl(ObjCMethodDecl *ND);
285  bool VisitObjCContainerDecl(ObjCContainerDecl *D);
286  bool VisitObjCCategoryDecl(ObjCCategoryDecl *ND);
287  bool VisitObjCProtocolDecl(ObjCProtocolDecl *PID);
288  bool VisitObjCPropertyDecl(ObjCPropertyDecl *PD);
289  bool VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
290  bool VisitObjCImplDecl(ObjCImplDecl *D);
291  bool VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
292  bool VisitObjCImplementationDecl(ObjCImplementationDecl *D);
293  // FIXME: ObjCCompatibleAliasDecl requires aliased-class locations.
294  bool VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D);
295  bool VisitObjCClassDecl(ObjCClassDecl *D);
296  bool VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *PD);
297  bool VisitLinkageSpecDecl(LinkageSpecDecl *D);
298  bool VisitNamespaceDecl(NamespaceDecl *D);
299  bool VisitNamespaceAliasDecl(NamespaceAliasDecl *D);
300  bool VisitUsingDirectiveDecl(UsingDirectiveDecl *D);
301  bool VisitUsingDecl(UsingDecl *D);
302  bool VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D);
303  bool VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D);
304
305  // Name visitor
306  bool VisitDeclarationNameInfo(DeclarationNameInfo Name);
307  bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS, SourceRange Range);
308
309  // Template visitors
310  bool VisitTemplateParameters(const TemplateParameterList *Params);
311  bool VisitTemplateName(TemplateName Name, SourceLocation Loc);
312  bool VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL);
313
314  // Type visitors
315  bool VisitQualifiedTypeLoc(QualifiedTypeLoc TL);
316  bool VisitBuiltinTypeLoc(BuiltinTypeLoc TL);
317  bool VisitTypedefTypeLoc(TypedefTypeLoc TL);
318  bool VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL);
319  bool VisitTagTypeLoc(TagTypeLoc TL);
320  bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL);
321  bool VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL);
322  bool VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL);
323  bool VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL);
324  bool VisitPointerTypeLoc(PointerTypeLoc TL);
325  bool VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL);
326  bool VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL);
327  bool VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL);
328  bool VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL);
329  bool VisitFunctionTypeLoc(FunctionTypeLoc TL, bool SkipResultType = false);
330  bool VisitArrayTypeLoc(ArrayTypeLoc TL);
331  bool VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL);
332  // FIXME: Implement visitors here when the unimplemented TypeLocs get
333  // implemented
334  bool VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL);
335  bool VisitTypeOfTypeLoc(TypeOfTypeLoc TL);
336
337  // Statement visitors
338  bool VisitStmt(Stmt *S);
339
340  // Expression visitors
341  bool VisitOffsetOfExpr(OffsetOfExpr *E);
342  bool VisitDesignatedInitExpr(DesignatedInitExpr *E);
343  bool VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E);
344  bool VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E);
345  bool VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E);
346
347  // Data-recursive visitor functions.
348  bool IsInRegionOfInterest(CXCursor C);
349  bool RunVisitorWorkList(VisitorWorkList &WL);
350  void EnqueueWorkList(VisitorWorkList &WL, Stmt *S);
351  LLVM_ATTRIBUTE_NOINLINE bool VisitDataRecursive(Stmt *S);
352};
353
354} // end anonymous namespace
355
356static SourceRange getRawCursorExtent(CXCursor C);
357
358RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
359  return RangeCompare(AU->getSourceManager(), R, RegionOfInterest);
360}
361
362/// \brief Visit the given cursor and, if requested by the visitor,
363/// its children.
364///
365/// \param Cursor the cursor to visit.
366///
367/// \param CheckRegionOfInterest if true, then the caller already checked that
368/// this cursor is within the region of interest.
369///
370/// \returns true if the visitation should be aborted, false if it
371/// should continue.
372bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
373  if (clang_isInvalid(Cursor.kind))
374    return false;
375
376  if (clang_isDeclaration(Cursor.kind)) {
377    Decl *D = getCursorDecl(Cursor);
378    assert(D && "Invalid declaration cursor");
379    if (D->getPCHLevel() > MaxPCHLevel)
380      return false;
381
382    if (D->isImplicit())
383      return false;
384  }
385
386  // If we have a range of interest, and this cursor doesn't intersect with it,
387  // we're done.
388  if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
389    SourceRange Range = getRawCursorExtent(Cursor);
390    if (Range.isInvalid() || CompareRegionOfInterest(Range))
391      return false;
392  }
393
394  switch (Visitor(Cursor, Parent, ClientData)) {
395  case CXChildVisit_Break:
396    return true;
397
398  case CXChildVisit_Continue:
399    return false;
400
401  case CXChildVisit_Recurse:
402    return VisitChildren(Cursor);
403  }
404
405  return false;
406}
407
408std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
409CursorVisitor::getPreprocessedEntities() {
410  PreprocessingRecord &PPRec
411    = *AU->getPreprocessor().getPreprocessingRecord();
412
413  bool OnlyLocalDecls
414    = !AU->isMainFileAST() && AU->getOnlyLocalDecls();
415
416  // There is no region of interest; we have to walk everything.
417  if (RegionOfInterest.isInvalid())
418    return std::make_pair(PPRec.begin(OnlyLocalDecls),
419                          PPRec.end(OnlyLocalDecls));
420
421  // Find the file in which the region of interest lands.
422  SourceManager &SM = AU->getSourceManager();
423  std::pair<FileID, unsigned> Begin
424    = SM.getDecomposedInstantiationLoc(RegionOfInterest.getBegin());
425  std::pair<FileID, unsigned> End
426    = SM.getDecomposedInstantiationLoc(RegionOfInterest.getEnd());
427
428  // The region of interest spans files; we have to walk everything.
429  if (Begin.first != End.first)
430    return std::make_pair(PPRec.begin(OnlyLocalDecls),
431                          PPRec.end(OnlyLocalDecls));
432
433  ASTUnit::PreprocessedEntitiesByFileMap &ByFileMap
434    = AU->getPreprocessedEntitiesByFile();
435  if (ByFileMap.empty()) {
436    // Build the mapping from files to sets of preprocessed entities.
437    for (PreprocessingRecord::iterator E = PPRec.begin(OnlyLocalDecls),
438                                    EEnd = PPRec.end(OnlyLocalDecls);
439         E != EEnd; ++E) {
440      std::pair<FileID, unsigned> P
441        = SM.getDecomposedInstantiationLoc((*E)->getSourceRange().getBegin());
442      ByFileMap[P.first].push_back(*E);
443    }
444  }
445
446  return std::make_pair(ByFileMap[Begin.first].begin(),
447                        ByFileMap[Begin.first].end());
448}
449
450/// \brief Visit the children of the given cursor.
451///
452/// \returns true if the visitation should be aborted, false if it
453/// should continue.
454bool CursorVisitor::VisitChildren(CXCursor Cursor) {
455  if (clang_isReference(Cursor.kind)) {
456    // By definition, references have no children.
457    return false;
458  }
459
460  // Set the Parent field to Cursor, then back to its old value once we're
461  // done.
462  SetParentRAII SetParent(Parent, StmtParent, Cursor);
463
464  if (clang_isDeclaration(Cursor.kind)) {
465    Decl *D = getCursorDecl(Cursor);
466    assert(D && "Invalid declaration cursor");
467    return VisitAttributes(D) || Visit(D);
468  }
469
470  if (clang_isStatement(Cursor.kind))
471    return Visit(getCursorStmt(Cursor));
472  if (clang_isExpression(Cursor.kind))
473    return Visit(getCursorExpr(Cursor));
474
475  if (clang_isTranslationUnit(Cursor.kind)) {
476    CXTranslationUnit tu = getCursorTU(Cursor);
477    ASTUnit *CXXUnit = static_cast<ASTUnit*>(tu->TUData);
478    if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
479        RegionOfInterest.isInvalid()) {
480      for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(),
481                                    TLEnd = CXXUnit->top_level_end();
482           TL != TLEnd; ++TL) {
483        if (Visit(MakeCXCursor(*TL, tu), true))
484          return true;
485      }
486    } else if (VisitDeclContext(
487                            CXXUnit->getASTContext().getTranslationUnitDecl()))
488      return true;
489
490    // Walk the preprocessing record.
491    if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
492      // FIXME: Once we have the ability to deserialize a preprocessing record,
493      // do so.
494      PreprocessingRecord::iterator E, EEnd;
495      for (llvm::tie(E, EEnd) = getPreprocessedEntities(); E != EEnd; ++E) {
496        if (MacroInstantiation *MI = dyn_cast<MacroInstantiation>(*E)) {
497          if (Visit(MakeMacroInstantiationCursor(MI, tu)))
498            return true;
499
500          continue;
501        }
502
503        if (MacroDefinition *MD = dyn_cast<MacroDefinition>(*E)) {
504          if (Visit(MakeMacroDefinitionCursor(MD, tu)))
505            return true;
506
507          continue;
508        }
509
510        if (InclusionDirective *ID = dyn_cast<InclusionDirective>(*E)) {
511          if (Visit(MakeInclusionDirectiveCursor(ID, tu)))
512            return true;
513
514          continue;
515        }
516      }
517    }
518    return false;
519  }
520
521  // Nothing to visit at the moment.
522  return false;
523}
524
525bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
526  if (Visit(B->getSignatureAsWritten()->getTypeLoc()))
527    return true;
528
529  if (Stmt *Body = B->getBody())
530    return Visit(MakeCXCursor(Body, StmtParent, TU));
531
532  return false;
533}
534
535llvm::Optional<bool> CursorVisitor::shouldVisitCursor(CXCursor Cursor) {
536  if (RegionOfInterest.isValid()) {
537    SourceRange Range = getRawCursorExtent(Cursor);
538    if (Range.isInvalid())
539      return llvm::Optional<bool>();
540
541    switch (CompareRegionOfInterest(Range)) {
542    case RangeBefore:
543      // This declaration comes before the region of interest; skip it.
544      return llvm::Optional<bool>();
545
546    case RangeAfter:
547      // This declaration comes after the region of interest; we're done.
548      return false;
549
550    case RangeOverlap:
551      // This declaration overlaps the region of interest; visit it.
552      break;
553    }
554  }
555  return true;
556}
557
558bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
559  DeclContext::decl_iterator I = DC->decls_begin(), E = DC->decls_end();
560
561  // FIXME: Eventually remove.  This part of a hack to support proper
562  // iteration over all Decls contained lexically within an ObjC container.
563  SaveAndRestore<DeclContext::decl_iterator*> DI_saved(DI_current, &I);
564  SaveAndRestore<DeclContext::decl_iterator> DE_saved(DE_current, E);
565
566  for ( ; I != E; ++I) {
567    Decl *D = *I;
568    if (D->getLexicalDeclContext() != DC)
569      continue;
570    CXCursor Cursor = MakeCXCursor(D, TU);
571    const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
572    if (!V.hasValue())
573      continue;
574    if (!V.getValue())
575      return false;
576    if (Visit(Cursor, true))
577      return true;
578  }
579  return false;
580}
581
582bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
583  llvm_unreachable("Translation units are visited directly by Visit()");
584  return false;
585}
586
587bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
588  if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
589    return Visit(TSInfo->getTypeLoc());
590
591  return false;
592}
593
594bool CursorVisitor::VisitTagDecl(TagDecl *D) {
595  return VisitDeclContext(D);
596}
597
598bool CursorVisitor::VisitClassTemplateSpecializationDecl(
599                                          ClassTemplateSpecializationDecl *D) {
600  bool ShouldVisitBody = false;
601  switch (D->getSpecializationKind()) {
602  case TSK_Undeclared:
603  case TSK_ImplicitInstantiation:
604    // Nothing to visit
605    return false;
606
607  case TSK_ExplicitInstantiationDeclaration:
608  case TSK_ExplicitInstantiationDefinition:
609    break;
610
611  case TSK_ExplicitSpecialization:
612    ShouldVisitBody = true;
613    break;
614  }
615
616  // Visit the template arguments used in the specialization.
617  if (TypeSourceInfo *SpecType = D->getTypeAsWritten()) {
618    TypeLoc TL = SpecType->getTypeLoc();
619    if (TemplateSpecializationTypeLoc *TSTLoc
620          = dyn_cast<TemplateSpecializationTypeLoc>(&TL)) {
621      for (unsigned I = 0, N = TSTLoc->getNumArgs(); I != N; ++I)
622        if (VisitTemplateArgumentLoc(TSTLoc->getArgLoc(I)))
623          return true;
624    }
625  }
626
627  if (ShouldVisitBody && VisitCXXRecordDecl(D))
628    return true;
629
630  return false;
631}
632
633bool CursorVisitor::VisitClassTemplatePartialSpecializationDecl(
634                                   ClassTemplatePartialSpecializationDecl *D) {
635  // FIXME: Visit the "outer" template parameter lists on the TagDecl
636  // before visiting these template parameters.
637  if (VisitTemplateParameters(D->getTemplateParameters()))
638    return true;
639
640  // Visit the partial specialization arguments.
641  const TemplateArgumentLoc *TemplateArgs = D->getTemplateArgsAsWritten();
642  for (unsigned I = 0, N = D->getNumTemplateArgsAsWritten(); I != N; ++I)
643    if (VisitTemplateArgumentLoc(TemplateArgs[I]))
644      return true;
645
646  return VisitCXXRecordDecl(D);
647}
648
649bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
650  // Visit the default argument.
651  if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
652    if (TypeSourceInfo *DefArg = D->getDefaultArgumentInfo())
653      if (Visit(DefArg->getTypeLoc()))
654        return true;
655
656  return false;
657}
658
659bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
660  if (Expr *Init = D->getInitExpr())
661    return Visit(MakeCXCursor(Init, StmtParent, TU));
662  return false;
663}
664
665bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
666  if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
667    if (Visit(TSInfo->getTypeLoc()))
668      return true;
669
670  return false;
671}
672
673/// \brief Compare two base or member initializers based on their source order.
674static int CompareCXXBaseOrMemberInitializers(const void* Xp, const void *Yp) {
675  CXXBaseOrMemberInitializer const * const *X
676    = static_cast<CXXBaseOrMemberInitializer const * const *>(Xp);
677  CXXBaseOrMemberInitializer const * const *Y
678    = static_cast<CXXBaseOrMemberInitializer const * const *>(Yp);
679
680  if ((*X)->getSourceOrder() < (*Y)->getSourceOrder())
681    return -1;
682  else if ((*X)->getSourceOrder() > (*Y)->getSourceOrder())
683    return 1;
684  else
685    return 0;
686}
687
688bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
689  if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) {
690    // Visit the function declaration's syntactic components in the order
691    // written. This requires a bit of work.
692    TypeLoc TL = TSInfo->getTypeLoc();
693    FunctionTypeLoc *FTL = dyn_cast<FunctionTypeLoc>(&TL);
694
695    // If we have a function declared directly (without the use of a typedef),
696    // visit just the return type. Otherwise, just visit the function's type
697    // now.
698    if ((FTL && !isa<CXXConversionDecl>(ND) && Visit(FTL->getResultLoc())) ||
699        (!FTL && Visit(TL)))
700      return true;
701
702    // Visit the nested-name-specifier, if present.
703    if (NestedNameSpecifier *Qualifier = ND->getQualifier())
704      if (VisitNestedNameSpecifier(Qualifier, ND->getQualifierRange()))
705        return true;
706
707    // Visit the declaration name.
708    if (VisitDeclarationNameInfo(ND->getNameInfo()))
709      return true;
710
711    // FIXME: Visit explicitly-specified template arguments!
712
713    // Visit the function parameters, if we have a function type.
714    if (FTL && VisitFunctionTypeLoc(*FTL, true))
715      return true;
716
717    // FIXME: Attributes?
718  }
719
720  if (ND->isThisDeclarationADefinition()) {
721    if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ND)) {
722      // Find the initializers that were written in the source.
723      llvm::SmallVector<CXXBaseOrMemberInitializer *, 4> WrittenInits;
724      for (CXXConstructorDecl::init_iterator I = Constructor->init_begin(),
725                                          IEnd = Constructor->init_end();
726           I != IEnd; ++I) {
727        if (!(*I)->isWritten())
728          continue;
729
730        WrittenInits.push_back(*I);
731      }
732
733      // Sort the initializers in source order
734      llvm::array_pod_sort(WrittenInits.begin(), WrittenInits.end(),
735                           &CompareCXXBaseOrMemberInitializers);
736
737      // Visit the initializers in source order
738      for (unsigned I = 0, N = WrittenInits.size(); I != N; ++I) {
739        CXXBaseOrMemberInitializer *Init = WrittenInits[I];
740        if (Init->isMemberInitializer()) {
741          if (Visit(MakeCursorMemberRef(Init->getMember(),
742                                        Init->getMemberLocation(), TU)))
743            return true;
744        } else if (TypeSourceInfo *BaseInfo = Init->getBaseClassInfo()) {
745          if (Visit(BaseInfo->getTypeLoc()))
746            return true;
747        }
748
749        // Visit the initializer value.
750        if (Expr *Initializer = Init->getInit())
751          if (Visit(MakeCXCursor(Initializer, ND, TU)))
752            return true;
753      }
754    }
755
756    if (Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
757      return true;
758  }
759
760  return false;
761}
762
763bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
764  if (VisitDeclaratorDecl(D))
765    return true;
766
767  if (Expr *BitWidth = D->getBitWidth())
768    return Visit(MakeCXCursor(BitWidth, StmtParent, TU));
769
770  return false;
771}
772
773bool CursorVisitor::VisitVarDecl(VarDecl *D) {
774  if (VisitDeclaratorDecl(D))
775    return true;
776
777  if (Expr *Init = D->getInit())
778    return Visit(MakeCXCursor(Init, StmtParent, TU));
779
780  return false;
781}
782
783bool CursorVisitor::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
784  if (VisitDeclaratorDecl(D))
785    return true;
786
787  if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
788    if (Expr *DefArg = D->getDefaultArgument())
789      return Visit(MakeCXCursor(DefArg, StmtParent, TU));
790
791  return false;
792}
793
794bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
795  // FIXME: Visit the "outer" template parameter lists on the FunctionDecl
796  // before visiting these template parameters.
797  if (VisitTemplateParameters(D->getTemplateParameters()))
798    return true;
799
800  return VisitFunctionDecl(D->getTemplatedDecl());
801}
802
803bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) {
804  // FIXME: Visit the "outer" template parameter lists on the TagDecl
805  // before visiting these template parameters.
806  if (VisitTemplateParameters(D->getTemplateParameters()))
807    return true;
808
809  return VisitCXXRecordDecl(D->getTemplatedDecl());
810}
811
812bool CursorVisitor::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
813  if (VisitTemplateParameters(D->getTemplateParameters()))
814    return true;
815
816  if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited() &&
817      VisitTemplateArgumentLoc(D->getDefaultArgument()))
818    return true;
819
820  return false;
821}
822
823bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
824  if (TypeSourceInfo *TSInfo = ND->getResultTypeSourceInfo())
825    if (Visit(TSInfo->getTypeLoc()))
826      return true;
827
828  for (ObjCMethodDecl::param_iterator P = ND->param_begin(),
829       PEnd = ND->param_end();
830       P != PEnd; ++P) {
831    if (Visit(MakeCXCursor(*P, TU)))
832      return true;
833  }
834
835  if (ND->isThisDeclarationADefinition() &&
836      Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
837    return true;
838
839  return false;
840}
841
842namespace {
843  struct ContainerDeclsSort {
844    SourceManager &SM;
845    ContainerDeclsSort(SourceManager &sm) : SM(sm) {}
846    bool operator()(Decl *A, Decl *B) {
847      SourceLocation L_A = A->getLocStart();
848      SourceLocation L_B = B->getLocStart();
849      assert(L_A.isValid() && L_B.isValid());
850      return SM.isBeforeInTranslationUnit(L_A, L_B);
851    }
852  };
853}
854
855bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
856  // FIXME: Eventually convert back to just 'VisitDeclContext()'.  Essentially
857  // an @implementation can lexically contain Decls that are not properly
858  // nested in the AST.  When we identify such cases, we need to retrofit
859  // this nesting here.
860  if (!DI_current)
861    return VisitDeclContext(D);
862
863  // Scan the Decls that immediately come after the container
864  // in the current DeclContext.  If any fall within the
865  // container's lexical region, stash them into a vector
866  // for later processing.
867  llvm::SmallVector<Decl *, 24> DeclsInContainer;
868  SourceLocation EndLoc = D->getSourceRange().getEnd();
869  SourceManager &SM = AU->getSourceManager();
870  if (EndLoc.isValid()) {
871    DeclContext::decl_iterator next = *DI_current;
872    while (++next != DE_current) {
873      Decl *D_next = *next;
874      if (!D_next)
875        break;
876      SourceLocation L = D_next->getLocStart();
877      if (!L.isValid())
878        break;
879      if (SM.isBeforeInTranslationUnit(L, EndLoc)) {
880        *DI_current = next;
881        DeclsInContainer.push_back(D_next);
882        continue;
883      }
884      break;
885    }
886  }
887
888  // The common case.
889  if (DeclsInContainer.empty())
890    return VisitDeclContext(D);
891
892  // Get all the Decls in the DeclContext, and sort them with the
893  // additional ones we've collected.  Then visit them.
894  for (DeclContext::decl_iterator I = D->decls_begin(), E = D->decls_end();
895       I!=E; ++I) {
896    Decl *subDecl = *I;
897    if (!subDecl || subDecl->getLexicalDeclContext() != D ||
898        subDecl->getLocStart().isInvalid())
899      continue;
900    DeclsInContainer.push_back(subDecl);
901  }
902
903  // Now sort the Decls so that they appear in lexical order.
904  std::sort(DeclsInContainer.begin(), DeclsInContainer.end(),
905            ContainerDeclsSort(SM));
906
907  // Now visit the decls.
908  for (llvm::SmallVectorImpl<Decl*>::iterator I = DeclsInContainer.begin(),
909         E = DeclsInContainer.end(); I != E; ++I) {
910    CXCursor Cursor = MakeCXCursor(*I, TU);
911    const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
912    if (!V.hasValue())
913      continue;
914    if (!V.getValue())
915      return false;
916    if (Visit(Cursor, true))
917      return true;
918  }
919  return false;
920}
921
922bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
923  if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
924                                   TU)))
925    return true;
926
927  ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
928  for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
929         E = ND->protocol_end(); I != E; ++I, ++PL)
930    if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
931      return true;
932
933  return VisitObjCContainerDecl(ND);
934}
935
936bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
937  ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
938  for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
939       E = PID->protocol_end(); I != E; ++I, ++PL)
940    if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
941      return true;
942
943  return VisitObjCContainerDecl(PID);
944}
945
946bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
947  if (PD->getTypeSourceInfo() && Visit(PD->getTypeSourceInfo()->getTypeLoc()))
948    return true;
949
950  // FIXME: This implements a workaround with @property declarations also being
951  // installed in the DeclContext for the @interface.  Eventually this code
952  // should be removed.
953  ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
954  if (!CDecl || !CDecl->IsClassExtension())
955    return false;
956
957  ObjCInterfaceDecl *ID = CDecl->getClassInterface();
958  if (!ID)
959    return false;
960
961  IdentifierInfo *PropertyId = PD->getIdentifier();
962  ObjCPropertyDecl *prevDecl =
963    ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId);
964
965  if (!prevDecl)
966    return false;
967
968  // Visit synthesized methods since they will be skipped when visiting
969  // the @interface.
970  if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
971    if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
972      if (Visit(MakeCXCursor(MD, TU)))
973        return true;
974
975  if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
976    if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
977      if (Visit(MakeCXCursor(MD, TU)))
978        return true;
979
980  return false;
981}
982
983bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
984  // Issue callbacks for super class.
985  if (D->getSuperClass() &&
986      Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
987                                        D->getSuperClassLoc(),
988                                        TU)))
989    return true;
990
991  ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
992  for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
993         E = D->protocol_end(); I != E; ++I, ++PL)
994    if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
995      return true;
996
997  return VisitObjCContainerDecl(D);
998}
999
1000bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
1001  return VisitObjCContainerDecl(D);
1002}
1003
1004bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
1005  // 'ID' could be null when dealing with invalid code.
1006  if (ObjCInterfaceDecl *ID = D->getClassInterface())
1007    if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
1008      return true;
1009
1010  return VisitObjCImplDecl(D);
1011}
1012
1013bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
1014#if 0
1015  // Issue callbacks for super class.
1016  // FIXME: No source location information!
1017  if (D->getSuperClass() &&
1018      Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
1019                                        D->getSuperClassLoc(),
1020                                        TU)))
1021    return true;
1022#endif
1023
1024  return VisitObjCImplDecl(D);
1025}
1026
1027bool CursorVisitor::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D) {
1028  ObjCForwardProtocolDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1029  for (ObjCForwardProtocolDecl::protocol_iterator I = D->protocol_begin(),
1030                                                  E = D->protocol_end();
1031       I != E; ++I, ++PL)
1032    if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
1033      return true;
1034
1035  return false;
1036}
1037
1038bool CursorVisitor::VisitObjCClassDecl(ObjCClassDecl *D) {
1039  for (ObjCClassDecl::iterator C = D->begin(), CEnd = D->end(); C != CEnd; ++C)
1040    if (Visit(MakeCursorObjCClassRef(C->getInterface(), C->getLocation(), TU)))
1041      return true;
1042
1043  return false;
1044}
1045
1046bool CursorVisitor::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *PD) {
1047  if (ObjCIvarDecl *Ivar = PD->getPropertyIvarDecl())
1048    return Visit(MakeCursorMemberRef(Ivar, PD->getPropertyIvarDeclLoc(), TU));
1049
1050  return false;
1051}
1052
1053bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
1054  return VisitDeclContext(D);
1055}
1056
1057bool CursorVisitor::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
1058  // Visit nested-name-specifier.
1059  if (NestedNameSpecifier *Qualifier = D->getQualifier())
1060    if (VisitNestedNameSpecifier(Qualifier, D->getQualifierRange()))
1061      return true;
1062
1063  return Visit(MakeCursorNamespaceRef(D->getAliasedNamespace(),
1064                                      D->getTargetNameLoc(), TU));
1065}
1066
1067bool CursorVisitor::VisitUsingDecl(UsingDecl *D) {
1068  // Visit nested-name-specifier.
1069  if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameDecl())
1070    if (VisitNestedNameSpecifier(Qualifier, D->getNestedNameRange()))
1071      return true;
1072
1073  if (Visit(MakeCursorOverloadedDeclRef(D, D->getLocation(), TU)))
1074    return true;
1075
1076  return VisitDeclarationNameInfo(D->getNameInfo());
1077}
1078
1079bool CursorVisitor::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
1080  // Visit nested-name-specifier.
1081  if (NestedNameSpecifier *Qualifier = D->getQualifier())
1082    if (VisitNestedNameSpecifier(Qualifier, D->getQualifierRange()))
1083      return true;
1084
1085  return Visit(MakeCursorNamespaceRef(D->getNominatedNamespaceAsWritten(),
1086                                      D->getIdentLocation(), TU));
1087}
1088
1089bool CursorVisitor::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
1090  // Visit nested-name-specifier.
1091  if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameSpecifier())
1092    if (VisitNestedNameSpecifier(Qualifier, D->getTargetNestedNameRange()))
1093      return true;
1094
1095  return VisitDeclarationNameInfo(D->getNameInfo());
1096}
1097
1098bool CursorVisitor::VisitUnresolvedUsingTypenameDecl(
1099                                               UnresolvedUsingTypenameDecl *D) {
1100  // Visit nested-name-specifier.
1101  if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameSpecifier())
1102    if (VisitNestedNameSpecifier(Qualifier, D->getTargetNestedNameRange()))
1103      return true;
1104
1105  return false;
1106}
1107
1108bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) {
1109  switch (Name.getName().getNameKind()) {
1110  case clang::DeclarationName::Identifier:
1111  case clang::DeclarationName::CXXLiteralOperatorName:
1112  case clang::DeclarationName::CXXOperatorName:
1113  case clang::DeclarationName::CXXUsingDirective:
1114    return false;
1115
1116  case clang::DeclarationName::CXXConstructorName:
1117  case clang::DeclarationName::CXXDestructorName:
1118  case clang::DeclarationName::CXXConversionFunctionName:
1119    if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo())
1120      return Visit(TSInfo->getTypeLoc());
1121    return false;
1122
1123  case clang::DeclarationName::ObjCZeroArgSelector:
1124  case clang::DeclarationName::ObjCOneArgSelector:
1125  case clang::DeclarationName::ObjCMultiArgSelector:
1126    // FIXME: Per-identifier location info?
1127    return false;
1128  }
1129
1130  return false;
1131}
1132
1133bool CursorVisitor::VisitNestedNameSpecifier(NestedNameSpecifier *NNS,
1134                                             SourceRange Range) {
1135  // FIXME: This whole routine is a hack to work around the lack of proper
1136  // source information in nested-name-specifiers (PR5791). Since we do have
1137  // a beginning source location, we can visit the first component of the
1138  // nested-name-specifier, if it's a single-token component.
1139  if (!NNS)
1140    return false;
1141
1142  // Get the first component in the nested-name-specifier.
1143  while (NestedNameSpecifier *Prefix = NNS->getPrefix())
1144    NNS = Prefix;
1145
1146  switch (NNS->getKind()) {
1147  case NestedNameSpecifier::Namespace:
1148    // FIXME: The token at this source location might actually have been a
1149    // namespace alias, but we don't model that. Lame!
1150    return Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(), Range.getBegin(),
1151                                        TU));
1152
1153  case NestedNameSpecifier::TypeSpec: {
1154    // If the type has a form where we know that the beginning of the source
1155    // range matches up with a reference cursor. Visit the appropriate reference
1156    // cursor.
1157    Type *T = NNS->getAsType();
1158    if (const TypedefType *Typedef = dyn_cast<TypedefType>(T))
1159      return Visit(MakeCursorTypeRef(Typedef->getDecl(), Range.getBegin(), TU));
1160    if (const TagType *Tag = dyn_cast<TagType>(T))
1161      return Visit(MakeCursorTypeRef(Tag->getDecl(), Range.getBegin(), TU));
1162    if (const TemplateSpecializationType *TST
1163                                      = dyn_cast<TemplateSpecializationType>(T))
1164      return VisitTemplateName(TST->getTemplateName(), Range.getBegin());
1165    break;
1166  }
1167
1168  case NestedNameSpecifier::TypeSpecWithTemplate:
1169  case NestedNameSpecifier::Global:
1170  case NestedNameSpecifier::Identifier:
1171    break;
1172  }
1173
1174  return false;
1175}
1176
1177bool CursorVisitor::VisitTemplateParameters(
1178                                          const TemplateParameterList *Params) {
1179  if (!Params)
1180    return false;
1181
1182  for (TemplateParameterList::const_iterator P = Params->begin(),
1183                                          PEnd = Params->end();
1184       P != PEnd; ++P) {
1185    if (Visit(MakeCXCursor(*P, TU)))
1186      return true;
1187  }
1188
1189  return false;
1190}
1191
1192bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) {
1193  switch (Name.getKind()) {
1194  case TemplateName::Template:
1195    return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU));
1196
1197  case TemplateName::OverloadedTemplate:
1198    // Visit the overloaded template set.
1199    if (Visit(MakeCursorOverloadedDeclRef(Name, Loc, TU)))
1200      return true;
1201
1202    return false;
1203
1204  case TemplateName::DependentTemplate:
1205    // FIXME: Visit nested-name-specifier.
1206    return false;
1207
1208  case TemplateName::QualifiedTemplate:
1209    // FIXME: Visit nested-name-specifier.
1210    return Visit(MakeCursorTemplateRef(
1211                                  Name.getAsQualifiedTemplateName()->getDecl(),
1212                                       Loc, TU));
1213  }
1214
1215  return false;
1216}
1217
1218bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) {
1219  switch (TAL.getArgument().getKind()) {
1220  case TemplateArgument::Null:
1221  case TemplateArgument::Integral:
1222    return false;
1223
1224  case TemplateArgument::Pack:
1225    // FIXME: Implement when variadic templates come along.
1226    return false;
1227
1228  case TemplateArgument::Type:
1229    if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo())
1230      return Visit(TSInfo->getTypeLoc());
1231    return false;
1232
1233  case TemplateArgument::Declaration:
1234    if (Expr *E = TAL.getSourceDeclExpression())
1235      return Visit(MakeCXCursor(E, StmtParent, TU));
1236    return false;
1237
1238  case TemplateArgument::Expression:
1239    if (Expr *E = TAL.getSourceExpression())
1240      return Visit(MakeCXCursor(E, StmtParent, TU));
1241    return false;
1242
1243  case TemplateArgument::Template:
1244    return VisitTemplateName(TAL.getArgument().getAsTemplate(),
1245                             TAL.getTemplateNameLoc());
1246  }
1247
1248  return false;
1249}
1250
1251bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1252  return VisitDeclContext(D);
1253}
1254
1255bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1256  return Visit(TL.getUnqualifiedLoc());
1257}
1258
1259bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
1260  ASTContext &Context = AU->getASTContext();
1261
1262  // Some builtin types (such as Objective-C's "id", "sel", and
1263  // "Class") have associated declarations. Create cursors for those.
1264  QualType VisitType;
1265  switch (TL.getType()->getAs<BuiltinType>()->getKind()) {
1266  case BuiltinType::Void:
1267  case BuiltinType::Bool:
1268  case BuiltinType::Char_U:
1269  case BuiltinType::UChar:
1270  case BuiltinType::Char16:
1271  case BuiltinType::Char32:
1272  case BuiltinType::UShort:
1273  case BuiltinType::UInt:
1274  case BuiltinType::ULong:
1275  case BuiltinType::ULongLong:
1276  case BuiltinType::UInt128:
1277  case BuiltinType::Char_S:
1278  case BuiltinType::SChar:
1279  case BuiltinType::WChar:
1280  case BuiltinType::Short:
1281  case BuiltinType::Int:
1282  case BuiltinType::Long:
1283  case BuiltinType::LongLong:
1284  case BuiltinType::Int128:
1285  case BuiltinType::Float:
1286  case BuiltinType::Double:
1287  case BuiltinType::LongDouble:
1288  case BuiltinType::NullPtr:
1289  case BuiltinType::Overload:
1290  case BuiltinType::Dependent:
1291    break;
1292
1293  case BuiltinType::UndeducedAuto: // FIXME: Deserves a cursor?
1294    break;
1295
1296  case BuiltinType::ObjCId:
1297    VisitType = Context.getObjCIdType();
1298    break;
1299
1300  case BuiltinType::ObjCClass:
1301    VisitType = Context.getObjCClassType();
1302    break;
1303
1304  case BuiltinType::ObjCSel:
1305    VisitType = Context.getObjCSelType();
1306    break;
1307  }
1308
1309  if (!VisitType.isNull()) {
1310    if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
1311      return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
1312                                     TU));
1313  }
1314
1315  return false;
1316}
1317
1318bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
1319  return Visit(MakeCursorTypeRef(TL.getTypedefDecl(), TL.getNameLoc(), TU));
1320}
1321
1322bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
1323  return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1324}
1325
1326bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
1327  return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1328}
1329
1330bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
1331  // FIXME: We can't visit the template type parameter, because there's
1332  // no context information with which we can match up the depth/index in the
1333  // type to the appropriate
1334  return false;
1335}
1336
1337bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
1338  if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
1339    return true;
1340
1341  return false;
1342}
1343
1344bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
1345  if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
1346    return true;
1347
1348  for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1349    if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1350                                        TU)))
1351      return true;
1352  }
1353
1354  return false;
1355}
1356
1357bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
1358  return Visit(TL.getPointeeLoc());
1359}
1360
1361bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
1362  return Visit(TL.getPointeeLoc());
1363}
1364
1365bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1366  return Visit(TL.getPointeeLoc());
1367}
1368
1369bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1370  return Visit(TL.getPointeeLoc());
1371}
1372
1373bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
1374  return Visit(TL.getPointeeLoc());
1375}
1376
1377bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
1378  return Visit(TL.getPointeeLoc());
1379}
1380
1381bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL,
1382                                         bool SkipResultType) {
1383  if (!SkipResultType && Visit(TL.getResultLoc()))
1384    return true;
1385
1386  for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1387    if (Decl *D = TL.getArg(I))
1388      if (Visit(MakeCXCursor(D, TU)))
1389        return true;
1390
1391  return false;
1392}
1393
1394bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
1395  if (Visit(TL.getElementLoc()))
1396    return true;
1397
1398  if (Expr *Size = TL.getSizeExpr())
1399    return Visit(MakeCXCursor(Size, StmtParent, TU));
1400
1401  return false;
1402}
1403
1404bool CursorVisitor::VisitTemplateSpecializationTypeLoc(
1405                                             TemplateSpecializationTypeLoc TL) {
1406  // Visit the template name.
1407  if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1408                        TL.getTemplateNameLoc()))
1409    return true;
1410
1411  // Visit the template arguments.
1412  for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1413    if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1414      return true;
1415
1416  return false;
1417}
1418
1419bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
1420  return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
1421}
1422
1423bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
1424  if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1425    return Visit(TSInfo->getTypeLoc());
1426
1427  return false;
1428}
1429
1430bool CursorVisitor::VisitStmt(Stmt *S) {
1431  return VisitDataRecursive(S);
1432}
1433
1434bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
1435  if (D->isDefinition()) {
1436    for (CXXRecordDecl::base_class_iterator I = D->bases_begin(),
1437         E = D->bases_end(); I != E; ++I) {
1438      if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(I, TU)))
1439        return true;
1440    }
1441  }
1442
1443  return VisitTagDecl(D);
1444}
1445
1446bool CursorVisitor::VisitOffsetOfExpr(OffsetOfExpr *E) {
1447  // Visit the type into which we're computing an offset.
1448  if (Visit(E->getTypeSourceInfo()->getTypeLoc()))
1449    return true;
1450
1451  // Visit the components of the offsetof expression.
1452  for (unsigned I = 0, N = E->getNumComponents(); I != N; ++I) {
1453    typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
1454    const OffsetOfNode &Node = E->getComponent(I);
1455    switch (Node.getKind()) {
1456    case OffsetOfNode::Array:
1457      if (Visit(MakeCXCursor(E->getIndexExpr(Node.getArrayExprIndex()),
1458                             StmtParent, TU)))
1459        return true;
1460      break;
1461
1462    case OffsetOfNode::Field:
1463      if (Visit(MakeCursorMemberRef(Node.getField(), Node.getRange().getEnd(),
1464                                    TU)))
1465        return true;
1466      break;
1467
1468    case OffsetOfNode::Identifier:
1469    case OffsetOfNode::Base:
1470      continue;
1471    }
1472  }
1473
1474  return false;
1475}
1476
1477bool CursorVisitor::VisitDesignatedInitExpr(DesignatedInitExpr *E) {
1478  // Visit the designators.
1479  typedef DesignatedInitExpr::Designator Designator;
1480  for (DesignatedInitExpr::designators_iterator D = E->designators_begin(),
1481                                             DEnd = E->designators_end();
1482       D != DEnd; ++D) {
1483    if (D->isFieldDesignator()) {
1484      if (FieldDecl *Field = D->getField())
1485        if (Visit(MakeCursorMemberRef(Field, D->getFieldLoc(), TU)))
1486          return true;
1487
1488      continue;
1489    }
1490
1491    if (D->isArrayDesignator()) {
1492      if (Visit(MakeCXCursor(E->getArrayIndex(*D), StmtParent, TU)))
1493        return true;
1494
1495      continue;
1496    }
1497
1498    assert(D->isArrayRangeDesignator() && "Unknown designator kind");
1499    if (Visit(MakeCXCursor(E->getArrayRangeStart(*D), StmtParent, TU)) ||
1500        Visit(MakeCXCursor(E->getArrayRangeEnd(*D), StmtParent, TU)))
1501      return true;
1502  }
1503
1504  // Visit the initializer value itself.
1505  return Visit(MakeCXCursor(E->getInit(), StmtParent, TU));
1506}
1507
1508bool CursorVisitor::VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E) {
1509  // Visit base expression.
1510  if (Visit(MakeCXCursor(E->getBase(), StmtParent, TU)))
1511    return true;
1512
1513  // Visit the nested-name-specifier.
1514  if (NestedNameSpecifier *Qualifier = E->getQualifier())
1515    if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1516      return true;
1517
1518  // Visit the scope type that looks disturbingly like the nested-name-specifier
1519  // but isn't.
1520  if (TypeSourceInfo *TSInfo = E->getScopeTypeInfo())
1521    if (Visit(TSInfo->getTypeLoc()))
1522      return true;
1523
1524  // Visit the name of the type being destroyed.
1525  if (TypeSourceInfo *TSInfo = E->getDestroyedTypeInfo())
1526    if (Visit(TSInfo->getTypeLoc()))
1527      return true;
1528
1529  return false;
1530}
1531
1532bool CursorVisitor::VisitDependentScopeDeclRefExpr(
1533                                                DependentScopeDeclRefExpr *E) {
1534  // Visit the nested-name-specifier.
1535  if (NestedNameSpecifier *Qualifier = E->getQualifier())
1536    if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1537      return true;
1538
1539  // Visit the declaration name.
1540  if (VisitDeclarationNameInfo(E->getNameInfo()))
1541    return true;
1542
1543  // Visit the explicitly-specified template arguments.
1544  if (const ExplicitTemplateArgumentList *ArgList
1545      = E->getOptionalExplicitTemplateArgs()) {
1546    for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
1547         *ArgEnd = Arg + ArgList->NumTemplateArgs;
1548         Arg != ArgEnd; ++Arg) {
1549      if (VisitTemplateArgumentLoc(*Arg))
1550        return true;
1551    }
1552  }
1553
1554  return false;
1555}
1556
1557bool CursorVisitor::VisitCXXDependentScopeMemberExpr(
1558                                              CXXDependentScopeMemberExpr *E) {
1559  // Visit the base expression, if there is one.
1560  if (!E->isImplicitAccess() &&
1561      Visit(MakeCXCursor(E->getBase(), StmtParent, TU)))
1562    return true;
1563
1564  // Visit the nested-name-specifier.
1565  if (NestedNameSpecifier *Qualifier = E->getQualifier())
1566    if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1567      return true;
1568
1569  // Visit the declaration name.
1570  if (VisitDeclarationNameInfo(E->getMemberNameInfo()))
1571    return true;
1572
1573  // Visit the explicitly-specified template arguments.
1574  if (const ExplicitTemplateArgumentList *ArgList
1575      = E->getOptionalExplicitTemplateArgs()) {
1576    for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
1577         *ArgEnd = Arg + ArgList->NumTemplateArgs;
1578         Arg != ArgEnd; ++Arg) {
1579      if (VisitTemplateArgumentLoc(*Arg))
1580        return true;
1581    }
1582  }
1583
1584  return false;
1585}
1586
1587bool CursorVisitor::VisitAttributes(Decl *D) {
1588  for (AttrVec::const_iterator i = D->attr_begin(), e = D->attr_end();
1589       i != e; ++i)
1590    if (Visit(MakeCXCursor(*i, D, TU)))
1591        return true;
1592
1593  return false;
1594}
1595
1596//===----------------------------------------------------------------------===//
1597// Data-recursive visitor methods.
1598//===----------------------------------------------------------------------===//
1599
1600namespace {
1601#define DEF_JOB(NAME, DATA, KIND)\
1602class NAME : public VisitorJob {\
1603public:\
1604  NAME(DATA *d, CXCursor parent) : VisitorJob(parent, VisitorJob::KIND, d) {} \
1605  static bool classof(const VisitorJob *VJ) { return VJ->getKind() == KIND; }\
1606  DATA *get() const { return static_cast<DATA*>(dataA); }\
1607};
1608
1609DEF_JOB(StmtVisit, Stmt, StmtVisitKind)
1610DEF_JOB(MemberExprParts, MemberExpr, MemberExprPartsKind)
1611DEF_JOB(DeclRefExprParts, DeclRefExpr, DeclRefExprPartsKind)
1612DEF_JOB(OverloadExprParts, OverloadExpr, OverloadExprPartsKind)
1613DEF_JOB(ExplicitTemplateArgsVisit, ExplicitTemplateArgumentList,
1614        ExplicitTemplateArgsVisitKind)
1615#undef DEF_JOB
1616
1617class DeclVisit : public VisitorJob {
1618public:
1619  DeclVisit(Decl *d, CXCursor parent, bool isFirst) :
1620    VisitorJob(parent, VisitorJob::DeclVisitKind,
1621               d, isFirst ? (void*) 1 : (void*) 0) {}
1622  static bool classof(const VisitorJob *VJ) {
1623    return VJ->getKind() == DeclVisitKind;
1624  }
1625  Decl *get() const { return static_cast<Decl*>(dataA); }
1626  bool isFirst() const { return dataB ? true : false; }
1627};
1628class TypeLocVisit : public VisitorJob {
1629public:
1630  TypeLocVisit(TypeLoc tl, CXCursor parent) :
1631    VisitorJob(parent, VisitorJob::TypeLocVisitKind,
1632               tl.getType().getAsOpaquePtr(), tl.getOpaqueData()) {}
1633
1634  static bool classof(const VisitorJob *VJ) {
1635    return VJ->getKind() == TypeLocVisitKind;
1636  }
1637
1638  TypeLoc get() const {
1639    QualType T = QualType::getFromOpaquePtr(dataA);
1640    return TypeLoc(T, dataB);
1641  }
1642};
1643
1644class LabelRefVisit : public VisitorJob {
1645public:
1646  LabelRefVisit(LabelStmt *LS, SourceLocation labelLoc, CXCursor parent)
1647    : VisitorJob(parent, VisitorJob::LabelRefVisitKind, LS,
1648                 (void*) labelLoc.getRawEncoding()) {}
1649
1650  static bool classof(const VisitorJob *VJ) {
1651    return VJ->getKind() == VisitorJob::LabelRefVisitKind;
1652  }
1653  LabelStmt *get() const { return static_cast<LabelStmt*>(dataA); }
1654  SourceLocation getLoc() const {
1655    return SourceLocation::getFromRawEncoding((unsigned)(uintptr_t) dataB); }
1656};
1657
1658class EnqueueVisitor : public StmtVisitor<EnqueueVisitor, void> {
1659  VisitorWorkList &WL;
1660  CXCursor Parent;
1661public:
1662  EnqueueVisitor(VisitorWorkList &wl, CXCursor parent)
1663    : WL(wl), Parent(parent) {}
1664
1665  void VisitAddrLabelExpr(AddrLabelExpr *E);
1666  void VisitBlockExpr(BlockExpr *B);
1667  void VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
1668  void VisitCompoundStmt(CompoundStmt *S);
1669  void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { /* Do nothing. */ }
1670  void VisitCXXNewExpr(CXXNewExpr *E);
1671  void VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
1672  void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E);
1673  void VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E);
1674  void VisitCXXTypeidExpr(CXXTypeidExpr *E);
1675  void VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr *E);
1676  void VisitCXXUuidofExpr(CXXUuidofExpr *E);
1677  void VisitDeclRefExpr(DeclRefExpr *D);
1678  void VisitDeclStmt(DeclStmt *S);
1679  void VisitExplicitCastExpr(ExplicitCastExpr *E);
1680  void VisitForStmt(ForStmt *FS);
1681  void VisitGotoStmt(GotoStmt *GS);
1682  void VisitIfStmt(IfStmt *If);
1683  void VisitInitListExpr(InitListExpr *IE);
1684  void VisitMemberExpr(MemberExpr *M);
1685  void VisitObjCEncodeExpr(ObjCEncodeExpr *E);
1686  void VisitObjCMessageExpr(ObjCMessageExpr *M);
1687  void VisitOverloadExpr(OverloadExpr *E);
1688  void VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E);
1689  void VisitStmt(Stmt *S);
1690  void VisitSwitchStmt(SwitchStmt *S);
1691  void VisitTypesCompatibleExpr(TypesCompatibleExpr *E);
1692  void VisitWhileStmt(WhileStmt *W);
1693  void VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E);
1694  void VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U);
1695  void VisitVAArgExpr(VAArgExpr *E);
1696
1697private:
1698  void AddExplicitTemplateArgs(const ExplicitTemplateArgumentList *A);
1699  void AddStmt(Stmt *S);
1700  void AddDecl(Decl *D, bool isFirst = true);
1701  void AddTypeLoc(TypeSourceInfo *TI);
1702  void EnqueueChildren(Stmt *S);
1703};
1704} // end anonyous namespace
1705
1706void EnqueueVisitor::AddStmt(Stmt *S) {
1707  if (S)
1708    WL.push_back(StmtVisit(S, Parent));
1709}
1710void EnqueueVisitor::AddDecl(Decl *D, bool isFirst) {
1711  if (D)
1712    WL.push_back(DeclVisit(D, Parent, isFirst));
1713}
1714void EnqueueVisitor::
1715  AddExplicitTemplateArgs(const ExplicitTemplateArgumentList *A) {
1716  if (A)
1717    WL.push_back(ExplicitTemplateArgsVisit(
1718                        const_cast<ExplicitTemplateArgumentList*>(A), Parent));
1719}
1720void EnqueueVisitor::AddTypeLoc(TypeSourceInfo *TI) {
1721  if (TI)
1722    WL.push_back(TypeLocVisit(TI->getTypeLoc(), Parent));
1723 }
1724void EnqueueVisitor::EnqueueChildren(Stmt *S) {
1725  unsigned size = WL.size();
1726  for (Stmt::child_iterator Child = S->child_begin(), ChildEnd = S->child_end();
1727       Child != ChildEnd; ++Child) {
1728    AddStmt(*Child);
1729  }
1730  if (size == WL.size())
1731    return;
1732  // Now reverse the entries we just added.  This will match the DFS
1733  // ordering performed by the worklist.
1734  VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1735  std::reverse(I, E);
1736}
1737void EnqueueVisitor::VisitAddrLabelExpr(AddrLabelExpr *E) {
1738  WL.push_back(LabelRefVisit(E->getLabel(), E->getLabelLoc(), Parent));
1739}
1740void EnqueueVisitor::VisitBlockExpr(BlockExpr *B) {
1741  AddDecl(B->getBlockDecl());
1742}
1743void EnqueueVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
1744  EnqueueChildren(E);
1745  AddTypeLoc(E->getTypeSourceInfo());
1746}
1747void EnqueueVisitor::VisitCompoundStmt(CompoundStmt *S) {
1748  for (CompoundStmt::reverse_body_iterator I = S->body_rbegin(),
1749        E = S->body_rend(); I != E; ++I) {
1750    AddStmt(*I);
1751  }
1752}
1753void EnqueueVisitor::VisitCXXNewExpr(CXXNewExpr *E) {
1754  // Enqueue the initializer or constructor arguments.
1755  for (unsigned I = E->getNumConstructorArgs(); I > 0; --I)
1756    AddStmt(E->getConstructorArg(I-1));
1757  // Enqueue the array size, if any.
1758  AddStmt(E->getArraySize());
1759  // Enqueue the allocated type.
1760  AddTypeLoc(E->getAllocatedTypeSourceInfo());
1761  // Enqueue the placement arguments.
1762  for (unsigned I = E->getNumPlacementArgs(); I > 0; --I)
1763    AddStmt(E->getPlacementArg(I-1));
1764}
1765void EnqueueVisitor::VisitCXXOperatorCallExpr(CXXOperatorCallExpr *CE) {
1766  for (unsigned I = CE->getNumArgs(); I > 1 /* Yes, this is 1 */; --I)
1767    AddStmt(CE->getArg(I-1));
1768  AddStmt(CE->getCallee());
1769  AddStmt(CE->getArg(0));
1770}
1771void EnqueueVisitor::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
1772  AddTypeLoc(E->getTypeSourceInfo());
1773}
1774void EnqueueVisitor::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E) {
1775  EnqueueChildren(E);
1776  AddTypeLoc(E->getTypeSourceInfo());
1777}
1778void EnqueueVisitor::VisitCXXTypeidExpr(CXXTypeidExpr *E) {
1779  EnqueueChildren(E);
1780  if (E->isTypeOperand())
1781    AddTypeLoc(E->getTypeOperandSourceInfo());
1782}
1783
1784void EnqueueVisitor::VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr
1785                                                     *E) {
1786  EnqueueChildren(E);
1787  AddTypeLoc(E->getTypeSourceInfo());
1788}
1789void EnqueueVisitor::VisitCXXUuidofExpr(CXXUuidofExpr *E) {
1790  EnqueueChildren(E);
1791  if (E->isTypeOperand())
1792    AddTypeLoc(E->getTypeOperandSourceInfo());
1793}
1794void EnqueueVisitor::VisitDeclRefExpr(DeclRefExpr *DR) {
1795  if (DR->hasExplicitTemplateArgs()) {
1796    AddExplicitTemplateArgs(&DR->getExplicitTemplateArgs());
1797  }
1798  WL.push_back(DeclRefExprParts(DR, Parent));
1799}
1800void EnqueueVisitor::VisitDeclStmt(DeclStmt *S) {
1801  unsigned size = WL.size();
1802  bool isFirst = true;
1803  for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
1804       D != DEnd; ++D) {
1805    AddDecl(*D, isFirst);
1806    isFirst = false;
1807  }
1808  if (size == WL.size())
1809    return;
1810  // Now reverse the entries we just added.  This will match the DFS
1811  // ordering performed by the worklist.
1812  VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1813  std::reverse(I, E);
1814}
1815void EnqueueVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
1816  EnqueueChildren(E);
1817  AddTypeLoc(E->getTypeInfoAsWritten());
1818}
1819void EnqueueVisitor::VisitForStmt(ForStmt *FS) {
1820  AddStmt(FS->getBody());
1821  AddStmt(FS->getInc());
1822  AddStmt(FS->getCond());
1823  AddDecl(FS->getConditionVariable());
1824  AddStmt(FS->getInit());
1825}
1826void EnqueueVisitor::VisitGotoStmt(GotoStmt *GS) {
1827  WL.push_back(LabelRefVisit(GS->getLabel(), GS->getLabelLoc(), Parent));
1828}
1829void EnqueueVisitor::VisitIfStmt(IfStmt *If) {
1830  AddStmt(If->getElse());
1831  AddStmt(If->getThen());
1832  AddStmt(If->getCond());
1833  AddDecl(If->getConditionVariable());
1834}
1835void EnqueueVisitor::VisitInitListExpr(InitListExpr *IE) {
1836  // We care about the syntactic form of the initializer list, only.
1837  if (InitListExpr *Syntactic = IE->getSyntacticForm())
1838    IE = Syntactic;
1839  EnqueueChildren(IE);
1840}
1841void EnqueueVisitor::VisitMemberExpr(MemberExpr *M) {
1842  WL.push_back(MemberExprParts(M, Parent));
1843  AddStmt(M->getBase());
1844}
1845void EnqueueVisitor::VisitObjCEncodeExpr(ObjCEncodeExpr *E) {
1846  AddTypeLoc(E->getEncodedTypeSourceInfo());
1847}
1848void EnqueueVisitor::VisitObjCMessageExpr(ObjCMessageExpr *M) {
1849  EnqueueChildren(M);
1850  AddTypeLoc(M->getClassReceiverTypeInfo());
1851}
1852void EnqueueVisitor::VisitOverloadExpr(OverloadExpr *E) {
1853  AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
1854  WL.push_back(OverloadExprParts(E, Parent));
1855}
1856void EnqueueVisitor::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E) {
1857  EnqueueChildren(E);
1858  if (E->isArgumentType())
1859    AddTypeLoc(E->getArgumentTypeInfo());
1860}
1861void EnqueueVisitor::VisitStmt(Stmt *S) {
1862  EnqueueChildren(S);
1863}
1864void EnqueueVisitor::VisitSwitchStmt(SwitchStmt *S) {
1865  AddStmt(S->getBody());
1866  AddStmt(S->getCond());
1867  AddDecl(S->getConditionVariable());
1868}
1869void EnqueueVisitor::VisitTypesCompatibleExpr(TypesCompatibleExpr *E) {
1870  AddTypeLoc(E->getArgTInfo2());
1871  AddTypeLoc(E->getArgTInfo1());
1872}
1873
1874void EnqueueVisitor::VisitWhileStmt(WhileStmt *W) {
1875  AddStmt(W->getBody());
1876  AddStmt(W->getCond());
1877  AddDecl(W->getConditionVariable());
1878}
1879void EnqueueVisitor::VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E) {
1880  AddTypeLoc(E->getQueriedTypeSourceInfo());
1881}
1882void EnqueueVisitor::VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U) {
1883  VisitOverloadExpr(U);
1884  if (!U->isImplicitAccess())
1885    AddStmt(U->getBase());
1886}
1887void EnqueueVisitor::VisitVAArgExpr(VAArgExpr *E) {
1888  AddStmt(E->getSubExpr());
1889  AddTypeLoc(E->getWrittenTypeInfo());
1890}
1891
1892void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, Stmt *S) {
1893  EnqueueVisitor(WL, MakeCXCursor(S, StmtParent, TU)).Visit(S);
1894}
1895
1896bool CursorVisitor::IsInRegionOfInterest(CXCursor C) {
1897  if (RegionOfInterest.isValid()) {
1898    SourceRange Range = getRawCursorExtent(C);
1899    if (Range.isInvalid() || CompareRegionOfInterest(Range))
1900      return false;
1901  }
1902  return true;
1903}
1904
1905bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) {
1906  while (!WL.empty()) {
1907    // Dequeue the worklist item.
1908    VisitorJob LI = WL.back();
1909    WL.pop_back();
1910
1911    // Set the Parent field, then back to its old value once we're done.
1912    SetParentRAII SetParent(Parent, StmtParent, LI.getParent());
1913
1914    switch (LI.getKind()) {
1915      case VisitorJob::DeclVisitKind: {
1916        Decl *D = cast<DeclVisit>(&LI)->get();
1917        if (!D)
1918          continue;
1919
1920        // For now, perform default visitation for Decls.
1921        if (Visit(MakeCXCursor(D, TU, cast<DeclVisit>(&LI)->isFirst())))
1922            return true;
1923
1924        continue;
1925      }
1926      case VisitorJob::ExplicitTemplateArgsVisitKind: {
1927        const ExplicitTemplateArgumentList *ArgList =
1928          cast<ExplicitTemplateArgsVisit>(&LI)->get();
1929        for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
1930               *ArgEnd = Arg + ArgList->NumTemplateArgs;
1931               Arg != ArgEnd; ++Arg) {
1932          if (VisitTemplateArgumentLoc(*Arg))
1933            return true;
1934        }
1935        continue;
1936      }
1937      case VisitorJob::TypeLocVisitKind: {
1938        // Perform default visitation for TypeLocs.
1939        if (Visit(cast<TypeLocVisit>(&LI)->get()))
1940          return true;
1941        continue;
1942      }
1943      case VisitorJob::LabelRefVisitKind: {
1944        LabelStmt *LS = cast<LabelRefVisit>(&LI)->get();
1945        if (Visit(MakeCursorLabelRef(LS,
1946                                     cast<LabelRefVisit>(&LI)->getLoc(),
1947                                     TU)))
1948          return true;
1949        continue;
1950      }
1951      case VisitorJob::StmtVisitKind: {
1952        Stmt *S = cast<StmtVisit>(&LI)->get();
1953        if (!S)
1954          continue;
1955
1956        // Update the current cursor.
1957        CXCursor Cursor = MakeCXCursor(S, StmtParent, TU);
1958
1959        switch (S->getStmtClass()) {
1960          // Cases not yet handled by the data-recursion
1961          // algorithm.
1962          case Stmt::OffsetOfExprClass:
1963          case Stmt::DesignatedInitExprClass:
1964          case Stmt::CXXPseudoDestructorExprClass:
1965          case Stmt::DependentScopeDeclRefExprClass:
1966          case Stmt::CXXDependentScopeMemberExprClass:
1967            if (Visit(Cursor))
1968              return true;
1969            break;
1970          default:
1971            if (!IsInRegionOfInterest(Cursor))
1972              continue;
1973            switch (Visitor(Cursor, Parent, ClientData)) {
1974              case CXChildVisit_Break:
1975                return true;
1976              case CXChildVisit_Continue:
1977                break;
1978              case CXChildVisit_Recurse:
1979                EnqueueWorkList(WL, S);
1980                break;
1981            }
1982            break;
1983        }
1984        continue;
1985      }
1986      case VisitorJob::MemberExprPartsKind: {
1987        // Handle the other pieces in the MemberExpr besides the base.
1988        MemberExpr *M = cast<MemberExprParts>(&LI)->get();
1989
1990        // Visit the nested-name-specifier
1991        if (NestedNameSpecifier *Qualifier = M->getQualifier())
1992          if (VisitNestedNameSpecifier(Qualifier, M->getQualifierRange()))
1993            return true;
1994
1995        // Visit the declaration name.
1996        if (VisitDeclarationNameInfo(M->getMemberNameInfo()))
1997          return true;
1998
1999        // Visit the explicitly-specified template arguments, if any.
2000        if (M->hasExplicitTemplateArgs()) {
2001          for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(),
2002               *ArgEnd = Arg + M->getNumTemplateArgs();
2003               Arg != ArgEnd; ++Arg) {
2004            if (VisitTemplateArgumentLoc(*Arg))
2005              return true;
2006          }
2007        }
2008        continue;
2009      }
2010      case VisitorJob::DeclRefExprPartsKind: {
2011        DeclRefExpr *DR = cast<DeclRefExprParts>(&LI)->get();
2012        // Visit nested-name-specifier, if present.
2013        if (NestedNameSpecifier *Qualifier = DR->getQualifier())
2014          if (VisitNestedNameSpecifier(Qualifier, DR->getQualifierRange()))
2015            return true;
2016        // Visit declaration name.
2017        if (VisitDeclarationNameInfo(DR->getNameInfo()))
2018          return true;
2019        continue;
2020      }
2021      case VisitorJob::OverloadExprPartsKind: {
2022        OverloadExpr *O = cast<OverloadExprParts>(&LI)->get();
2023        // Visit the nested-name-specifier.
2024        if (NestedNameSpecifier *Qualifier = O->getQualifier())
2025          if (VisitNestedNameSpecifier(Qualifier, O->getQualifierRange()))
2026            return true;
2027        // Visit the declaration name.
2028        if (VisitDeclarationNameInfo(O->getNameInfo()))
2029          return true;
2030        // Visit the overloaded declaration reference.
2031        if (Visit(MakeCursorOverloadedDeclRef(O, TU)))
2032          return true;
2033        continue;
2034      }
2035    }
2036  }
2037  return false;
2038}
2039
2040bool CursorVisitor::VisitDataRecursive(Stmt *S) {
2041  VisitorWorkList *WL = 0;
2042  if (!WorkListFreeList.empty()) {
2043    WL = WorkListFreeList.back();
2044    WL->clear();
2045    WorkListFreeList.pop_back();
2046  }
2047  else {
2048    WL = new VisitorWorkList();
2049    WorkListCache.push_back(WL);
2050  }
2051  EnqueueWorkList(*WL, S);
2052  bool result = RunVisitorWorkList(*WL);
2053  WorkListFreeList.push_back(WL);
2054  return result;
2055}
2056
2057//===----------------------------------------------------------------------===//
2058// Misc. API hooks.
2059//===----------------------------------------------------------------------===//
2060
2061static llvm::sys::Mutex EnableMultithreadingMutex;
2062static bool EnabledMultithreading;
2063
2064extern "C" {
2065CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
2066                          int displayDiagnostics) {
2067  // Disable pretty stack trace functionality, which will otherwise be a very
2068  // poor citizen of the world and set up all sorts of signal handlers.
2069  llvm::DisablePrettyStackTrace = true;
2070
2071  // We use crash recovery to make some of our APIs more reliable, implicitly
2072  // enable it.
2073  llvm::CrashRecoveryContext::Enable();
2074
2075  // Enable support for multithreading in LLVM.
2076  {
2077    llvm::sys::ScopedLock L(EnableMultithreadingMutex);
2078    if (!EnabledMultithreading) {
2079      llvm::llvm_start_multithreaded();
2080      EnabledMultithreading = true;
2081    }
2082  }
2083
2084  CIndexer *CIdxr = new CIndexer();
2085  if (excludeDeclarationsFromPCH)
2086    CIdxr->setOnlyLocalDecls();
2087  if (displayDiagnostics)
2088    CIdxr->setDisplayDiagnostics();
2089  return CIdxr;
2090}
2091
2092void clang_disposeIndex(CXIndex CIdx) {
2093  if (CIdx)
2094    delete static_cast<CIndexer *>(CIdx);
2095}
2096
2097CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
2098                                              const char *ast_filename) {
2099  if (!CIdx)
2100    return 0;
2101
2102  CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
2103  FileSystemOptions FileSystemOpts;
2104  FileSystemOpts.WorkingDir = CXXIdx->getWorkingDirectory();
2105
2106  llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
2107  ASTUnit *TU = ASTUnit::LoadFromASTFile(ast_filename, Diags, FileSystemOpts,
2108                                  CXXIdx->getOnlyLocalDecls(),
2109                                  0, 0, true);
2110  return MakeCXTranslationUnit(TU);
2111}
2112
2113unsigned clang_defaultEditingTranslationUnitOptions() {
2114  return CXTranslationUnit_PrecompiledPreamble |
2115         CXTranslationUnit_CacheCompletionResults |
2116         CXTranslationUnit_CXXPrecompiledPreamble;
2117}
2118
2119CXTranslationUnit
2120clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
2121                                          const char *source_filename,
2122                                          int num_command_line_args,
2123                                          const char * const *command_line_args,
2124                                          unsigned num_unsaved_files,
2125                                          struct CXUnsavedFile *unsaved_files) {
2126  return clang_parseTranslationUnit(CIdx, source_filename,
2127                                    command_line_args, num_command_line_args,
2128                                    unsaved_files, num_unsaved_files,
2129                                 CXTranslationUnit_DetailedPreprocessingRecord);
2130}
2131
2132struct ParseTranslationUnitInfo {
2133  CXIndex CIdx;
2134  const char *source_filename;
2135  const char *const *command_line_args;
2136  int num_command_line_args;
2137  struct CXUnsavedFile *unsaved_files;
2138  unsigned num_unsaved_files;
2139  unsigned options;
2140  CXTranslationUnit result;
2141};
2142static void clang_parseTranslationUnit_Impl(void *UserData) {
2143  ParseTranslationUnitInfo *PTUI =
2144    static_cast<ParseTranslationUnitInfo*>(UserData);
2145  CXIndex CIdx = PTUI->CIdx;
2146  const char *source_filename = PTUI->source_filename;
2147  const char * const *command_line_args = PTUI->command_line_args;
2148  int num_command_line_args = PTUI->num_command_line_args;
2149  struct CXUnsavedFile *unsaved_files = PTUI->unsaved_files;
2150  unsigned num_unsaved_files = PTUI->num_unsaved_files;
2151  unsigned options = PTUI->options;
2152  PTUI->result = 0;
2153
2154  if (!CIdx)
2155    return;
2156
2157  CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
2158
2159  bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
2160  bool CompleteTranslationUnit
2161    = ((options & CXTranslationUnit_Incomplete) == 0);
2162  bool CacheCodeCompetionResults
2163    = options & CXTranslationUnit_CacheCompletionResults;
2164  bool CXXPrecompilePreamble
2165    = options & CXTranslationUnit_CXXPrecompiledPreamble;
2166  bool CXXChainedPCH
2167    = options & CXTranslationUnit_CXXChainedPCH;
2168
2169  // Configure the diagnostics.
2170  DiagnosticOptions DiagOpts;
2171  llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
2172  Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
2173
2174  llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
2175  for (unsigned I = 0; I != num_unsaved_files; ++I) {
2176    llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
2177    const llvm::MemoryBuffer *Buffer
2178      = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
2179    RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
2180                                           Buffer));
2181  }
2182
2183  llvm::SmallVector<const char *, 16> Args;
2184
2185  // The 'source_filename' argument is optional.  If the caller does not
2186  // specify it then it is assumed that the source file is specified
2187  // in the actual argument list.
2188  if (source_filename)
2189    Args.push_back(source_filename);
2190
2191  // Since the Clang C library is primarily used by batch tools dealing with
2192  // (often very broken) source code, where spell-checking can have a
2193  // significant negative impact on performance (particularly when
2194  // precompiled headers are involved), we disable it by default.
2195  // Only do this if we haven't found a spell-checking-related argument.
2196  bool FoundSpellCheckingArgument = false;
2197  for (int I = 0; I != num_command_line_args; ++I) {
2198    if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
2199        strcmp(command_line_args[I], "-fspell-checking") == 0) {
2200      FoundSpellCheckingArgument = true;
2201      break;
2202    }
2203  }
2204  if (!FoundSpellCheckingArgument)
2205    Args.push_back("-fno-spell-checking");
2206
2207  Args.insert(Args.end(), command_line_args,
2208              command_line_args + num_command_line_args);
2209
2210  // Do we need the detailed preprocessing record?
2211  if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
2212    Args.push_back("-Xclang");
2213    Args.push_back("-detailed-preprocessing-record");
2214  }
2215
2216  unsigned NumErrors = Diags->getNumErrors();
2217  llvm::OwningPtr<ASTUnit> Unit(
2218    ASTUnit::LoadFromCommandLine(Args.data(), Args.data() + Args.size(),
2219                                 Diags,
2220                                 CXXIdx->getClangResourcesPath(),
2221                                 CXXIdx->getOnlyLocalDecls(),
2222                                 /*CaptureDiagnostics=*/true,
2223                                 RemappedFiles.data(),
2224                                 RemappedFiles.size(),
2225                                 PrecompilePreamble,
2226                                 CompleteTranslationUnit,
2227                                 CacheCodeCompetionResults,
2228                                 CXXPrecompilePreamble,
2229                                 CXXChainedPCH));
2230
2231  if (NumErrors != Diags->getNumErrors()) {
2232    // Make sure to check that 'Unit' is non-NULL.
2233    if (CXXIdx->getDisplayDiagnostics() && Unit.get()) {
2234      for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
2235                                      DEnd = Unit->stored_diag_end();
2236           D != DEnd; ++D) {
2237        CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOptions());
2238        CXString Msg = clang_formatDiagnostic(&Diag,
2239                                    clang_defaultDiagnosticDisplayOptions());
2240        fprintf(stderr, "%s\n", clang_getCString(Msg));
2241        clang_disposeString(Msg);
2242      }
2243#ifdef LLVM_ON_WIN32
2244      // On Windows, force a flush, since there may be multiple copies of
2245      // stderr and stdout in the file system, all with different buffers
2246      // but writing to the same device.
2247      fflush(stderr);
2248#endif
2249    }
2250  }
2251
2252  PTUI->result = MakeCXTranslationUnit(Unit.take());
2253}
2254CXTranslationUnit clang_parseTranslationUnit(CXIndex CIdx,
2255                                             const char *source_filename,
2256                                         const char * const *command_line_args,
2257                                             int num_command_line_args,
2258                                            struct CXUnsavedFile *unsaved_files,
2259                                             unsigned num_unsaved_files,
2260                                             unsigned options) {
2261  ParseTranslationUnitInfo PTUI = { CIdx, source_filename, command_line_args,
2262                                    num_command_line_args, unsaved_files,
2263                                    num_unsaved_files, options, 0 };
2264  llvm::CrashRecoveryContext CRC;
2265
2266  if (!RunSafely(CRC, clang_parseTranslationUnit_Impl, &PTUI)) {
2267    fprintf(stderr, "libclang: crash detected during parsing: {\n");
2268    fprintf(stderr, "  'source_filename' : '%s'\n", source_filename);
2269    fprintf(stderr, "  'command_line_args' : [");
2270    for (int i = 0; i != num_command_line_args; ++i) {
2271      if (i)
2272        fprintf(stderr, ", ");
2273      fprintf(stderr, "'%s'", command_line_args[i]);
2274    }
2275    fprintf(stderr, "],\n");
2276    fprintf(stderr, "  'unsaved_files' : [");
2277    for (unsigned i = 0; i != num_unsaved_files; ++i) {
2278      if (i)
2279        fprintf(stderr, ", ");
2280      fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
2281              unsaved_files[i].Length);
2282    }
2283    fprintf(stderr, "],\n");
2284    fprintf(stderr, "  'options' : %d,\n", options);
2285    fprintf(stderr, "}\n");
2286
2287    return 0;
2288  }
2289
2290  return PTUI.result;
2291}
2292
2293unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
2294  return CXSaveTranslationUnit_None;
2295}
2296
2297int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
2298                              unsigned options) {
2299  if (!TU)
2300    return 1;
2301
2302  return static_cast<ASTUnit *>(TU->TUData)->Save(FileName);
2303}
2304
2305void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
2306  if (CTUnit) {
2307    // If the translation unit has been marked as unsafe to free, just discard
2308    // it.
2309    if (static_cast<ASTUnit *>(CTUnit->TUData)->isUnsafeToFree())
2310      return;
2311
2312    delete static_cast<ASTUnit *>(CTUnit->TUData);
2313    disposeCXStringPool(CTUnit->StringPool);
2314    delete CTUnit;
2315  }
2316}
2317
2318unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
2319  return CXReparse_None;
2320}
2321
2322struct ReparseTranslationUnitInfo {
2323  CXTranslationUnit TU;
2324  unsigned num_unsaved_files;
2325  struct CXUnsavedFile *unsaved_files;
2326  unsigned options;
2327  int result;
2328};
2329
2330static void clang_reparseTranslationUnit_Impl(void *UserData) {
2331  ReparseTranslationUnitInfo *RTUI =
2332    static_cast<ReparseTranslationUnitInfo*>(UserData);
2333  CXTranslationUnit TU = RTUI->TU;
2334  unsigned num_unsaved_files = RTUI->num_unsaved_files;
2335  struct CXUnsavedFile *unsaved_files = RTUI->unsaved_files;
2336  unsigned options = RTUI->options;
2337  (void) options;
2338  RTUI->result = 1;
2339
2340  if (!TU)
2341    return;
2342
2343  ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
2344  ASTUnit::ConcurrencyCheck Check(*CXXUnit);
2345
2346  llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
2347  for (unsigned I = 0; I != num_unsaved_files; ++I) {
2348    llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
2349    const llvm::MemoryBuffer *Buffer
2350      = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
2351    RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
2352                                           Buffer));
2353  }
2354
2355  if (!CXXUnit->Reparse(RemappedFiles.data(), RemappedFiles.size()))
2356    RTUI->result = 0;
2357}
2358
2359int clang_reparseTranslationUnit(CXTranslationUnit TU,
2360                                 unsigned num_unsaved_files,
2361                                 struct CXUnsavedFile *unsaved_files,
2362                                 unsigned options) {
2363  ReparseTranslationUnitInfo RTUI = { TU, num_unsaved_files, unsaved_files,
2364                                      options, 0 };
2365  llvm::CrashRecoveryContext CRC;
2366
2367  if (!RunSafely(CRC, clang_reparseTranslationUnit_Impl, &RTUI)) {
2368    fprintf(stderr, "libclang: crash detected during reparsing\n");
2369    static_cast<ASTUnit *>(TU->TUData)->setUnsafeToFree(true);
2370    return 1;
2371  }
2372
2373
2374  return RTUI.result;
2375}
2376
2377
2378CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
2379  if (!CTUnit)
2380    return createCXString("");
2381
2382  ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit->TUData);
2383  return createCXString(CXXUnit->getOriginalSourceFileName(), true);
2384}
2385
2386CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
2387  CXCursor Result = { CXCursor_TranslationUnit, { 0, 0, TU } };
2388  return Result;
2389}
2390
2391} // end: extern "C"
2392
2393//===----------------------------------------------------------------------===//
2394// CXSourceLocation and CXSourceRange Operations.
2395//===----------------------------------------------------------------------===//
2396
2397extern "C" {
2398CXSourceLocation clang_getNullLocation() {
2399  CXSourceLocation Result = { { 0, 0 }, 0 };
2400  return Result;
2401}
2402
2403unsigned clang_equalLocations(CXSourceLocation loc1, CXSourceLocation loc2) {
2404  return (loc1.ptr_data[0] == loc2.ptr_data[0] &&
2405          loc1.ptr_data[1] == loc2.ptr_data[1] &&
2406          loc1.int_data == loc2.int_data);
2407}
2408
2409CXSourceLocation clang_getLocation(CXTranslationUnit tu,
2410                                   CXFile file,
2411                                   unsigned line,
2412                                   unsigned column) {
2413  if (!tu || !file)
2414    return clang_getNullLocation();
2415
2416  ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
2417  SourceLocation SLoc
2418    = CXXUnit->getSourceManager().getLocation(
2419                                        static_cast<const FileEntry *>(file),
2420                                              line, column);
2421  if (SLoc.isInvalid()) return clang_getNullLocation();
2422
2423  return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
2424}
2425
2426CXSourceLocation clang_getLocationForOffset(CXTranslationUnit tu,
2427                                            CXFile file,
2428                                            unsigned offset) {
2429  if (!tu || !file)
2430    return clang_getNullLocation();
2431
2432  ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
2433  SourceLocation Start
2434    = CXXUnit->getSourceManager().getLocation(
2435                                        static_cast<const FileEntry *>(file),
2436                                              1, 1);
2437  if (Start.isInvalid()) return clang_getNullLocation();
2438
2439  SourceLocation SLoc = Start.getFileLocWithOffset(offset);
2440
2441  if (SLoc.isInvalid()) return clang_getNullLocation();
2442
2443  return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
2444}
2445
2446CXSourceRange clang_getNullRange() {
2447  CXSourceRange Result = { { 0, 0 }, 0, 0 };
2448  return Result;
2449}
2450
2451CXSourceRange clang_getRange(CXSourceLocation begin, CXSourceLocation end) {
2452  if (begin.ptr_data[0] != end.ptr_data[0] ||
2453      begin.ptr_data[1] != end.ptr_data[1])
2454    return clang_getNullRange();
2455
2456  CXSourceRange Result = { { begin.ptr_data[0], begin.ptr_data[1] },
2457                           begin.int_data, end.int_data };
2458  return Result;
2459}
2460
2461void clang_getInstantiationLocation(CXSourceLocation location,
2462                                    CXFile *file,
2463                                    unsigned *line,
2464                                    unsigned *column,
2465                                    unsigned *offset) {
2466  SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2467
2468  if (!location.ptr_data[0] || Loc.isInvalid()) {
2469    if (file)
2470      *file = 0;
2471    if (line)
2472      *line = 0;
2473    if (column)
2474      *column = 0;
2475    if (offset)
2476      *offset = 0;
2477    return;
2478  }
2479
2480  const SourceManager &SM =
2481    *static_cast<const SourceManager*>(location.ptr_data[0]);
2482  SourceLocation InstLoc = SM.getInstantiationLoc(Loc);
2483
2484  if (file)
2485    *file = (void *)SM.getFileEntryForID(SM.getFileID(InstLoc));
2486  if (line)
2487    *line = SM.getInstantiationLineNumber(InstLoc);
2488  if (column)
2489    *column = SM.getInstantiationColumnNumber(InstLoc);
2490  if (offset)
2491    *offset = SM.getDecomposedLoc(InstLoc).second;
2492}
2493
2494void clang_getSpellingLocation(CXSourceLocation location,
2495                               CXFile *file,
2496                               unsigned *line,
2497                               unsigned *column,
2498                               unsigned *offset) {
2499  SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2500
2501  if (!location.ptr_data[0] || Loc.isInvalid()) {
2502    if (file)
2503      *file = 0;
2504    if (line)
2505      *line = 0;
2506    if (column)
2507      *column = 0;
2508    if (offset)
2509      *offset = 0;
2510    return;
2511  }
2512
2513  const SourceManager &SM =
2514    *static_cast<const SourceManager*>(location.ptr_data[0]);
2515  SourceLocation SpellLoc = Loc;
2516  if (SpellLoc.isMacroID()) {
2517    SourceLocation SimpleSpellingLoc = SM.getImmediateSpellingLoc(SpellLoc);
2518    if (SimpleSpellingLoc.isFileID() &&
2519        SM.getFileEntryForID(SM.getDecomposedLoc(SimpleSpellingLoc).first))
2520      SpellLoc = SimpleSpellingLoc;
2521    else
2522      SpellLoc = SM.getInstantiationLoc(SpellLoc);
2523  }
2524
2525  std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(SpellLoc);
2526  FileID FID = LocInfo.first;
2527  unsigned FileOffset = LocInfo.second;
2528
2529  if (file)
2530    *file = (void *)SM.getFileEntryForID(FID);
2531  if (line)
2532    *line = SM.getLineNumber(FID, FileOffset);
2533  if (column)
2534    *column = SM.getColumnNumber(FID, FileOffset);
2535  if (offset)
2536    *offset = FileOffset;
2537}
2538
2539CXSourceLocation clang_getRangeStart(CXSourceRange range) {
2540  CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
2541                              range.begin_int_data };
2542  return Result;
2543}
2544
2545CXSourceLocation clang_getRangeEnd(CXSourceRange range) {
2546  CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
2547                              range.end_int_data };
2548  return Result;
2549}
2550
2551} // end: extern "C"
2552
2553//===----------------------------------------------------------------------===//
2554// CXFile Operations.
2555//===----------------------------------------------------------------------===//
2556
2557extern "C" {
2558CXString clang_getFileName(CXFile SFile) {
2559  if (!SFile)
2560    return createCXString((const char*)NULL);
2561
2562  FileEntry *FEnt = static_cast<FileEntry *>(SFile);
2563  return createCXString(FEnt->getName());
2564}
2565
2566time_t clang_getFileTime(CXFile SFile) {
2567  if (!SFile)
2568    return 0;
2569
2570  FileEntry *FEnt = static_cast<FileEntry *>(SFile);
2571  return FEnt->getModificationTime();
2572}
2573
2574CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
2575  if (!tu)
2576    return 0;
2577
2578  ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
2579
2580  FileManager &FMgr = CXXUnit->getFileManager();
2581  const FileEntry *File = FMgr.getFile(file_name, file_name+strlen(file_name),
2582                                       CXXUnit->getFileSystemOpts());
2583  return const_cast<FileEntry *>(File);
2584}
2585
2586} // end: extern "C"
2587
2588//===----------------------------------------------------------------------===//
2589// CXCursor Operations.
2590//===----------------------------------------------------------------------===//
2591
2592static Decl *getDeclFromExpr(Stmt *E) {
2593  if (CastExpr *CE = dyn_cast<CastExpr>(E))
2594    return getDeclFromExpr(CE->getSubExpr());
2595
2596  if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
2597    return RefExpr->getDecl();
2598  if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2599    return RefExpr->getDecl();
2600  if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
2601    return ME->getMemberDecl();
2602  if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
2603    return RE->getDecl();
2604  if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E))
2605    return PRE->getProperty();
2606
2607  if (CallExpr *CE = dyn_cast<CallExpr>(E))
2608    return getDeclFromExpr(CE->getCallee());
2609  if (CXXConstructExpr *CE = llvm::dyn_cast<CXXConstructExpr>(E))
2610    if (!CE->isElidable())
2611    return CE->getConstructor();
2612  if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
2613    return OME->getMethodDecl();
2614
2615  if (ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
2616    return PE->getProtocol();
2617
2618  return 0;
2619}
2620
2621static SourceLocation getLocationFromExpr(Expr *E) {
2622  if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
2623    return /*FIXME:*/Msg->getLeftLoc();
2624  if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
2625    return DRE->getLocation();
2626  if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2627    return RefExpr->getLocation();
2628  if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
2629    return Member->getMemberLoc();
2630  if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
2631    return Ivar->getLocation();
2632  return E->getLocStart();
2633}
2634
2635extern "C" {
2636
2637unsigned clang_visitChildren(CXCursor parent,
2638                             CXCursorVisitor visitor,
2639                             CXClientData client_data) {
2640  CursorVisitor CursorVis(getCursorTU(parent), visitor, client_data,
2641                          getCursorASTUnit(parent)->getMaxPCHLevel());
2642  return CursorVis.VisitChildren(parent);
2643}
2644
2645#ifndef __has_feature
2646#define __has_feature(x) 0
2647#endif
2648#if __has_feature(blocks)
2649typedef enum CXChildVisitResult
2650     (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent);
2651
2652static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
2653    CXClientData client_data) {
2654  CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
2655  return block(cursor, parent);
2656}
2657#else
2658// If we are compiled with a compiler that doesn't have native blocks support,
2659// define and call the block manually, so the
2660typedef struct _CXChildVisitResult
2661{
2662	void *isa;
2663	int flags;
2664	int reserved;
2665	enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor,
2666                                         CXCursor);
2667} *CXCursorVisitorBlock;
2668
2669static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
2670    CXClientData client_data) {
2671  CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
2672  return block->invoke(block, cursor, parent);
2673}
2674#endif
2675
2676
2677unsigned clang_visitChildrenWithBlock(CXCursor parent,
2678                                      CXCursorVisitorBlock block) {
2679  return clang_visitChildren(parent, visitWithBlock, block);
2680}
2681
2682static CXString getDeclSpelling(Decl *D) {
2683  NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
2684  if (!ND) {
2685    if (ObjCPropertyImplDecl *PropImpl =llvm::dyn_cast<ObjCPropertyImplDecl>(D))
2686      if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
2687        return createCXString(Property->getIdentifier()->getName());
2688
2689    return createCXString("");
2690  }
2691
2692  if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
2693    return createCXString(OMD->getSelector().getAsString());
2694
2695  if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
2696    // No, this isn't the same as the code below. getIdentifier() is non-virtual
2697    // and returns different names. NamedDecl returns the class name and
2698    // ObjCCategoryImplDecl returns the category name.
2699    return createCXString(CIMP->getIdentifier()->getNameStart());
2700
2701  if (isa<UsingDirectiveDecl>(D))
2702    return createCXString("");
2703
2704  llvm::SmallString<1024> S;
2705  llvm::raw_svector_ostream os(S);
2706  ND->printName(os);
2707
2708  return createCXString(os.str());
2709}
2710
2711CXString clang_getCursorSpelling(CXCursor C) {
2712  if (clang_isTranslationUnit(C.kind))
2713    return clang_getTranslationUnitSpelling(
2714                            static_cast<CXTranslationUnit>(C.data[2]));
2715
2716  if (clang_isReference(C.kind)) {
2717    switch (C.kind) {
2718    case CXCursor_ObjCSuperClassRef: {
2719      ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
2720      return createCXString(Super->getIdentifier()->getNameStart());
2721    }
2722    case CXCursor_ObjCClassRef: {
2723      ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
2724      return createCXString(Class->getIdentifier()->getNameStart());
2725    }
2726    case CXCursor_ObjCProtocolRef: {
2727      ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
2728      assert(OID && "getCursorSpelling(): Missing protocol decl");
2729      return createCXString(OID->getIdentifier()->getNameStart());
2730    }
2731    case CXCursor_CXXBaseSpecifier: {
2732      CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
2733      return createCXString(B->getType().getAsString());
2734    }
2735    case CXCursor_TypeRef: {
2736      TypeDecl *Type = getCursorTypeRef(C).first;
2737      assert(Type && "Missing type decl");
2738
2739      return createCXString(getCursorContext(C).getTypeDeclType(Type).
2740                              getAsString());
2741    }
2742    case CXCursor_TemplateRef: {
2743      TemplateDecl *Template = getCursorTemplateRef(C).first;
2744      assert(Template && "Missing template decl");
2745
2746      return createCXString(Template->getNameAsString());
2747    }
2748
2749    case CXCursor_NamespaceRef: {
2750      NamedDecl *NS = getCursorNamespaceRef(C).first;
2751      assert(NS && "Missing namespace decl");
2752
2753      return createCXString(NS->getNameAsString());
2754    }
2755
2756    case CXCursor_MemberRef: {
2757      FieldDecl *Field = getCursorMemberRef(C).first;
2758      assert(Field && "Missing member decl");
2759
2760      return createCXString(Field->getNameAsString());
2761    }
2762
2763    case CXCursor_LabelRef: {
2764      LabelStmt *Label = getCursorLabelRef(C).first;
2765      assert(Label && "Missing label");
2766
2767      return createCXString(Label->getID()->getName());
2768    }
2769
2770    case CXCursor_OverloadedDeclRef: {
2771      OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
2772      if (Decl *D = Storage.dyn_cast<Decl *>()) {
2773        if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
2774          return createCXString(ND->getNameAsString());
2775        return createCXString("");
2776      }
2777      if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
2778        return createCXString(E->getName().getAsString());
2779      OverloadedTemplateStorage *Ovl
2780        = Storage.get<OverloadedTemplateStorage*>();
2781      if (Ovl->size() == 0)
2782        return createCXString("");
2783      return createCXString((*Ovl->begin())->getNameAsString());
2784    }
2785
2786    default:
2787      return createCXString("<not implemented>");
2788    }
2789  }
2790
2791  if (clang_isExpression(C.kind)) {
2792    Decl *D = getDeclFromExpr(getCursorExpr(C));
2793    if (D)
2794      return getDeclSpelling(D);
2795    return createCXString("");
2796  }
2797
2798  if (clang_isStatement(C.kind)) {
2799    Stmt *S = getCursorStmt(C);
2800    if (LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
2801      return createCXString(Label->getID()->getName());
2802
2803    return createCXString("");
2804  }
2805
2806  if (C.kind == CXCursor_MacroInstantiation)
2807    return createCXString(getCursorMacroInstantiation(C)->getName()
2808                                                           ->getNameStart());
2809
2810  if (C.kind == CXCursor_MacroDefinition)
2811    return createCXString(getCursorMacroDefinition(C)->getName()
2812                                                           ->getNameStart());
2813
2814  if (C.kind == CXCursor_InclusionDirective)
2815    return createCXString(getCursorInclusionDirective(C)->getFileName());
2816
2817  if (clang_isDeclaration(C.kind))
2818    return getDeclSpelling(getCursorDecl(C));
2819
2820  return createCXString("");
2821}
2822
2823CXString clang_getCursorDisplayName(CXCursor C) {
2824  if (!clang_isDeclaration(C.kind))
2825    return clang_getCursorSpelling(C);
2826
2827  Decl *D = getCursorDecl(C);
2828  if (!D)
2829    return createCXString("");
2830
2831  PrintingPolicy &Policy = getCursorContext(C).PrintingPolicy;
2832  if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
2833    D = FunTmpl->getTemplatedDecl();
2834
2835  if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
2836    llvm::SmallString<64> Str;
2837    llvm::raw_svector_ostream OS(Str);
2838    OS << Function->getNameAsString();
2839    if (Function->getPrimaryTemplate())
2840      OS << "<>";
2841    OS << "(";
2842    for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
2843      if (I)
2844        OS << ", ";
2845      OS << Function->getParamDecl(I)->getType().getAsString(Policy);
2846    }
2847
2848    if (Function->isVariadic()) {
2849      if (Function->getNumParams())
2850        OS << ", ";
2851      OS << "...";
2852    }
2853    OS << ")";
2854    return createCXString(OS.str());
2855  }
2856
2857  if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
2858    llvm::SmallString<64> Str;
2859    llvm::raw_svector_ostream OS(Str);
2860    OS << ClassTemplate->getNameAsString();
2861    OS << "<";
2862    TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
2863    for (unsigned I = 0, N = Params->size(); I != N; ++I) {
2864      if (I)
2865        OS << ", ";
2866
2867      NamedDecl *Param = Params->getParam(I);
2868      if (Param->getIdentifier()) {
2869        OS << Param->getIdentifier()->getName();
2870        continue;
2871      }
2872
2873      // There is no parameter name, which makes this tricky. Try to come up
2874      // with something useful that isn't too long.
2875      if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
2876        OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
2877      else if (NonTypeTemplateParmDecl *NTTP
2878                                    = dyn_cast<NonTypeTemplateParmDecl>(Param))
2879        OS << NTTP->getType().getAsString(Policy);
2880      else
2881        OS << "template<...> class";
2882    }
2883
2884    OS << ">";
2885    return createCXString(OS.str());
2886  }
2887
2888  if (ClassTemplateSpecializationDecl *ClassSpec
2889                              = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
2890    // If the type was explicitly written, use that.
2891    if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
2892      return createCXString(TSInfo->getType().getAsString(Policy));
2893
2894    llvm::SmallString<64> Str;
2895    llvm::raw_svector_ostream OS(Str);
2896    OS << ClassSpec->getNameAsString();
2897    OS << TemplateSpecializationType::PrintTemplateArgumentList(
2898                                      ClassSpec->getTemplateArgs().data(),
2899                                      ClassSpec->getTemplateArgs().size(),
2900                                                                Policy);
2901    return createCXString(OS.str());
2902  }
2903
2904  return clang_getCursorSpelling(C);
2905}
2906
2907CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
2908  switch (Kind) {
2909  case CXCursor_FunctionDecl:
2910      return createCXString("FunctionDecl");
2911  case CXCursor_TypedefDecl:
2912      return createCXString("TypedefDecl");
2913  case CXCursor_EnumDecl:
2914      return createCXString("EnumDecl");
2915  case CXCursor_EnumConstantDecl:
2916      return createCXString("EnumConstantDecl");
2917  case CXCursor_StructDecl:
2918      return createCXString("StructDecl");
2919  case CXCursor_UnionDecl:
2920      return createCXString("UnionDecl");
2921  case CXCursor_ClassDecl:
2922      return createCXString("ClassDecl");
2923  case CXCursor_FieldDecl:
2924      return createCXString("FieldDecl");
2925  case CXCursor_VarDecl:
2926      return createCXString("VarDecl");
2927  case CXCursor_ParmDecl:
2928      return createCXString("ParmDecl");
2929  case CXCursor_ObjCInterfaceDecl:
2930      return createCXString("ObjCInterfaceDecl");
2931  case CXCursor_ObjCCategoryDecl:
2932      return createCXString("ObjCCategoryDecl");
2933  case CXCursor_ObjCProtocolDecl:
2934      return createCXString("ObjCProtocolDecl");
2935  case CXCursor_ObjCPropertyDecl:
2936      return createCXString("ObjCPropertyDecl");
2937  case CXCursor_ObjCIvarDecl:
2938      return createCXString("ObjCIvarDecl");
2939  case CXCursor_ObjCInstanceMethodDecl:
2940      return createCXString("ObjCInstanceMethodDecl");
2941  case CXCursor_ObjCClassMethodDecl:
2942      return createCXString("ObjCClassMethodDecl");
2943  case CXCursor_ObjCImplementationDecl:
2944      return createCXString("ObjCImplementationDecl");
2945  case CXCursor_ObjCCategoryImplDecl:
2946      return createCXString("ObjCCategoryImplDecl");
2947  case CXCursor_CXXMethod:
2948      return createCXString("CXXMethod");
2949  case CXCursor_UnexposedDecl:
2950      return createCXString("UnexposedDecl");
2951  case CXCursor_ObjCSuperClassRef:
2952      return createCXString("ObjCSuperClassRef");
2953  case CXCursor_ObjCProtocolRef:
2954      return createCXString("ObjCProtocolRef");
2955  case CXCursor_ObjCClassRef:
2956      return createCXString("ObjCClassRef");
2957  case CXCursor_TypeRef:
2958      return createCXString("TypeRef");
2959  case CXCursor_TemplateRef:
2960      return createCXString("TemplateRef");
2961  case CXCursor_NamespaceRef:
2962    return createCXString("NamespaceRef");
2963  case CXCursor_MemberRef:
2964    return createCXString("MemberRef");
2965  case CXCursor_LabelRef:
2966    return createCXString("LabelRef");
2967  case CXCursor_OverloadedDeclRef:
2968    return createCXString("OverloadedDeclRef");
2969  case CXCursor_UnexposedExpr:
2970      return createCXString("UnexposedExpr");
2971  case CXCursor_BlockExpr:
2972      return createCXString("BlockExpr");
2973  case CXCursor_DeclRefExpr:
2974      return createCXString("DeclRefExpr");
2975  case CXCursor_MemberRefExpr:
2976      return createCXString("MemberRefExpr");
2977  case CXCursor_CallExpr:
2978      return createCXString("CallExpr");
2979  case CXCursor_ObjCMessageExpr:
2980      return createCXString("ObjCMessageExpr");
2981  case CXCursor_UnexposedStmt:
2982      return createCXString("UnexposedStmt");
2983  case CXCursor_LabelStmt:
2984      return createCXString("LabelStmt");
2985  case CXCursor_InvalidFile:
2986      return createCXString("InvalidFile");
2987  case CXCursor_InvalidCode:
2988    return createCXString("InvalidCode");
2989  case CXCursor_NoDeclFound:
2990      return createCXString("NoDeclFound");
2991  case CXCursor_NotImplemented:
2992      return createCXString("NotImplemented");
2993  case CXCursor_TranslationUnit:
2994      return createCXString("TranslationUnit");
2995  case CXCursor_UnexposedAttr:
2996      return createCXString("UnexposedAttr");
2997  case CXCursor_IBActionAttr:
2998      return createCXString("attribute(ibaction)");
2999  case CXCursor_IBOutletAttr:
3000     return createCXString("attribute(iboutlet)");
3001  case CXCursor_IBOutletCollectionAttr:
3002      return createCXString("attribute(iboutletcollection)");
3003  case CXCursor_PreprocessingDirective:
3004    return createCXString("preprocessing directive");
3005  case CXCursor_MacroDefinition:
3006    return createCXString("macro definition");
3007  case CXCursor_MacroInstantiation:
3008    return createCXString("macro instantiation");
3009  case CXCursor_InclusionDirective:
3010    return createCXString("inclusion directive");
3011  case CXCursor_Namespace:
3012    return createCXString("Namespace");
3013  case CXCursor_LinkageSpec:
3014    return createCXString("LinkageSpec");
3015  case CXCursor_CXXBaseSpecifier:
3016    return createCXString("C++ base class specifier");
3017  case CXCursor_Constructor:
3018    return createCXString("CXXConstructor");
3019  case CXCursor_Destructor:
3020    return createCXString("CXXDestructor");
3021  case CXCursor_ConversionFunction:
3022    return createCXString("CXXConversion");
3023  case CXCursor_TemplateTypeParameter:
3024    return createCXString("TemplateTypeParameter");
3025  case CXCursor_NonTypeTemplateParameter:
3026    return createCXString("NonTypeTemplateParameter");
3027  case CXCursor_TemplateTemplateParameter:
3028    return createCXString("TemplateTemplateParameter");
3029  case CXCursor_FunctionTemplate:
3030    return createCXString("FunctionTemplate");
3031  case CXCursor_ClassTemplate:
3032    return createCXString("ClassTemplate");
3033  case CXCursor_ClassTemplatePartialSpecialization:
3034    return createCXString("ClassTemplatePartialSpecialization");
3035  case CXCursor_NamespaceAlias:
3036    return createCXString("NamespaceAlias");
3037  case CXCursor_UsingDirective:
3038    return createCXString("UsingDirective");
3039  case CXCursor_UsingDeclaration:
3040    return createCXString("UsingDeclaration");
3041  }
3042
3043  llvm_unreachable("Unhandled CXCursorKind");
3044  return createCXString((const char*) 0);
3045}
3046
3047enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
3048                                         CXCursor parent,
3049                                         CXClientData client_data) {
3050  CXCursor *BestCursor = static_cast<CXCursor *>(client_data);
3051
3052  // If our current best cursor is the construction of a temporary object,
3053  // don't replace that cursor with a type reference, because we want
3054  // clang_getCursor() to point at the constructor.
3055  if (clang_isExpression(BestCursor->kind) &&
3056      isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
3057      cursor.kind == CXCursor_TypeRef)
3058    return CXChildVisit_Recurse;
3059
3060  *BestCursor = cursor;
3061  return CXChildVisit_Recurse;
3062}
3063
3064CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
3065  if (!TU)
3066    return clang_getNullCursor();
3067
3068  ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
3069  ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3070
3071  // Translate the given source location to make it point at the beginning of
3072  // the token under the cursor.
3073  SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
3074
3075  // Guard against an invalid SourceLocation, or we may assert in one
3076  // of the following calls.
3077  if (SLoc.isInvalid())
3078    return clang_getNullCursor();
3079
3080  bool Logging = getenv("LIBCLANG_LOGGING");
3081  SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
3082                                    CXXUnit->getASTContext().getLangOptions());
3083
3084  CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
3085  if (SLoc.isValid()) {
3086    // FIXME: Would be great to have a "hint" cursor, then walk from that
3087    // hint cursor upward until we find a cursor whose source range encloses
3088    // the region of interest, rather than starting from the translation unit.
3089    CXCursor Parent = clang_getTranslationUnitCursor(TU);
3090    CursorVisitor CursorVis(TU, GetCursorVisitor, &Result,
3091                            Decl::MaxPCHLevel, SourceLocation(SLoc));
3092    CursorVis.VisitChildren(Parent);
3093  }
3094
3095  if (Logging) {
3096    CXFile SearchFile;
3097    unsigned SearchLine, SearchColumn;
3098    CXFile ResultFile;
3099    unsigned ResultLine, ResultColumn;
3100    CXString SearchFileName, ResultFileName, KindSpelling;
3101    CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
3102
3103    clang_getInstantiationLocation(Loc, &SearchFile, &SearchLine, &SearchColumn,
3104                                   0);
3105    clang_getInstantiationLocation(ResultLoc, &ResultFile, &ResultLine,
3106                                   &ResultColumn, 0);
3107    SearchFileName = clang_getFileName(SearchFile);
3108    ResultFileName = clang_getFileName(ResultFile);
3109    KindSpelling = clang_getCursorKindSpelling(Result.kind);
3110    fprintf(stderr, "clang_getCursor(%s:%d:%d) = %s(%s:%d:%d)\n",
3111            clang_getCString(SearchFileName), SearchLine, SearchColumn,
3112            clang_getCString(KindSpelling),
3113            clang_getCString(ResultFileName), ResultLine, ResultColumn);
3114    clang_disposeString(SearchFileName);
3115    clang_disposeString(ResultFileName);
3116    clang_disposeString(KindSpelling);
3117  }
3118
3119  return Result;
3120}
3121
3122CXCursor clang_getNullCursor(void) {
3123  return MakeCXCursorInvalid(CXCursor_InvalidFile);
3124}
3125
3126unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
3127  return X == Y;
3128}
3129
3130unsigned clang_isInvalid(enum CXCursorKind K) {
3131  return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
3132}
3133
3134unsigned clang_isDeclaration(enum CXCursorKind K) {
3135  return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
3136}
3137
3138unsigned clang_isReference(enum CXCursorKind K) {
3139  return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
3140}
3141
3142unsigned clang_isExpression(enum CXCursorKind K) {
3143  return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
3144}
3145
3146unsigned clang_isStatement(enum CXCursorKind K) {
3147  return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
3148}
3149
3150unsigned clang_isTranslationUnit(enum CXCursorKind K) {
3151  return K == CXCursor_TranslationUnit;
3152}
3153
3154unsigned clang_isPreprocessing(enum CXCursorKind K) {
3155  return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
3156}
3157
3158unsigned clang_isUnexposed(enum CXCursorKind K) {
3159  switch (K) {
3160    case CXCursor_UnexposedDecl:
3161    case CXCursor_UnexposedExpr:
3162    case CXCursor_UnexposedStmt:
3163    case CXCursor_UnexposedAttr:
3164      return true;
3165    default:
3166      return false;
3167  }
3168}
3169
3170CXCursorKind clang_getCursorKind(CXCursor C) {
3171  return C.kind;
3172}
3173
3174CXSourceLocation clang_getCursorLocation(CXCursor C) {
3175  if (clang_isReference(C.kind)) {
3176    switch (C.kind) {
3177    case CXCursor_ObjCSuperClassRef: {
3178      std::pair<ObjCInterfaceDecl *, SourceLocation> P
3179        = getCursorObjCSuperClassRef(C);
3180      return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3181    }
3182
3183    case CXCursor_ObjCProtocolRef: {
3184      std::pair<ObjCProtocolDecl *, SourceLocation> P
3185        = getCursorObjCProtocolRef(C);
3186      return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3187    }
3188
3189    case CXCursor_ObjCClassRef: {
3190      std::pair<ObjCInterfaceDecl *, SourceLocation> P
3191        = getCursorObjCClassRef(C);
3192      return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3193    }
3194
3195    case CXCursor_TypeRef: {
3196      std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
3197      return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3198    }
3199
3200    case CXCursor_TemplateRef: {
3201      std::pair<TemplateDecl *, SourceLocation> P = getCursorTemplateRef(C);
3202      return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3203    }
3204
3205    case CXCursor_NamespaceRef: {
3206      std::pair<NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
3207      return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3208    }
3209
3210    case CXCursor_MemberRef: {
3211      std::pair<FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
3212      return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3213    }
3214
3215    case CXCursor_CXXBaseSpecifier: {
3216      CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
3217      if (!BaseSpec)
3218        return clang_getNullLocation();
3219
3220      if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
3221        return cxloc::translateSourceLocation(getCursorContext(C),
3222                                            TSInfo->getTypeLoc().getBeginLoc());
3223
3224      return cxloc::translateSourceLocation(getCursorContext(C),
3225                                        BaseSpec->getSourceRange().getBegin());
3226    }
3227
3228    case CXCursor_LabelRef: {
3229      std::pair<LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
3230      return cxloc::translateSourceLocation(getCursorContext(C), P.second);
3231    }
3232
3233    case CXCursor_OverloadedDeclRef:
3234      return cxloc::translateSourceLocation(getCursorContext(C),
3235                                          getCursorOverloadedDeclRef(C).second);
3236
3237    default:
3238      // FIXME: Need a way to enumerate all non-reference cases.
3239      llvm_unreachable("Missed a reference kind");
3240    }
3241  }
3242
3243  if (clang_isExpression(C.kind))
3244    return cxloc::translateSourceLocation(getCursorContext(C),
3245                                   getLocationFromExpr(getCursorExpr(C)));
3246
3247  if (clang_isStatement(C.kind))
3248    return cxloc::translateSourceLocation(getCursorContext(C),
3249                                          getCursorStmt(C)->getLocStart());
3250
3251  if (C.kind == CXCursor_PreprocessingDirective) {
3252    SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
3253    return cxloc::translateSourceLocation(getCursorContext(C), L);
3254  }
3255
3256  if (C.kind == CXCursor_MacroInstantiation) {
3257    SourceLocation L
3258      = cxcursor::getCursorMacroInstantiation(C)->getSourceRange().getBegin();
3259    return cxloc::translateSourceLocation(getCursorContext(C), L);
3260  }
3261
3262  if (C.kind == CXCursor_MacroDefinition) {
3263    SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
3264    return cxloc::translateSourceLocation(getCursorContext(C), L);
3265  }
3266
3267  if (C.kind == CXCursor_InclusionDirective) {
3268    SourceLocation L
3269      = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
3270    return cxloc::translateSourceLocation(getCursorContext(C), L);
3271  }
3272
3273  if (C.kind < CXCursor_FirstDecl || C.kind > CXCursor_LastDecl)
3274    return clang_getNullLocation();
3275
3276  Decl *D = getCursorDecl(C);
3277  SourceLocation Loc = D->getLocation();
3278  if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
3279    Loc = Class->getClassLoc();
3280  // FIXME: Multiple variables declared in a single declaration
3281  // currently lack the information needed to correctly determine their
3282  // ranges when accounting for the type-specifier.  We use context
3283  // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3284  // and if so, whether it is the first decl.
3285  if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3286    if (!cxcursor::isFirstInDeclGroup(C))
3287      Loc = VD->getLocation();
3288  }
3289
3290  return cxloc::translateSourceLocation(getCursorContext(C), Loc);
3291}
3292
3293} // end extern "C"
3294
3295static SourceRange getRawCursorExtent(CXCursor C) {
3296  if (clang_isReference(C.kind)) {
3297    switch (C.kind) {
3298    case CXCursor_ObjCSuperClassRef:
3299      return  getCursorObjCSuperClassRef(C).second;
3300
3301    case CXCursor_ObjCProtocolRef:
3302      return getCursorObjCProtocolRef(C).second;
3303
3304    case CXCursor_ObjCClassRef:
3305      return getCursorObjCClassRef(C).second;
3306
3307    case CXCursor_TypeRef:
3308      return getCursorTypeRef(C).second;
3309
3310    case CXCursor_TemplateRef:
3311      return getCursorTemplateRef(C).second;
3312
3313    case CXCursor_NamespaceRef:
3314      return getCursorNamespaceRef(C).second;
3315
3316    case CXCursor_MemberRef:
3317      return getCursorMemberRef(C).second;
3318
3319    case CXCursor_CXXBaseSpecifier:
3320      return getCursorCXXBaseSpecifier(C)->getSourceRange();
3321
3322    case CXCursor_LabelRef:
3323      return getCursorLabelRef(C).second;
3324
3325    case CXCursor_OverloadedDeclRef:
3326      return getCursorOverloadedDeclRef(C).second;
3327
3328    default:
3329      // FIXME: Need a way to enumerate all non-reference cases.
3330      llvm_unreachable("Missed a reference kind");
3331    }
3332  }
3333
3334  if (clang_isExpression(C.kind))
3335    return getCursorExpr(C)->getSourceRange();
3336
3337  if (clang_isStatement(C.kind))
3338    return getCursorStmt(C)->getSourceRange();
3339
3340  if (C.kind == CXCursor_PreprocessingDirective)
3341    return cxcursor::getCursorPreprocessingDirective(C);
3342
3343  if (C.kind == CXCursor_MacroInstantiation)
3344    return cxcursor::getCursorMacroInstantiation(C)->getSourceRange();
3345
3346  if (C.kind == CXCursor_MacroDefinition)
3347    return cxcursor::getCursorMacroDefinition(C)->getSourceRange();
3348
3349  if (C.kind == CXCursor_InclusionDirective)
3350    return cxcursor::getCursorInclusionDirective(C)->getSourceRange();
3351
3352  if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
3353    Decl *D = cxcursor::getCursorDecl(C);
3354    SourceRange R = D->getSourceRange();
3355    // FIXME: Multiple variables declared in a single declaration
3356    // currently lack the information needed to correctly determine their
3357    // ranges when accounting for the type-specifier.  We use context
3358    // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3359    // and if so, whether it is the first decl.
3360    if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3361      if (!cxcursor::isFirstInDeclGroup(C))
3362        R.setBegin(VD->getLocation());
3363    }
3364    return R;
3365  }
3366  return SourceRange();}
3367
3368extern "C" {
3369
3370CXSourceRange clang_getCursorExtent(CXCursor C) {
3371  SourceRange R = getRawCursorExtent(C);
3372  if (R.isInvalid())
3373    return clang_getNullRange();
3374
3375  return cxloc::translateSourceRange(getCursorContext(C), R);
3376}
3377
3378CXCursor clang_getCursorReferenced(CXCursor C) {
3379  if (clang_isInvalid(C.kind))
3380    return clang_getNullCursor();
3381
3382  CXTranslationUnit tu = getCursorTU(C);
3383  if (clang_isDeclaration(C.kind)) {
3384    Decl *D = getCursorDecl(C);
3385    if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
3386      return MakeCursorOverloadedDeclRef(Using, D->getLocation(), tu);
3387    if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
3388      return MakeCursorOverloadedDeclRef(Classes, D->getLocation(), tu);
3389    if (ObjCForwardProtocolDecl *Protocols
3390                                        = dyn_cast<ObjCForwardProtocolDecl>(D))
3391      return MakeCursorOverloadedDeclRef(Protocols, D->getLocation(), tu);
3392    if (ObjCPropertyImplDecl *PropImpl =llvm::dyn_cast<ObjCPropertyImplDecl>(D))
3393      if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
3394        return MakeCXCursor(Property, tu);
3395
3396    return C;
3397  }
3398
3399  if (clang_isExpression(C.kind)) {
3400    Expr *E = getCursorExpr(C);
3401    Decl *D = getDeclFromExpr(E);
3402    if (D)
3403      return MakeCXCursor(D, tu);
3404
3405    if (OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
3406      return MakeCursorOverloadedDeclRef(Ovl, tu);
3407
3408    return clang_getNullCursor();
3409  }
3410
3411  if (clang_isStatement(C.kind)) {
3412    Stmt *S = getCursorStmt(C);
3413    if (GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
3414      return MakeCXCursor(Goto->getLabel(), getCursorDecl(C), tu);
3415
3416    return clang_getNullCursor();
3417  }
3418
3419  if (C.kind == CXCursor_MacroInstantiation) {
3420    if (MacroDefinition *Def = getCursorMacroInstantiation(C)->getDefinition())
3421      return MakeMacroDefinitionCursor(Def, tu);
3422  }
3423
3424  if (!clang_isReference(C.kind))
3425    return clang_getNullCursor();
3426
3427  switch (C.kind) {
3428    case CXCursor_ObjCSuperClassRef:
3429      return MakeCXCursor(getCursorObjCSuperClassRef(C).first, tu);
3430
3431    case CXCursor_ObjCProtocolRef: {
3432      return MakeCXCursor(getCursorObjCProtocolRef(C).first, tu);
3433
3434    case CXCursor_ObjCClassRef:
3435      return MakeCXCursor(getCursorObjCClassRef(C).first, tu );
3436
3437    case CXCursor_TypeRef:
3438      return MakeCXCursor(getCursorTypeRef(C).first, tu );
3439
3440    case CXCursor_TemplateRef:
3441      return MakeCXCursor(getCursorTemplateRef(C).first, tu );
3442
3443    case CXCursor_NamespaceRef:
3444      return MakeCXCursor(getCursorNamespaceRef(C).first, tu );
3445
3446    case CXCursor_MemberRef:
3447      return MakeCXCursor(getCursorMemberRef(C).first, tu );
3448
3449    case CXCursor_CXXBaseSpecifier: {
3450      CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
3451      return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
3452                                                         tu ));
3453    }
3454
3455    case CXCursor_LabelRef:
3456      // FIXME: We end up faking the "parent" declaration here because we
3457      // don't want to make CXCursor larger.
3458      return MakeCXCursor(getCursorLabelRef(C).first,
3459               static_cast<ASTUnit*>(tu->TUData)->getASTContext()
3460                          .getTranslationUnitDecl(),
3461                          tu);
3462
3463    case CXCursor_OverloadedDeclRef:
3464      return C;
3465
3466    default:
3467      // We would prefer to enumerate all non-reference cursor kinds here.
3468      llvm_unreachable("Unhandled reference cursor kind");
3469      break;
3470    }
3471  }
3472
3473  return clang_getNullCursor();
3474}
3475
3476CXCursor clang_getCursorDefinition(CXCursor C) {
3477  if (clang_isInvalid(C.kind))
3478    return clang_getNullCursor();
3479
3480  CXTranslationUnit TU = getCursorTU(C);
3481
3482  bool WasReference = false;
3483  if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
3484    C = clang_getCursorReferenced(C);
3485    WasReference = true;
3486  }
3487
3488  if (C.kind == CXCursor_MacroInstantiation)
3489    return clang_getCursorReferenced(C);
3490
3491  if (!clang_isDeclaration(C.kind))
3492    return clang_getNullCursor();
3493
3494  Decl *D = getCursorDecl(C);
3495  if (!D)
3496    return clang_getNullCursor();
3497
3498  switch (D->getKind()) {
3499  // Declaration kinds that don't really separate the notions of
3500  // declaration and definition.
3501  case Decl::Namespace:
3502  case Decl::Typedef:
3503  case Decl::TemplateTypeParm:
3504  case Decl::EnumConstant:
3505  case Decl::Field:
3506  case Decl::ObjCIvar:
3507  case Decl::ObjCAtDefsField:
3508  case Decl::ImplicitParam:
3509  case Decl::ParmVar:
3510  case Decl::NonTypeTemplateParm:
3511  case Decl::TemplateTemplateParm:
3512  case Decl::ObjCCategoryImpl:
3513  case Decl::ObjCImplementation:
3514  case Decl::AccessSpec:
3515  case Decl::LinkageSpec:
3516  case Decl::ObjCPropertyImpl:
3517  case Decl::FileScopeAsm:
3518  case Decl::StaticAssert:
3519  case Decl::Block:
3520    return C;
3521
3522  // Declaration kinds that don't make any sense here, but are
3523  // nonetheless harmless.
3524  case Decl::TranslationUnit:
3525    break;
3526
3527  // Declaration kinds for which the definition is not resolvable.
3528  case Decl::UnresolvedUsingTypename:
3529  case Decl::UnresolvedUsingValue:
3530    break;
3531
3532  case Decl::UsingDirective:
3533    return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
3534                        TU);
3535
3536  case Decl::NamespaceAlias:
3537    return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), TU);
3538
3539  case Decl::Enum:
3540  case Decl::Record:
3541  case Decl::CXXRecord:
3542  case Decl::ClassTemplateSpecialization:
3543  case Decl::ClassTemplatePartialSpecialization:
3544    if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
3545      return MakeCXCursor(Def, TU);
3546    return clang_getNullCursor();
3547
3548  case Decl::Function:
3549  case Decl::CXXMethod:
3550  case Decl::CXXConstructor:
3551  case Decl::CXXDestructor:
3552  case Decl::CXXConversion: {
3553    const FunctionDecl *Def = 0;
3554    if (cast<FunctionDecl>(D)->getBody(Def))
3555      return MakeCXCursor(const_cast<FunctionDecl *>(Def), TU);
3556    return clang_getNullCursor();
3557  }
3558
3559  case Decl::Var: {
3560    // Ask the variable if it has a definition.
3561    if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
3562      return MakeCXCursor(Def, TU);
3563    return clang_getNullCursor();
3564  }
3565
3566  case Decl::FunctionTemplate: {
3567    const FunctionDecl *Def = 0;
3568    if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
3569      return MakeCXCursor(Def->getDescribedFunctionTemplate(), TU);
3570    return clang_getNullCursor();
3571  }
3572
3573  case Decl::ClassTemplate: {
3574    if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
3575                                                            ->getDefinition())
3576      return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
3577                          TU);
3578    return clang_getNullCursor();
3579  }
3580
3581  case Decl::Using:
3582    return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
3583                                       D->getLocation(), TU);
3584
3585  case Decl::UsingShadow:
3586    return clang_getCursorDefinition(
3587                       MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
3588                                    TU));
3589
3590  case Decl::ObjCMethod: {
3591    ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
3592    if (Method->isThisDeclarationADefinition())
3593      return C;
3594
3595    // Dig out the method definition in the associated
3596    // @implementation, if we have it.
3597    // FIXME: The ASTs should make finding the definition easier.
3598    if (ObjCInterfaceDecl *Class
3599                       = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
3600      if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
3601        if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
3602                                                  Method->isInstanceMethod()))
3603          if (Def->isThisDeclarationADefinition())
3604            return MakeCXCursor(Def, TU);
3605
3606    return clang_getNullCursor();
3607  }
3608
3609  case Decl::ObjCCategory:
3610    if (ObjCCategoryImplDecl *Impl
3611                               = cast<ObjCCategoryDecl>(D)->getImplementation())
3612      return MakeCXCursor(Impl, TU);
3613    return clang_getNullCursor();
3614
3615  case Decl::ObjCProtocol:
3616    if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
3617      return C;
3618    return clang_getNullCursor();
3619
3620  case Decl::ObjCInterface:
3621    // There are two notions of a "definition" for an Objective-C
3622    // class: the interface and its implementation. When we resolved a
3623    // reference to an Objective-C class, produce the @interface as
3624    // the definition; when we were provided with the interface,
3625    // produce the @implementation as the definition.
3626    if (WasReference) {
3627      if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
3628        return C;
3629    } else if (ObjCImplementationDecl *Impl
3630                              = cast<ObjCInterfaceDecl>(D)->getImplementation())
3631      return MakeCXCursor(Impl, TU);
3632    return clang_getNullCursor();
3633
3634  case Decl::ObjCProperty:
3635    // FIXME: We don't really know where to find the
3636    // ObjCPropertyImplDecls that implement this property.
3637    return clang_getNullCursor();
3638
3639  case Decl::ObjCCompatibleAlias:
3640    if (ObjCInterfaceDecl *Class
3641          = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
3642      if (!Class->isForwardDecl())
3643        return MakeCXCursor(Class, TU);
3644
3645    return clang_getNullCursor();
3646
3647  case Decl::ObjCForwardProtocol:
3648    return MakeCursorOverloadedDeclRef(cast<ObjCForwardProtocolDecl>(D),
3649                                       D->getLocation(), TU);
3650
3651  case Decl::ObjCClass:
3652    return MakeCursorOverloadedDeclRef(cast<ObjCClassDecl>(D), D->getLocation(),
3653                                       TU);
3654
3655  case Decl::Friend:
3656    if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
3657      return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
3658    return clang_getNullCursor();
3659
3660  case Decl::FriendTemplate:
3661    if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
3662      return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
3663    return clang_getNullCursor();
3664  }
3665
3666  return clang_getNullCursor();
3667}
3668
3669unsigned clang_isCursorDefinition(CXCursor C) {
3670  if (!clang_isDeclaration(C.kind))
3671    return 0;
3672
3673  return clang_getCursorDefinition(C) == C;
3674}
3675
3676unsigned clang_getNumOverloadedDecls(CXCursor C) {
3677  if (C.kind != CXCursor_OverloadedDeclRef)
3678    return 0;
3679
3680  OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
3681  if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
3682    return E->getNumDecls();
3683
3684  if (OverloadedTemplateStorage *S
3685                              = Storage.dyn_cast<OverloadedTemplateStorage*>())
3686    return S->size();
3687
3688  Decl *D = Storage.get<Decl*>();
3689  if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
3690    return Using->shadow_size();
3691  if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
3692    return Classes->size();
3693  if (ObjCForwardProtocolDecl *Protocols =dyn_cast<ObjCForwardProtocolDecl>(D))
3694    return Protocols->protocol_size();
3695
3696  return 0;
3697}
3698
3699CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
3700  if (cursor.kind != CXCursor_OverloadedDeclRef)
3701    return clang_getNullCursor();
3702
3703  if (index >= clang_getNumOverloadedDecls(cursor))
3704    return clang_getNullCursor();
3705
3706  CXTranslationUnit TU = getCursorTU(cursor);
3707  OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
3708  if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
3709    return MakeCXCursor(E->decls_begin()[index], TU);
3710
3711  if (OverloadedTemplateStorage *S
3712                              = Storage.dyn_cast<OverloadedTemplateStorage*>())
3713    return MakeCXCursor(S->begin()[index], TU);
3714
3715  Decl *D = Storage.get<Decl*>();
3716  if (UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
3717    // FIXME: This is, unfortunately, linear time.
3718    UsingDecl::shadow_iterator Pos = Using->shadow_begin();
3719    std::advance(Pos, index);
3720    return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), TU);
3721  }
3722
3723  if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
3724    return MakeCXCursor(Classes->begin()[index].getInterface(), TU);
3725
3726  if (ObjCForwardProtocolDecl *Protocols = dyn_cast<ObjCForwardProtocolDecl>(D))
3727    return MakeCXCursor(Protocols->protocol_begin()[index], TU);
3728
3729  return clang_getNullCursor();
3730}
3731
3732void clang_getDefinitionSpellingAndExtent(CXCursor C,
3733                                          const char **startBuf,
3734                                          const char **endBuf,
3735                                          unsigned *startLine,
3736                                          unsigned *startColumn,
3737                                          unsigned *endLine,
3738                                          unsigned *endColumn) {
3739  assert(getCursorDecl(C) && "CXCursor has null decl");
3740  NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
3741  FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
3742  CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
3743
3744  SourceManager &SM = FD->getASTContext().getSourceManager();
3745  *startBuf = SM.getCharacterData(Body->getLBracLoc());
3746  *endBuf = SM.getCharacterData(Body->getRBracLoc());
3747  *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
3748  *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
3749  *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
3750  *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
3751}
3752
3753void clang_enableStackTraces(void) {
3754  llvm::sys::PrintStackTraceOnErrorSignal();
3755}
3756
3757void clang_executeOnThread(void (*fn)(void*), void *user_data,
3758                           unsigned stack_size) {
3759  llvm::llvm_execute_on_thread(fn, user_data, stack_size);
3760}
3761
3762} // end: extern "C"
3763
3764//===----------------------------------------------------------------------===//
3765// Token-based Operations.
3766//===----------------------------------------------------------------------===//
3767
3768/* CXToken layout:
3769 *   int_data[0]: a CXTokenKind
3770 *   int_data[1]: starting token location
3771 *   int_data[2]: token length
3772 *   int_data[3]: reserved
3773 *   ptr_data: for identifiers and keywords, an IdentifierInfo*.
3774 *   otherwise unused.
3775 */
3776extern "C" {
3777
3778CXTokenKind clang_getTokenKind(CXToken CXTok) {
3779  return static_cast<CXTokenKind>(CXTok.int_data[0]);
3780}
3781
3782CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
3783  switch (clang_getTokenKind(CXTok)) {
3784  case CXToken_Identifier:
3785  case CXToken_Keyword:
3786    // We know we have an IdentifierInfo*, so use that.
3787    return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
3788                            ->getNameStart());
3789
3790  case CXToken_Literal: {
3791    // We have stashed the starting pointer in the ptr_data field. Use it.
3792    const char *Text = static_cast<const char *>(CXTok.ptr_data);
3793    return createCXString(llvm::StringRef(Text, CXTok.int_data[2]));
3794  }
3795
3796  case CXToken_Punctuation:
3797  case CXToken_Comment:
3798    break;
3799  }
3800
3801  // We have to find the starting buffer pointer the hard way, by
3802  // deconstructing the source location.
3803  ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
3804  if (!CXXUnit)
3805    return createCXString("");
3806
3807  SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
3808  std::pair<FileID, unsigned> LocInfo
3809    = CXXUnit->getSourceManager().getDecomposedLoc(Loc);
3810  bool Invalid = false;
3811  llvm::StringRef Buffer
3812    = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
3813  if (Invalid)
3814    return createCXString("");
3815
3816  return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
3817}
3818
3819CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
3820  ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
3821  if (!CXXUnit)
3822    return clang_getNullLocation();
3823
3824  return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
3825                        SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
3826}
3827
3828CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
3829  ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
3830  if (!CXXUnit)
3831    return clang_getNullRange();
3832
3833  return cxloc::translateSourceRange(CXXUnit->getASTContext(),
3834                        SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
3835}
3836
3837void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
3838                    CXToken **Tokens, unsigned *NumTokens) {
3839  if (Tokens)
3840    *Tokens = 0;
3841  if (NumTokens)
3842    *NumTokens = 0;
3843
3844  ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
3845  if (!CXXUnit || !Tokens || !NumTokens)
3846    return;
3847
3848  ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3849
3850  SourceRange R = cxloc::translateCXSourceRange(Range);
3851  if (R.isInvalid())
3852    return;
3853
3854  SourceManager &SourceMgr = CXXUnit->getSourceManager();
3855  std::pair<FileID, unsigned> BeginLocInfo
3856    = SourceMgr.getDecomposedLoc(R.getBegin());
3857  std::pair<FileID, unsigned> EndLocInfo
3858    = SourceMgr.getDecomposedLoc(R.getEnd());
3859
3860  // Cannot tokenize across files.
3861  if (BeginLocInfo.first != EndLocInfo.first)
3862    return;
3863
3864  // Create a lexer
3865  bool Invalid = false;
3866  llvm::StringRef Buffer
3867    = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
3868  if (Invalid)
3869    return;
3870
3871  Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
3872            CXXUnit->getASTContext().getLangOptions(),
3873            Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
3874  Lex.SetCommentRetentionState(true);
3875
3876  // Lex tokens until we hit the end of the range.
3877  const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
3878  llvm::SmallVector<CXToken, 32> CXTokens;
3879  Token Tok;
3880  bool previousWasAt = false;
3881  do {
3882    // Lex the next token
3883    Lex.LexFromRawLexer(Tok);
3884    if (Tok.is(tok::eof))
3885      break;
3886
3887    // Initialize the CXToken.
3888    CXToken CXTok;
3889
3890    //   - Common fields
3891    CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
3892    CXTok.int_data[2] = Tok.getLength();
3893    CXTok.int_data[3] = 0;
3894
3895    //   - Kind-specific fields
3896    if (Tok.isLiteral()) {
3897      CXTok.int_data[0] = CXToken_Literal;
3898      CXTok.ptr_data = (void *)Tok.getLiteralData();
3899    } else if (Tok.is(tok::identifier)) {
3900      // Lookup the identifier to determine whether we have a keyword.
3901      std::pair<FileID, unsigned> LocInfo
3902        = SourceMgr.getDecomposedLoc(Tok.getLocation());
3903      bool Invalid = false;
3904      llvm::StringRef Buf
3905        = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
3906      if (Invalid)
3907        return;
3908
3909      const char *StartPos = Buf.data() + LocInfo.second;
3910      IdentifierInfo *II
3911        = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok, StartPos);
3912
3913      if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
3914        CXTok.int_data[0] = CXToken_Keyword;
3915      }
3916      else {
3917        CXTok.int_data[0] = II->getTokenID() == tok::identifier?
3918                                CXToken_Identifier
3919                              : CXToken_Keyword;
3920      }
3921      CXTok.ptr_data = II;
3922    } else if (Tok.is(tok::comment)) {
3923      CXTok.int_data[0] = CXToken_Comment;
3924      CXTok.ptr_data = 0;
3925    } else {
3926      CXTok.int_data[0] = CXToken_Punctuation;
3927      CXTok.ptr_data = 0;
3928    }
3929    CXTokens.push_back(CXTok);
3930    previousWasAt = Tok.is(tok::at);
3931  } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
3932
3933  if (CXTokens.empty())
3934    return;
3935
3936  *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
3937  memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
3938  *NumTokens = CXTokens.size();
3939}
3940
3941void clang_disposeTokens(CXTranslationUnit TU,
3942                         CXToken *Tokens, unsigned NumTokens) {
3943  free(Tokens);
3944}
3945
3946} // end: extern "C"
3947
3948//===----------------------------------------------------------------------===//
3949// Token annotation APIs.
3950//===----------------------------------------------------------------------===//
3951
3952typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
3953static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
3954                                                     CXCursor parent,
3955                                                     CXClientData client_data);
3956namespace {
3957class AnnotateTokensWorker {
3958  AnnotateTokensData &Annotated;
3959  CXToken *Tokens;
3960  CXCursor *Cursors;
3961  unsigned NumTokens;
3962  unsigned TokIdx;
3963  unsigned PreprocessingTokIdx;
3964  CursorVisitor AnnotateVis;
3965  SourceManager &SrcMgr;
3966
3967  bool MoreTokens() const { return TokIdx < NumTokens; }
3968  unsigned NextToken() const { return TokIdx; }
3969  void AdvanceToken() { ++TokIdx; }
3970  SourceLocation GetTokenLoc(unsigned tokI) {
3971    return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
3972  }
3973
3974public:
3975  AnnotateTokensWorker(AnnotateTokensData &annotated,
3976                       CXToken *tokens, CXCursor *cursors, unsigned numTokens,
3977                       CXTranslationUnit tu, SourceRange RegionOfInterest)
3978    : Annotated(annotated), Tokens(tokens), Cursors(cursors),
3979      NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0),
3980      AnnotateVis(tu,
3981                  AnnotateTokensVisitor, this,
3982                  Decl::MaxPCHLevel, RegionOfInterest),
3983      SrcMgr(static_cast<ASTUnit*>(tu->TUData)->getSourceManager()) {}
3984
3985  void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
3986  enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
3987  void AnnotateTokens(CXCursor parent);
3988  void AnnotateTokens() {
3989    AnnotateTokens(clang_getTranslationUnitCursor(AnnotateVis.getTU()));
3990  }
3991};
3992}
3993
3994void AnnotateTokensWorker::AnnotateTokens(CXCursor parent) {
3995  // Walk the AST within the region of interest, annotating tokens
3996  // along the way.
3997  VisitChildren(parent);
3998
3999  for (unsigned I = 0 ; I < TokIdx ; ++I) {
4000    AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
4001    if (Pos != Annotated.end() &&
4002        (clang_isInvalid(Cursors[I].kind) ||
4003         Pos->second.kind != CXCursor_PreprocessingDirective))
4004      Cursors[I] = Pos->second;
4005  }
4006
4007  // Finish up annotating any tokens left.
4008  if (!MoreTokens())
4009    return;
4010
4011  const CXCursor &C = clang_getNullCursor();
4012  for (unsigned I = TokIdx ; I < NumTokens ; ++I) {
4013    AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
4014    Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second;
4015  }
4016}
4017
4018enum CXChildVisitResult
4019AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
4020  CXSourceLocation Loc = clang_getCursorLocation(cursor);
4021  SourceRange cursorRange = getRawCursorExtent(cursor);
4022  if (cursorRange.isInvalid())
4023    return CXChildVisit_Recurse;
4024
4025  if (clang_isPreprocessing(cursor.kind)) {
4026    // For macro instantiations, just note where the beginning of the macro
4027    // instantiation occurs.
4028    if (cursor.kind == CXCursor_MacroInstantiation) {
4029      Annotated[Loc.int_data] = cursor;
4030      return CXChildVisit_Recurse;
4031    }
4032
4033    // Items in the preprocessing record are kept separate from items in
4034    // declarations, so we keep a separate token index.
4035    unsigned SavedTokIdx = TokIdx;
4036    TokIdx = PreprocessingTokIdx;
4037
4038    // Skip tokens up until we catch up to the beginning of the preprocessing
4039    // entry.
4040    while (MoreTokens()) {
4041      const unsigned I = NextToken();
4042      SourceLocation TokLoc = GetTokenLoc(I);
4043      switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4044      case RangeBefore:
4045        AdvanceToken();
4046        continue;
4047      case RangeAfter:
4048      case RangeOverlap:
4049        break;
4050      }
4051      break;
4052    }
4053
4054    // Look at all of the tokens within this range.
4055    while (MoreTokens()) {
4056      const unsigned I = NextToken();
4057      SourceLocation TokLoc = GetTokenLoc(I);
4058      switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4059      case RangeBefore:
4060        assert(0 && "Infeasible");
4061      case RangeAfter:
4062        break;
4063      case RangeOverlap:
4064        Cursors[I] = cursor;
4065        AdvanceToken();
4066        continue;
4067      }
4068      break;
4069    }
4070
4071    // Save the preprocessing token index; restore the non-preprocessing
4072    // token index.
4073    PreprocessingTokIdx = TokIdx;
4074    TokIdx = SavedTokIdx;
4075    return CXChildVisit_Recurse;
4076  }
4077
4078  if (cursorRange.isInvalid())
4079    return CXChildVisit_Continue;
4080
4081  SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data);
4082
4083  // Adjust the annotated range based specific declarations.
4084  const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
4085  if (cursorK >= CXCursor_FirstDecl && cursorK <= CXCursor_LastDecl) {
4086    Decl *D = cxcursor::getCursorDecl(cursor);
4087    // Don't visit synthesized ObjC methods, since they have no syntatic
4088    // representation in the source.
4089    if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
4090      if (MD->isSynthesized())
4091        return CXChildVisit_Continue;
4092    }
4093    if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
4094      if (TypeSourceInfo *TI = DD->getTypeSourceInfo()) {
4095        TypeLoc TL = TI->getTypeLoc();
4096        SourceLocation TLoc = TL.getSourceRange().getBegin();
4097        if (TLoc.isValid() && L.isValid() &&
4098            SrcMgr.isBeforeInTranslationUnit(TLoc, L))
4099          cursorRange.setBegin(TLoc);
4100      }
4101    }
4102  }
4103
4104  // If the location of the cursor occurs within a macro instantiation, record
4105  // the spelling location of the cursor in our annotation map.  We can then
4106  // paper over the token labelings during a post-processing step to try and
4107  // get cursor mappings for tokens that are the *arguments* of a macro
4108  // instantiation.
4109  if (L.isMacroID()) {
4110    unsigned rawEncoding = SrcMgr.getSpellingLoc(L).getRawEncoding();
4111    // Only invalidate the old annotation if it isn't part of a preprocessing
4112    // directive.  Here we assume that the default construction of CXCursor
4113    // results in CXCursor.kind being an initialized value (i.e., 0).  If
4114    // this isn't the case, we can fix by doing lookup + insertion.
4115
4116    CXCursor &oldC = Annotated[rawEncoding];
4117    if (!clang_isPreprocessing(oldC.kind))
4118      oldC = cursor;
4119  }
4120
4121  const enum CXCursorKind K = clang_getCursorKind(parent);
4122  const CXCursor updateC =
4123    (clang_isInvalid(K) || K == CXCursor_TranslationUnit)
4124     ? clang_getNullCursor() : parent;
4125
4126  while (MoreTokens()) {
4127    const unsigned I = NextToken();
4128    SourceLocation TokLoc = GetTokenLoc(I);
4129    switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4130      case RangeBefore:
4131        Cursors[I] = updateC;
4132        AdvanceToken();
4133        continue;
4134      case RangeAfter:
4135      case RangeOverlap:
4136        break;
4137    }
4138    break;
4139  }
4140
4141  // Visit children to get their cursor information.
4142  const unsigned BeforeChildren = NextToken();
4143  VisitChildren(cursor);
4144  const unsigned AfterChildren = NextToken();
4145
4146  // Adjust 'Last' to the last token within the extent of the cursor.
4147  while (MoreTokens()) {
4148    const unsigned I = NextToken();
4149    SourceLocation TokLoc = GetTokenLoc(I);
4150    switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4151      case RangeBefore:
4152        assert(0 && "Infeasible");
4153      case RangeAfter:
4154        break;
4155      case RangeOverlap:
4156        Cursors[I] = updateC;
4157        AdvanceToken();
4158        continue;
4159    }
4160    break;
4161  }
4162  const unsigned Last = NextToken();
4163
4164  // Scan the tokens that are at the beginning of the cursor, but are not
4165  // capture by the child cursors.
4166
4167  // For AST elements within macros, rely on a post-annotate pass to
4168  // to correctly annotate the tokens with cursors.  Otherwise we can
4169  // get confusing results of having tokens that map to cursors that really
4170  // are expanded by an instantiation.
4171  if (L.isMacroID())
4172    cursor = clang_getNullCursor();
4173
4174  for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
4175    if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
4176      break;
4177
4178    Cursors[I] = cursor;
4179  }
4180  // Scan the tokens that are at the end of the cursor, but are not captured
4181  // but the child cursors.
4182  for (unsigned I = AfterChildren; I != Last; ++I)
4183    Cursors[I] = cursor;
4184
4185  TokIdx = Last;
4186  return CXChildVisit_Continue;
4187}
4188
4189static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
4190                                                     CXCursor parent,
4191                                                     CXClientData client_data) {
4192  return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
4193}
4194
4195// This gets run a separate thread to avoid stack blowout.
4196static void runAnnotateTokensWorker(void *UserData) {
4197  ((AnnotateTokensWorker*)UserData)->AnnotateTokens();
4198}
4199
4200extern "C" {
4201
4202void clang_annotateTokens(CXTranslationUnit TU,
4203                          CXToken *Tokens, unsigned NumTokens,
4204                          CXCursor *Cursors) {
4205
4206  if (NumTokens == 0 || !Tokens || !Cursors)
4207    return;
4208
4209  // Any token we don't specifically annotate will have a NULL cursor.
4210  CXCursor C = clang_getNullCursor();
4211  for (unsigned I = 0; I != NumTokens; ++I)
4212    Cursors[I] = C;
4213
4214  ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
4215  if (!CXXUnit)
4216    return;
4217
4218  ASTUnit::ConcurrencyCheck Check(*CXXUnit);
4219
4220  // Determine the region of interest, which contains all of the tokens.
4221  SourceRange RegionOfInterest;
4222  RegionOfInterest.setBegin(cxloc::translateSourceLocation(
4223                                        clang_getTokenLocation(TU, Tokens[0])));
4224  RegionOfInterest.setEnd(cxloc::translateSourceLocation(
4225                                clang_getTokenLocation(TU,
4226                                                       Tokens[NumTokens - 1])));
4227
4228  // A mapping from the source locations found when re-lexing or traversing the
4229  // region of interest to the corresponding cursors.
4230  AnnotateTokensData Annotated;
4231
4232  // Relex the tokens within the source range to look for preprocessing
4233  // directives.
4234  SourceManager &SourceMgr = CXXUnit->getSourceManager();
4235  std::pair<FileID, unsigned> BeginLocInfo
4236    = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
4237  std::pair<FileID, unsigned> EndLocInfo
4238    = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
4239
4240  llvm::StringRef Buffer;
4241  bool Invalid = false;
4242  if (BeginLocInfo.first == EndLocInfo.first &&
4243      ((Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid)),true) &&
4244      !Invalid) {
4245    Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
4246              CXXUnit->getASTContext().getLangOptions(),
4247              Buffer.begin(), Buffer.data() + BeginLocInfo.second,
4248              Buffer.end());
4249    Lex.SetCommentRetentionState(true);
4250
4251    // Lex tokens in raw mode until we hit the end of the range, to avoid
4252    // entering #includes or expanding macros.
4253    while (true) {
4254      Token Tok;
4255      Lex.LexFromRawLexer(Tok);
4256
4257    reprocess:
4258      if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
4259        // We have found a preprocessing directive. Gobble it up so that we
4260        // don't see it while preprocessing these tokens later, but keep track
4261        // of all of the token locations inside this preprocessing directive so
4262        // that we can annotate them appropriately.
4263        //
4264        // FIXME: Some simple tests here could identify macro definitions and
4265        // #undefs, to provide specific cursor kinds for those.
4266        std::vector<SourceLocation> Locations;
4267        do {
4268          Locations.push_back(Tok.getLocation());
4269          Lex.LexFromRawLexer(Tok);
4270        } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
4271
4272        using namespace cxcursor;
4273        CXCursor Cursor
4274          = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
4275                                                         Locations.back()),
4276                                           TU);
4277        for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
4278          Annotated[Locations[I].getRawEncoding()] = Cursor;
4279        }
4280
4281        if (Tok.isAtStartOfLine())
4282          goto reprocess;
4283
4284        continue;
4285      }
4286
4287      if (Tok.is(tok::eof))
4288        break;
4289    }
4290  }
4291
4292  // Annotate all of the source locations in the region of interest that map to
4293  // a specific cursor.
4294  AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens,
4295                         TU, RegionOfInterest);
4296
4297  // Run the worker within a CrashRecoveryContext.
4298  // FIXME: We use a ridiculous stack size here because the data-recursion
4299  // algorithm uses a large stack frame than the non-data recursive version,
4300  // and AnnotationTokensWorker currently transforms the data-recursion
4301  // algorithm back into a traditional recursion by explicitly calling
4302  // VisitChildren().  We will need to remove this explicit recursive call.
4303  llvm::CrashRecoveryContext CRC;
4304  if (!RunSafely(CRC, runAnnotateTokensWorker, &W,
4305                 GetSafetyThreadStackSize() * 2)) {
4306    fprintf(stderr, "libclang: crash detected while annotating tokens\n");
4307  }
4308}
4309} // end: extern "C"
4310
4311//===----------------------------------------------------------------------===//
4312// Operations for querying linkage of a cursor.
4313//===----------------------------------------------------------------------===//
4314
4315extern "C" {
4316CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
4317  if (!clang_isDeclaration(cursor.kind))
4318    return CXLinkage_Invalid;
4319
4320  Decl *D = cxcursor::getCursorDecl(cursor);
4321  if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
4322    switch (ND->getLinkage()) {
4323      case NoLinkage: return CXLinkage_NoLinkage;
4324      case InternalLinkage: return CXLinkage_Internal;
4325      case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
4326      case ExternalLinkage: return CXLinkage_External;
4327    };
4328
4329  return CXLinkage_Invalid;
4330}
4331} // end: extern "C"
4332
4333//===----------------------------------------------------------------------===//
4334// Operations for querying language of a cursor.
4335//===----------------------------------------------------------------------===//
4336
4337static CXLanguageKind getDeclLanguage(const Decl *D) {
4338  switch (D->getKind()) {
4339    default:
4340      break;
4341    case Decl::ImplicitParam:
4342    case Decl::ObjCAtDefsField:
4343    case Decl::ObjCCategory:
4344    case Decl::ObjCCategoryImpl:
4345    case Decl::ObjCClass:
4346    case Decl::ObjCCompatibleAlias:
4347    case Decl::ObjCForwardProtocol:
4348    case Decl::ObjCImplementation:
4349    case Decl::ObjCInterface:
4350    case Decl::ObjCIvar:
4351    case Decl::ObjCMethod:
4352    case Decl::ObjCProperty:
4353    case Decl::ObjCPropertyImpl:
4354    case Decl::ObjCProtocol:
4355      return CXLanguage_ObjC;
4356    case Decl::CXXConstructor:
4357    case Decl::CXXConversion:
4358    case Decl::CXXDestructor:
4359    case Decl::CXXMethod:
4360    case Decl::CXXRecord:
4361    case Decl::ClassTemplate:
4362    case Decl::ClassTemplatePartialSpecialization:
4363    case Decl::ClassTemplateSpecialization:
4364    case Decl::Friend:
4365    case Decl::FriendTemplate:
4366    case Decl::FunctionTemplate:
4367    case Decl::LinkageSpec:
4368    case Decl::Namespace:
4369    case Decl::NamespaceAlias:
4370    case Decl::NonTypeTemplateParm:
4371    case Decl::StaticAssert:
4372    case Decl::TemplateTemplateParm:
4373    case Decl::TemplateTypeParm:
4374    case Decl::UnresolvedUsingTypename:
4375    case Decl::UnresolvedUsingValue:
4376    case Decl::Using:
4377    case Decl::UsingDirective:
4378    case Decl::UsingShadow:
4379      return CXLanguage_CPlusPlus;
4380  }
4381
4382  return CXLanguage_C;
4383}
4384
4385extern "C" {
4386
4387enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
4388  if (clang_isDeclaration(cursor.kind))
4389    if (Decl *D = cxcursor::getCursorDecl(cursor)) {
4390      if (D->hasAttr<UnavailableAttr>() ||
4391          (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted()))
4392        return CXAvailability_Available;
4393
4394      if (D->hasAttr<DeprecatedAttr>())
4395        return CXAvailability_Deprecated;
4396    }
4397
4398  return CXAvailability_Available;
4399}
4400
4401CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
4402  if (clang_isDeclaration(cursor.kind))
4403    return getDeclLanguage(cxcursor::getCursorDecl(cursor));
4404
4405  return CXLanguage_Invalid;
4406}
4407
4408CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
4409  if (clang_isDeclaration(cursor.kind)) {
4410    if (Decl *D = getCursorDecl(cursor)) {
4411      DeclContext *DC = D->getDeclContext();
4412      return MakeCXCursor(cast<Decl>(DC), getCursorTU(cursor));
4413    }
4414  }
4415
4416  if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
4417    if (Decl *D = getCursorDecl(cursor))
4418      return MakeCXCursor(D, getCursorTU(cursor));
4419  }
4420
4421  return clang_getNullCursor();
4422}
4423
4424CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
4425  if (clang_isDeclaration(cursor.kind)) {
4426    if (Decl *D = getCursorDecl(cursor)) {
4427      DeclContext *DC = D->getLexicalDeclContext();
4428      return MakeCXCursor(cast<Decl>(DC), getCursorTU(cursor));
4429    }
4430  }
4431
4432  // FIXME: Note that we can't easily compute the lexical context of a
4433  // statement or expression, so we return nothing.
4434  return clang_getNullCursor();
4435}
4436
4437static void CollectOverriddenMethods(DeclContext *Ctx,
4438                                     ObjCMethodDecl *Method,
4439                            llvm::SmallVectorImpl<ObjCMethodDecl *> &Methods) {
4440  if (!Ctx)
4441    return;
4442
4443  // If we have a class or category implementation, jump straight to the
4444  // interface.
4445  if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(Ctx))
4446    return CollectOverriddenMethods(Impl->getClassInterface(), Method, Methods);
4447
4448  ObjCContainerDecl *Container = dyn_cast<ObjCContainerDecl>(Ctx);
4449  if (!Container)
4450    return;
4451
4452  // Check whether we have a matching method at this level.
4453  if (ObjCMethodDecl *Overridden = Container->getMethod(Method->getSelector(),
4454                                                    Method->isInstanceMethod()))
4455    if (Method != Overridden) {
4456      // We found an override at this level; there is no need to look
4457      // into other protocols or categories.
4458      Methods.push_back(Overridden);
4459      return;
4460    }
4461
4462  if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
4463    for (ObjCProtocolDecl::protocol_iterator P = Protocol->protocol_begin(),
4464                                          PEnd = Protocol->protocol_end();
4465         P != PEnd; ++P)
4466      CollectOverriddenMethods(*P, Method, Methods);
4467  }
4468
4469  if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Container)) {
4470    for (ObjCCategoryDecl::protocol_iterator P = Category->protocol_begin(),
4471                                          PEnd = Category->protocol_end();
4472         P != PEnd; ++P)
4473      CollectOverriddenMethods(*P, Method, Methods);
4474  }
4475
4476  if (ObjCInterfaceDecl *Interface = dyn_cast<ObjCInterfaceDecl>(Container)) {
4477    for (ObjCInterfaceDecl::protocol_iterator P = Interface->protocol_begin(),
4478                                           PEnd = Interface->protocol_end();
4479         P != PEnd; ++P)
4480      CollectOverriddenMethods(*P, Method, Methods);
4481
4482    for (ObjCCategoryDecl *Category = Interface->getCategoryList();
4483         Category; Category = Category->getNextClassCategory())
4484      CollectOverriddenMethods(Category, Method, Methods);
4485
4486    // We only look into the superclass if we haven't found anything yet.
4487    if (Methods.empty())
4488      if (ObjCInterfaceDecl *Super = Interface->getSuperClass())
4489        return CollectOverriddenMethods(Super, Method, Methods);
4490  }
4491}
4492
4493void clang_getOverriddenCursors(CXCursor cursor,
4494                                CXCursor **overridden,
4495                                unsigned *num_overridden) {
4496  if (overridden)
4497    *overridden = 0;
4498  if (num_overridden)
4499    *num_overridden = 0;
4500  if (!overridden || !num_overridden)
4501    return;
4502
4503  if (!clang_isDeclaration(cursor.kind))
4504    return;
4505
4506  Decl *D = getCursorDecl(cursor);
4507  if (!D)
4508    return;
4509
4510  // Handle C++ member functions.
4511  CXTranslationUnit TU = getCursorTU(cursor);
4512  if (CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
4513    *num_overridden = CXXMethod->size_overridden_methods();
4514    if (!*num_overridden)
4515      return;
4516
4517    *overridden = new CXCursor [*num_overridden];
4518    unsigned I = 0;
4519    for (CXXMethodDecl::method_iterator
4520              M = CXXMethod->begin_overridden_methods(),
4521           MEnd = CXXMethod->end_overridden_methods();
4522         M != MEnd; (void)++M, ++I)
4523      (*overridden)[I] = MakeCXCursor(const_cast<CXXMethodDecl*>(*M), TU);
4524    return;
4525  }
4526
4527  ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
4528  if (!Method)
4529    return;
4530
4531  // Handle Objective-C methods.
4532  llvm::SmallVector<ObjCMethodDecl *, 4> Methods;
4533  CollectOverriddenMethods(Method->getDeclContext(), Method, Methods);
4534
4535  if (Methods.empty())
4536    return;
4537
4538  *num_overridden = Methods.size();
4539  *overridden = new CXCursor [Methods.size()];
4540  for (unsigned I = 0, N = Methods.size(); I != N; ++I)
4541    (*overridden)[I] = MakeCXCursor(Methods[I], TU);
4542}
4543
4544void clang_disposeOverriddenCursors(CXCursor *overridden) {
4545  delete [] overridden;
4546}
4547
4548CXFile clang_getIncludedFile(CXCursor cursor) {
4549  if (cursor.kind != CXCursor_InclusionDirective)
4550    return 0;
4551
4552  InclusionDirective *ID = getCursorInclusionDirective(cursor);
4553  return (void *)ID->getFile();
4554}
4555
4556} // end: extern "C"
4557
4558
4559//===----------------------------------------------------------------------===//
4560// C++ AST instrospection.
4561//===----------------------------------------------------------------------===//
4562
4563extern "C" {
4564unsigned clang_CXXMethod_isStatic(CXCursor C) {
4565  if (!clang_isDeclaration(C.kind))
4566    return 0;
4567
4568  CXXMethodDecl *Method = 0;
4569  Decl *D = cxcursor::getCursorDecl(C);
4570  if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
4571    Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
4572  else
4573    Method = dyn_cast_or_null<CXXMethodDecl>(D);
4574  return (Method && Method->isStatic()) ? 1 : 0;
4575}
4576
4577} // end: extern "C"
4578
4579//===----------------------------------------------------------------------===//
4580// Attribute introspection.
4581//===----------------------------------------------------------------------===//
4582
4583extern "C" {
4584CXType clang_getIBOutletCollectionType(CXCursor C) {
4585  if (C.kind != CXCursor_IBOutletCollectionAttr)
4586    return cxtype::MakeCXType(QualType(), cxcursor::getCursorTU(C));
4587
4588  IBOutletCollectionAttr *A =
4589    cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
4590
4591  return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorTU(C));
4592}
4593} // end: extern "C"
4594
4595//===----------------------------------------------------------------------===//
4596// Misc. utility functions.
4597//===----------------------------------------------------------------------===//
4598
4599/// Default to using an 8 MB stack size on "safety" threads.
4600static unsigned SafetyStackThreadSize = 8 << 20;
4601
4602namespace clang {
4603
4604bool RunSafely(llvm::CrashRecoveryContext &CRC,
4605               void (*Fn)(void*), void *UserData,
4606               unsigned Size) {
4607  if (!Size)
4608    Size = GetSafetyThreadStackSize();
4609  if (Size)
4610    return CRC.RunSafelyOnThread(Fn, UserData, Size);
4611  return CRC.RunSafely(Fn, UserData);
4612}
4613
4614unsigned GetSafetyThreadStackSize() {
4615  return SafetyStackThreadSize;
4616}
4617
4618void SetSafetyThreadStackSize(unsigned Value) {
4619  SafetyStackThreadSize = Value;
4620}
4621
4622}
4623
4624extern "C" {
4625
4626CXString clang_getClangVersion() {
4627  return createCXString(getClangFullVersion());
4628}
4629
4630} // end: extern "C"
4631