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