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