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