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