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