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