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