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