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