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