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