CIndex.cpp revision 430d7a1a621a126a9ffe442ad8987ba02b46dae9
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.getExpansionRange(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 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  SmallVector<VisitorWorkList*, 5> WorkListFreeList;
207  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 (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      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  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 (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  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    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    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
2790unsigned clang_equalRanges(CXSourceRange range1, CXSourceRange range2)
2791{
2792  return range1.ptr_data[0] == range2.ptr_data[0]
2793      && range1.ptr_data[1] == range2.ptr_data[1]
2794      && range1.begin_int_data == range2.begin_int_data
2795      && range1.end_int_data == range2.end_int_data;
2796}
2797} // end: extern "C"
2798
2799static void createNullLocation(CXFile *file, unsigned *line,
2800                               unsigned *column, unsigned *offset) {
2801  if (file)
2802   *file = 0;
2803  if (line)
2804   *line = 0;
2805  if (column)
2806   *column = 0;
2807  if (offset)
2808   *offset = 0;
2809  return;
2810}
2811
2812extern "C" {
2813void clang_getInstantiationLocation(CXSourceLocation location,
2814                                    CXFile *file,
2815                                    unsigned *line,
2816                                    unsigned *column,
2817                                    unsigned *offset) {
2818  SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2819
2820  if (!location.ptr_data[0] || Loc.isInvalid()) {
2821    createNullLocation(file, line, column, offset);
2822    return;
2823  }
2824
2825  const SourceManager &SM =
2826    *static_cast<const SourceManager*>(location.ptr_data[0]);
2827  SourceLocation InstLoc = SM.getExpansionLoc(Loc);
2828
2829  // Check that the FileID is invalid on the expansion location.
2830  // This can manifest in invalid code.
2831  FileID fileID = SM.getFileID(InstLoc);
2832  bool Invalid = false;
2833  const SrcMgr::SLocEntry &sloc = SM.getSLocEntry(fileID, &Invalid);
2834  if (!sloc.isFile() || Invalid) {
2835    createNullLocation(file, line, column, offset);
2836    return;
2837  }
2838
2839  if (file)
2840    *file = (void *)SM.getFileEntryForSLocEntry(sloc);
2841  if (line)
2842    *line = SM.getInstantiationLineNumber(InstLoc);
2843  if (column)
2844    *column = SM.getInstantiationColumnNumber(InstLoc);
2845  if (offset)
2846    *offset = SM.getDecomposedLoc(InstLoc).second;
2847}
2848
2849void clang_getSpellingLocation(CXSourceLocation location,
2850                               CXFile *file,
2851                               unsigned *line,
2852                               unsigned *column,
2853                               unsigned *offset) {
2854  SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2855
2856  if (!location.ptr_data[0] || Loc.isInvalid())
2857    return createNullLocation(file, line, column, offset);
2858
2859  const SourceManager &SM =
2860    *static_cast<const SourceManager*>(location.ptr_data[0]);
2861  SourceLocation SpellLoc = Loc;
2862  if (SpellLoc.isMacroID()) {
2863    SourceLocation SimpleSpellingLoc = SM.getImmediateSpellingLoc(SpellLoc);
2864    if (SimpleSpellingLoc.isFileID() &&
2865        SM.getFileEntryForID(SM.getDecomposedLoc(SimpleSpellingLoc).first))
2866      SpellLoc = SimpleSpellingLoc;
2867    else
2868      SpellLoc = SM.getExpansionLoc(SpellLoc);
2869  }
2870
2871  std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(SpellLoc);
2872  FileID FID = LocInfo.first;
2873  unsigned FileOffset = LocInfo.second;
2874
2875  if (FID.isInvalid())
2876    return createNullLocation(file, line, column, offset);
2877
2878  if (file)
2879    *file = (void *)SM.getFileEntryForID(FID);
2880  if (line)
2881    *line = SM.getLineNumber(FID, FileOffset);
2882  if (column)
2883    *column = SM.getColumnNumber(FID, FileOffset);
2884  if (offset)
2885    *offset = FileOffset;
2886}
2887
2888CXSourceLocation clang_getRangeStart(CXSourceRange range) {
2889  CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
2890                              range.begin_int_data };
2891  return Result;
2892}
2893
2894CXSourceLocation clang_getRangeEnd(CXSourceRange range) {
2895  CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
2896                              range.end_int_data };
2897  return Result;
2898}
2899
2900} // end: extern "C"
2901
2902//===----------------------------------------------------------------------===//
2903// CXFile Operations.
2904//===----------------------------------------------------------------------===//
2905
2906extern "C" {
2907CXString clang_getFileName(CXFile SFile) {
2908  if (!SFile)
2909    return createCXString((const char*)NULL);
2910
2911  FileEntry *FEnt = static_cast<FileEntry *>(SFile);
2912  return createCXString(FEnt->getName());
2913}
2914
2915time_t clang_getFileTime(CXFile SFile) {
2916  if (!SFile)
2917    return 0;
2918
2919  FileEntry *FEnt = static_cast<FileEntry *>(SFile);
2920  return FEnt->getModificationTime();
2921}
2922
2923CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
2924  if (!tu)
2925    return 0;
2926
2927  ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
2928
2929  FileManager &FMgr = CXXUnit->getFileManager();
2930  return const_cast<FileEntry *>(FMgr.getFile(file_name));
2931}
2932
2933unsigned clang_isFileMultipleIncludeGuarded(CXTranslationUnit tu, CXFile file) {
2934  if (!tu || !file)
2935    return 0;
2936
2937  ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
2938  FileEntry *FEnt = static_cast<FileEntry *>(file);
2939  return CXXUnit->getPreprocessor().getHeaderSearchInfo()
2940                                          .isFileMultipleIncludeGuarded(FEnt);
2941}
2942
2943} // end: extern "C"
2944
2945//===----------------------------------------------------------------------===//
2946// CXCursor Operations.
2947//===----------------------------------------------------------------------===//
2948
2949static Decl *getDeclFromExpr(Stmt *E) {
2950  if (CastExpr *CE = dyn_cast<CastExpr>(E))
2951    return getDeclFromExpr(CE->getSubExpr());
2952
2953  if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
2954    return RefExpr->getDecl();
2955  if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2956    return RefExpr->getDecl();
2957  if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
2958    return ME->getMemberDecl();
2959  if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
2960    return RE->getDecl();
2961  if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E))
2962    return PRE->isExplicitProperty() ? PRE->getExplicitProperty() : 0;
2963
2964  if (CallExpr *CE = dyn_cast<CallExpr>(E))
2965    return getDeclFromExpr(CE->getCallee());
2966  if (CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(E))
2967    if (!CE->isElidable())
2968    return CE->getConstructor();
2969  if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
2970    return OME->getMethodDecl();
2971
2972  if (ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
2973    return PE->getProtocol();
2974  if (SubstNonTypeTemplateParmPackExpr *NTTP
2975                              = dyn_cast<SubstNonTypeTemplateParmPackExpr>(E))
2976    return NTTP->getParameterPack();
2977  if (SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
2978    if (isa<NonTypeTemplateParmDecl>(SizeOfPack->getPack()) ||
2979        isa<ParmVarDecl>(SizeOfPack->getPack()))
2980      return SizeOfPack->getPack();
2981
2982  return 0;
2983}
2984
2985static SourceLocation getLocationFromExpr(Expr *E) {
2986  if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
2987    return /*FIXME:*/Msg->getLeftLoc();
2988  if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
2989    return DRE->getLocation();
2990  if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2991    return RefExpr->getLocation();
2992  if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
2993    return Member->getMemberLoc();
2994  if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
2995    return Ivar->getLocation();
2996  if (SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
2997    return SizeOfPack->getPackLoc();
2998
2999  return E->getLocStart();
3000}
3001
3002extern "C" {
3003
3004unsigned clang_visitChildren(CXCursor parent,
3005                             CXCursorVisitor visitor,
3006                             CXClientData client_data) {
3007  CursorVisitor CursorVis(getCursorTU(parent), visitor, client_data,
3008                          getCursorASTUnit(parent)->getMaxPCHLevel(),
3009                          false);
3010  return CursorVis.VisitChildren(parent);
3011}
3012
3013#ifndef __has_feature
3014#define __has_feature(x) 0
3015#endif
3016#if __has_feature(blocks)
3017typedef enum CXChildVisitResult
3018     (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent);
3019
3020static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
3021    CXClientData client_data) {
3022  CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
3023  return block(cursor, parent);
3024}
3025#else
3026// If we are compiled with a compiler that doesn't have native blocks support,
3027// define and call the block manually, so the
3028typedef struct _CXChildVisitResult
3029{
3030	void *isa;
3031	int flags;
3032	int reserved;
3033	enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor,
3034                                         CXCursor);
3035} *CXCursorVisitorBlock;
3036
3037static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
3038    CXClientData client_data) {
3039  CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
3040  return block->invoke(block, cursor, parent);
3041}
3042#endif
3043
3044
3045unsigned clang_visitChildrenWithBlock(CXCursor parent,
3046                                      CXCursorVisitorBlock block) {
3047  return clang_visitChildren(parent, visitWithBlock, block);
3048}
3049
3050static CXString getDeclSpelling(Decl *D) {
3051  NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
3052  if (!ND) {
3053    if (ObjCPropertyImplDecl *PropImpl =dyn_cast<ObjCPropertyImplDecl>(D))
3054      if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
3055        return createCXString(Property->getIdentifier()->getName());
3056
3057    return createCXString("");
3058  }
3059
3060  if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
3061    return createCXString(OMD->getSelector().getAsString());
3062
3063  if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
3064    // No, this isn't the same as the code below. getIdentifier() is non-virtual
3065    // and returns different names. NamedDecl returns the class name and
3066    // ObjCCategoryImplDecl returns the category name.
3067    return createCXString(CIMP->getIdentifier()->getNameStart());
3068
3069  if (isa<UsingDirectiveDecl>(D))
3070    return createCXString("");
3071
3072  llvm::SmallString<1024> S;
3073  llvm::raw_svector_ostream os(S);
3074  ND->printName(os);
3075
3076  return createCXString(os.str());
3077}
3078
3079CXString clang_getCursorSpelling(CXCursor C) {
3080  if (clang_isTranslationUnit(C.kind))
3081    return clang_getTranslationUnitSpelling(
3082                            static_cast<CXTranslationUnit>(C.data[2]));
3083
3084  if (clang_isReference(C.kind)) {
3085    switch (C.kind) {
3086    case CXCursor_ObjCSuperClassRef: {
3087      ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
3088      return createCXString(Super->getIdentifier()->getNameStart());
3089    }
3090    case CXCursor_ObjCClassRef: {
3091      ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
3092      return createCXString(Class->getIdentifier()->getNameStart());
3093    }
3094    case CXCursor_ObjCProtocolRef: {
3095      ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
3096      assert(OID && "getCursorSpelling(): Missing protocol decl");
3097      return createCXString(OID->getIdentifier()->getNameStart());
3098    }
3099    case CXCursor_CXXBaseSpecifier: {
3100      CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
3101      return createCXString(B->getType().getAsString());
3102    }
3103    case CXCursor_TypeRef: {
3104      TypeDecl *Type = getCursorTypeRef(C).first;
3105      assert(Type && "Missing type decl");
3106
3107      return createCXString(getCursorContext(C).getTypeDeclType(Type).
3108                              getAsString());
3109    }
3110    case CXCursor_TemplateRef: {
3111      TemplateDecl *Template = getCursorTemplateRef(C).first;
3112      assert(Template && "Missing template decl");
3113
3114      return createCXString(Template->getNameAsString());
3115    }
3116
3117    case CXCursor_NamespaceRef: {
3118      NamedDecl *NS = getCursorNamespaceRef(C).first;
3119      assert(NS && "Missing namespace decl");
3120
3121      return createCXString(NS->getNameAsString());
3122    }
3123
3124    case CXCursor_MemberRef: {
3125      FieldDecl *Field = getCursorMemberRef(C).first;
3126      assert(Field && "Missing member decl");
3127
3128      return createCXString(Field->getNameAsString());
3129    }
3130
3131    case CXCursor_LabelRef: {
3132      LabelStmt *Label = getCursorLabelRef(C).first;
3133      assert(Label && "Missing label");
3134
3135      return createCXString(Label->getName());
3136    }
3137
3138    case CXCursor_OverloadedDeclRef: {
3139      OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
3140      if (Decl *D = Storage.dyn_cast<Decl *>()) {
3141        if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
3142          return createCXString(ND->getNameAsString());
3143        return createCXString("");
3144      }
3145      if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
3146        return createCXString(E->getName().getAsString());
3147      OverloadedTemplateStorage *Ovl
3148        = Storage.get<OverloadedTemplateStorage*>();
3149      if (Ovl->size() == 0)
3150        return createCXString("");
3151      return createCXString((*Ovl->begin())->getNameAsString());
3152    }
3153
3154    default:
3155      return createCXString("<not implemented>");
3156    }
3157  }
3158
3159  if (clang_isExpression(C.kind)) {
3160    Decl *D = getDeclFromExpr(getCursorExpr(C));
3161    if (D)
3162      return getDeclSpelling(D);
3163    return createCXString("");
3164  }
3165
3166  if (clang_isStatement(C.kind)) {
3167    Stmt *S = getCursorStmt(C);
3168    if (LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
3169      return createCXString(Label->getName());
3170
3171    return createCXString("");
3172  }
3173
3174  if (C.kind == CXCursor_MacroExpansion)
3175    return createCXString(getCursorMacroExpansion(C)->getName()
3176                                                           ->getNameStart());
3177
3178  if (C.kind == CXCursor_MacroDefinition)
3179    return createCXString(getCursorMacroDefinition(C)->getName()
3180                                                           ->getNameStart());
3181
3182  if (C.kind == CXCursor_InclusionDirective)
3183    return createCXString(getCursorInclusionDirective(C)->getFileName());
3184
3185  if (clang_isDeclaration(C.kind))
3186    return getDeclSpelling(getCursorDecl(C));
3187
3188  return createCXString("");
3189}
3190
3191CXString clang_getCursorDisplayName(CXCursor C) {
3192  if (!clang_isDeclaration(C.kind))
3193    return clang_getCursorSpelling(C);
3194
3195  Decl *D = getCursorDecl(C);
3196  if (!D)
3197    return createCXString("");
3198
3199  PrintingPolicy &Policy = getCursorContext(C).PrintingPolicy;
3200  if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
3201    D = FunTmpl->getTemplatedDecl();
3202
3203  if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
3204    llvm::SmallString<64> Str;
3205    llvm::raw_svector_ostream OS(Str);
3206    OS << Function->getNameAsString();
3207    if (Function->getPrimaryTemplate())
3208      OS << "<>";
3209    OS << "(";
3210    for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
3211      if (I)
3212        OS << ", ";
3213      OS << Function->getParamDecl(I)->getType().getAsString(Policy);
3214    }
3215
3216    if (Function->isVariadic()) {
3217      if (Function->getNumParams())
3218        OS << ", ";
3219      OS << "...";
3220    }
3221    OS << ")";
3222    return createCXString(OS.str());
3223  }
3224
3225  if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
3226    llvm::SmallString<64> Str;
3227    llvm::raw_svector_ostream OS(Str);
3228    OS << ClassTemplate->getNameAsString();
3229    OS << "<";
3230    TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
3231    for (unsigned I = 0, N = Params->size(); I != N; ++I) {
3232      if (I)
3233        OS << ", ";
3234
3235      NamedDecl *Param = Params->getParam(I);
3236      if (Param->getIdentifier()) {
3237        OS << Param->getIdentifier()->getName();
3238        continue;
3239      }
3240
3241      // There is no parameter name, which makes this tricky. Try to come up
3242      // with something useful that isn't too long.
3243      if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
3244        OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
3245      else if (NonTypeTemplateParmDecl *NTTP
3246                                    = dyn_cast<NonTypeTemplateParmDecl>(Param))
3247        OS << NTTP->getType().getAsString(Policy);
3248      else
3249        OS << "template<...> class";
3250    }
3251
3252    OS << ">";
3253    return createCXString(OS.str());
3254  }
3255
3256  if (ClassTemplateSpecializationDecl *ClassSpec
3257                              = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
3258    // If the type was explicitly written, use that.
3259    if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
3260      return createCXString(TSInfo->getType().getAsString(Policy));
3261
3262    llvm::SmallString<64> Str;
3263    llvm::raw_svector_ostream OS(Str);
3264    OS << ClassSpec->getNameAsString();
3265    OS << TemplateSpecializationType::PrintTemplateArgumentList(
3266                                      ClassSpec->getTemplateArgs().data(),
3267                                      ClassSpec->getTemplateArgs().size(),
3268                                                                Policy);
3269    return createCXString(OS.str());
3270  }
3271
3272  return clang_getCursorSpelling(C);
3273}
3274
3275CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
3276  switch (Kind) {
3277  case CXCursor_FunctionDecl:
3278      return createCXString("FunctionDecl");
3279  case CXCursor_TypedefDecl:
3280      return createCXString("TypedefDecl");
3281  case CXCursor_EnumDecl:
3282      return createCXString("EnumDecl");
3283  case CXCursor_EnumConstantDecl:
3284      return createCXString("EnumConstantDecl");
3285  case CXCursor_StructDecl:
3286      return createCXString("StructDecl");
3287  case CXCursor_UnionDecl:
3288      return createCXString("UnionDecl");
3289  case CXCursor_ClassDecl:
3290      return createCXString("ClassDecl");
3291  case CXCursor_FieldDecl:
3292      return createCXString("FieldDecl");
3293  case CXCursor_VarDecl:
3294      return createCXString("VarDecl");
3295  case CXCursor_ParmDecl:
3296      return createCXString("ParmDecl");
3297  case CXCursor_ObjCInterfaceDecl:
3298      return createCXString("ObjCInterfaceDecl");
3299  case CXCursor_ObjCCategoryDecl:
3300      return createCXString("ObjCCategoryDecl");
3301  case CXCursor_ObjCProtocolDecl:
3302      return createCXString("ObjCProtocolDecl");
3303  case CXCursor_ObjCPropertyDecl:
3304      return createCXString("ObjCPropertyDecl");
3305  case CXCursor_ObjCIvarDecl:
3306      return createCXString("ObjCIvarDecl");
3307  case CXCursor_ObjCInstanceMethodDecl:
3308      return createCXString("ObjCInstanceMethodDecl");
3309  case CXCursor_ObjCClassMethodDecl:
3310      return createCXString("ObjCClassMethodDecl");
3311  case CXCursor_ObjCImplementationDecl:
3312      return createCXString("ObjCImplementationDecl");
3313  case CXCursor_ObjCCategoryImplDecl:
3314      return createCXString("ObjCCategoryImplDecl");
3315  case CXCursor_CXXMethod:
3316      return createCXString("CXXMethod");
3317  case CXCursor_UnexposedDecl:
3318      return createCXString("UnexposedDecl");
3319  case CXCursor_ObjCSuperClassRef:
3320      return createCXString("ObjCSuperClassRef");
3321  case CXCursor_ObjCProtocolRef:
3322      return createCXString("ObjCProtocolRef");
3323  case CXCursor_ObjCClassRef:
3324      return createCXString("ObjCClassRef");
3325  case CXCursor_TypeRef:
3326      return createCXString("TypeRef");
3327  case CXCursor_TemplateRef:
3328      return createCXString("TemplateRef");
3329  case CXCursor_NamespaceRef:
3330    return createCXString("NamespaceRef");
3331  case CXCursor_MemberRef:
3332    return createCXString("MemberRef");
3333  case CXCursor_LabelRef:
3334    return createCXString("LabelRef");
3335  case CXCursor_OverloadedDeclRef:
3336    return createCXString("OverloadedDeclRef");
3337  case CXCursor_UnexposedExpr:
3338      return createCXString("UnexposedExpr");
3339  case CXCursor_BlockExpr:
3340      return createCXString("BlockExpr");
3341  case CXCursor_DeclRefExpr:
3342      return createCXString("DeclRefExpr");
3343  case CXCursor_MemberRefExpr:
3344      return createCXString("MemberRefExpr");
3345  case CXCursor_CallExpr:
3346      return createCXString("CallExpr");
3347  case CXCursor_ObjCMessageExpr:
3348      return createCXString("ObjCMessageExpr");
3349  case CXCursor_UnexposedStmt:
3350      return createCXString("UnexposedStmt");
3351  case CXCursor_LabelStmt:
3352      return createCXString("LabelStmt");
3353  case CXCursor_InvalidFile:
3354      return createCXString("InvalidFile");
3355  case CXCursor_InvalidCode:
3356    return createCXString("InvalidCode");
3357  case CXCursor_NoDeclFound:
3358      return createCXString("NoDeclFound");
3359  case CXCursor_NotImplemented:
3360      return createCXString("NotImplemented");
3361  case CXCursor_TranslationUnit:
3362      return createCXString("TranslationUnit");
3363  case CXCursor_UnexposedAttr:
3364      return createCXString("UnexposedAttr");
3365  case CXCursor_IBActionAttr:
3366      return createCXString("attribute(ibaction)");
3367  case CXCursor_IBOutletAttr:
3368     return createCXString("attribute(iboutlet)");
3369  case CXCursor_IBOutletCollectionAttr:
3370      return createCXString("attribute(iboutletcollection)");
3371  case CXCursor_PreprocessingDirective:
3372    return createCXString("preprocessing directive");
3373  case CXCursor_MacroDefinition:
3374    return createCXString("macro definition");
3375  case CXCursor_MacroExpansion:
3376    return createCXString("macro expansion");
3377  case CXCursor_InclusionDirective:
3378    return createCXString("inclusion directive");
3379  case CXCursor_Namespace:
3380    return createCXString("Namespace");
3381  case CXCursor_LinkageSpec:
3382    return createCXString("LinkageSpec");
3383  case CXCursor_CXXBaseSpecifier:
3384    return createCXString("C++ base class specifier");
3385  case CXCursor_Constructor:
3386    return createCXString("CXXConstructor");
3387  case CXCursor_Destructor:
3388    return createCXString("CXXDestructor");
3389  case CXCursor_ConversionFunction:
3390    return createCXString("CXXConversion");
3391  case CXCursor_TemplateTypeParameter:
3392    return createCXString("TemplateTypeParameter");
3393  case CXCursor_NonTypeTemplateParameter:
3394    return createCXString("NonTypeTemplateParameter");
3395  case CXCursor_TemplateTemplateParameter:
3396    return createCXString("TemplateTemplateParameter");
3397  case CXCursor_FunctionTemplate:
3398    return createCXString("FunctionTemplate");
3399  case CXCursor_ClassTemplate:
3400    return createCXString("ClassTemplate");
3401  case CXCursor_ClassTemplatePartialSpecialization:
3402    return createCXString("ClassTemplatePartialSpecialization");
3403  case CXCursor_NamespaceAlias:
3404    return createCXString("NamespaceAlias");
3405  case CXCursor_UsingDirective:
3406    return createCXString("UsingDirective");
3407  case CXCursor_UsingDeclaration:
3408    return createCXString("UsingDeclaration");
3409  case CXCursor_TypeAliasDecl:
3410    return createCXString("TypeAliasDecl");
3411  case CXCursor_ObjCSynthesizeDecl:
3412    return createCXString("ObjCSynthesizeDecl");
3413  case CXCursor_ObjCDynamicDecl:
3414    return createCXString("ObjCDynamicDecl");
3415  }
3416
3417  llvm_unreachable("Unhandled CXCursorKind");
3418  return createCXString((const char*) 0);
3419}
3420
3421struct GetCursorData {
3422  SourceLocation TokenBeginLoc;
3423  CXCursor &BestCursor;
3424
3425  GetCursorData(SourceLocation tokenBegin, CXCursor &outputCursor)
3426    : TokenBeginLoc(tokenBegin), BestCursor(outputCursor) { }
3427};
3428
3429enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
3430                                         CXCursor parent,
3431                                         CXClientData client_data) {
3432  GetCursorData *Data = static_cast<GetCursorData *>(client_data);
3433  CXCursor *BestCursor = &Data->BestCursor;
3434
3435  if (clang_isExpression(cursor.kind) &&
3436      clang_isDeclaration(BestCursor->kind)) {
3437    Decl *D = getCursorDecl(*BestCursor);
3438
3439    // Avoid having the cursor of an expression replace the declaration cursor
3440    // when the expression source range overlaps the declaration range.
3441    // This can happen for C++ constructor expressions whose range generally
3442    // include the variable declaration, e.g.:
3443    //  MyCXXClass foo; // Make sure pointing at 'foo' returns a VarDecl cursor.
3444    if (D->getLocation().isValid() && Data->TokenBeginLoc.isValid() &&
3445        D->getLocation() == Data->TokenBeginLoc)
3446      return CXChildVisit_Break;
3447  }
3448
3449  // If our current best cursor is the construction of a temporary object,
3450  // don't replace that cursor with a type reference, because we want
3451  // clang_getCursor() to point at the constructor.
3452  if (clang_isExpression(BestCursor->kind) &&
3453      isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
3454      cursor.kind == CXCursor_TypeRef)
3455    return CXChildVisit_Recurse;
3456
3457  // Don't override a preprocessing cursor with another preprocessing
3458  // cursor; we want the outermost preprocessing cursor.
3459  if (clang_isPreprocessing(cursor.kind) &&
3460      clang_isPreprocessing(BestCursor->kind))
3461    return CXChildVisit_Recurse;
3462
3463  *BestCursor = cursor;
3464  return CXChildVisit_Recurse;
3465}
3466
3467CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
3468  if (!TU)
3469    return clang_getNullCursor();
3470
3471  ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
3472  ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3473
3474  // Translate the given source location to make it point at the beginning of
3475  // the token under the cursor.
3476  SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
3477
3478  // Guard against an invalid SourceLocation, or we may assert in one
3479  // of the following calls.
3480  if (SLoc.isInvalid())
3481    return clang_getNullCursor();
3482
3483  bool Logging = getenv("LIBCLANG_LOGGING");
3484  SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
3485                                    CXXUnit->getASTContext().getLangOptions());
3486
3487  CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
3488  if (SLoc.isValid()) {
3489    // FIXME: Would be great to have a "hint" cursor, then walk from that
3490    // hint cursor upward until we find a cursor whose source range encloses
3491    // the region of interest, rather than starting from the translation unit.
3492    GetCursorData ResultData(SLoc, Result);
3493    CXCursor Parent = clang_getTranslationUnitCursor(TU);
3494    CursorVisitor CursorVis(TU, GetCursorVisitor, &ResultData,
3495                            Decl::MaxPCHLevel, true, SourceLocation(SLoc));
3496    CursorVis.VisitChildren(Parent);
3497  }
3498
3499  if (Logging) {
3500    CXFile SearchFile;
3501    unsigned SearchLine, SearchColumn;
3502    CXFile ResultFile;
3503    unsigned ResultLine, ResultColumn;
3504    CXString SearchFileName, ResultFileName, KindSpelling, USR;
3505    const char *IsDef = clang_isCursorDefinition(Result)? " (Definition)" : "";
3506    CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
3507
3508    clang_getInstantiationLocation(Loc, &SearchFile, &SearchLine, &SearchColumn,
3509                                   0);
3510    clang_getInstantiationLocation(ResultLoc, &ResultFile, &ResultLine,
3511                                   &ResultColumn, 0);
3512    SearchFileName = clang_getFileName(SearchFile);
3513    ResultFileName = clang_getFileName(ResultFile);
3514    KindSpelling = clang_getCursorKindSpelling(Result.kind);
3515    USR = clang_getCursorUSR(Result);
3516    fprintf(stderr, "clang_getCursor(%s:%d:%d) = %s(%s:%d:%d):%s%s\n",
3517            clang_getCString(SearchFileName), SearchLine, SearchColumn,
3518            clang_getCString(KindSpelling),
3519            clang_getCString(ResultFileName), ResultLine, ResultColumn,
3520            clang_getCString(USR), IsDef);
3521    clang_disposeString(SearchFileName);
3522    clang_disposeString(ResultFileName);
3523    clang_disposeString(KindSpelling);
3524    clang_disposeString(USR);
3525
3526    CXCursor Definition = clang_getCursorDefinition(Result);
3527    if (!clang_equalCursors(Definition, clang_getNullCursor())) {
3528      CXSourceLocation DefinitionLoc = clang_getCursorLocation(Definition);
3529      CXString DefinitionKindSpelling
3530                                = clang_getCursorKindSpelling(Definition.kind);
3531      CXFile DefinitionFile;
3532      unsigned DefinitionLine, DefinitionColumn;
3533      clang_getInstantiationLocation(DefinitionLoc, &DefinitionFile,
3534                                     &DefinitionLine, &DefinitionColumn, 0);
3535      CXString DefinitionFileName = clang_getFileName(DefinitionFile);
3536      fprintf(stderr, "  -> %s(%s:%d:%d)\n",
3537              clang_getCString(DefinitionKindSpelling),
3538              clang_getCString(DefinitionFileName),
3539              DefinitionLine, DefinitionColumn);
3540      clang_disposeString(DefinitionFileName);
3541      clang_disposeString(DefinitionKindSpelling);
3542    }
3543  }
3544
3545  return Result;
3546}
3547
3548CXCursor clang_getNullCursor(void) {
3549  return MakeCXCursorInvalid(CXCursor_InvalidFile);
3550}
3551
3552unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
3553  return X == Y;
3554}
3555
3556unsigned clang_hashCursor(CXCursor C) {
3557  unsigned Index = 0;
3558  if (clang_isExpression(C.kind) || clang_isStatement(C.kind))
3559    Index = 1;
3560
3561  return llvm::DenseMapInfo<std::pair<unsigned, void*> >::getHashValue(
3562                                        std::make_pair(C.kind, C.data[Index]));
3563}
3564
3565unsigned clang_isInvalid(enum CXCursorKind K) {
3566  return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
3567}
3568
3569unsigned clang_isDeclaration(enum CXCursorKind K) {
3570  return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
3571}
3572
3573unsigned clang_isReference(enum CXCursorKind K) {
3574  return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
3575}
3576
3577unsigned clang_isExpression(enum CXCursorKind K) {
3578  return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
3579}
3580
3581unsigned clang_isStatement(enum CXCursorKind K) {
3582  return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
3583}
3584
3585unsigned clang_isAttribute(enum CXCursorKind K) {
3586    return K >= CXCursor_FirstAttr && K <= CXCursor_LastAttr;
3587}
3588
3589unsigned clang_isTranslationUnit(enum CXCursorKind K) {
3590  return K == CXCursor_TranslationUnit;
3591}
3592
3593unsigned clang_isPreprocessing(enum CXCursorKind K) {
3594  return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
3595}
3596
3597unsigned clang_isUnexposed(enum CXCursorKind K) {
3598  switch (K) {
3599    case CXCursor_UnexposedDecl:
3600    case CXCursor_UnexposedExpr:
3601    case CXCursor_UnexposedStmt:
3602    case CXCursor_UnexposedAttr:
3603      return true;
3604    default:
3605      return false;
3606  }
3607}
3608
3609CXCursorKind clang_getCursorKind(CXCursor C) {
3610  return C.kind;
3611}
3612
3613CXSourceLocation clang_getCursorLocation(CXCursor C) {
3614  if (clang_isReference(C.kind)) {
3615    switch (C.kind) {
3616    case CXCursor_ObjCSuperClassRef: {
3617      std::pair<ObjCInterfaceDecl *, SourceLocation> P
3618        = getCursorObjCSuperClassRef(C);
3619      return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3620    }
3621
3622    case CXCursor_ObjCProtocolRef: {
3623      std::pair<ObjCProtocolDecl *, SourceLocation> P
3624        = getCursorObjCProtocolRef(C);
3625      return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3626    }
3627
3628    case CXCursor_ObjCClassRef: {
3629      std::pair<ObjCInterfaceDecl *, SourceLocation> P
3630        = getCursorObjCClassRef(C);
3631      return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3632    }
3633
3634    case CXCursor_TypeRef: {
3635      std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
3636      return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3637    }
3638
3639    case CXCursor_TemplateRef: {
3640      std::pair<TemplateDecl *, SourceLocation> P = getCursorTemplateRef(C);
3641      return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3642    }
3643
3644    case CXCursor_NamespaceRef: {
3645      std::pair<NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
3646      return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3647    }
3648
3649    case CXCursor_MemberRef: {
3650      std::pair<FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
3651      return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3652    }
3653
3654    case CXCursor_CXXBaseSpecifier: {
3655      CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
3656      if (!BaseSpec)
3657        return clang_getNullLocation();
3658
3659      if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
3660        return cxloc::translateSourceLocation(getCursorContext(C),
3661                                            TSInfo->getTypeLoc().getBeginLoc());
3662
3663      return cxloc::translateSourceLocation(getCursorContext(C),
3664                                        BaseSpec->getSourceRange().getBegin());
3665    }
3666
3667    case CXCursor_LabelRef: {
3668      std::pair<LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
3669      return cxloc::translateSourceLocation(getCursorContext(C), P.second);
3670    }
3671
3672    case CXCursor_OverloadedDeclRef:
3673      return cxloc::translateSourceLocation(getCursorContext(C),
3674                                          getCursorOverloadedDeclRef(C).second);
3675
3676    default:
3677      // FIXME: Need a way to enumerate all non-reference cases.
3678      llvm_unreachable("Missed a reference kind");
3679    }
3680  }
3681
3682  if (clang_isExpression(C.kind))
3683    return cxloc::translateSourceLocation(getCursorContext(C),
3684                                   getLocationFromExpr(getCursorExpr(C)));
3685
3686  if (clang_isStatement(C.kind))
3687    return cxloc::translateSourceLocation(getCursorContext(C),
3688                                          getCursorStmt(C)->getLocStart());
3689
3690  if (C.kind == CXCursor_PreprocessingDirective) {
3691    SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
3692    return cxloc::translateSourceLocation(getCursorContext(C), L);
3693  }
3694
3695  if (C.kind == CXCursor_MacroExpansion) {
3696    SourceLocation L
3697      = cxcursor::getCursorMacroExpansion(C)->getSourceRange().getBegin();
3698    return cxloc::translateSourceLocation(getCursorContext(C), L);
3699  }
3700
3701  if (C.kind == CXCursor_MacroDefinition) {
3702    SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
3703    return cxloc::translateSourceLocation(getCursorContext(C), L);
3704  }
3705
3706  if (C.kind == CXCursor_InclusionDirective) {
3707    SourceLocation L
3708      = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
3709    return cxloc::translateSourceLocation(getCursorContext(C), L);
3710  }
3711
3712  if (C.kind < CXCursor_FirstDecl || C.kind > CXCursor_LastDecl)
3713    return clang_getNullLocation();
3714
3715  Decl *D = getCursorDecl(C);
3716  SourceLocation Loc = D->getLocation();
3717  if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
3718    Loc = Class->getClassLoc();
3719  // FIXME: Multiple variables declared in a single declaration
3720  // currently lack the information needed to correctly determine their
3721  // ranges when accounting for the type-specifier.  We use context
3722  // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3723  // and if so, whether it is the first decl.
3724  if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3725    if (!cxcursor::isFirstInDeclGroup(C))
3726      Loc = VD->getLocation();
3727  }
3728
3729  return cxloc::translateSourceLocation(getCursorContext(C), Loc);
3730}
3731
3732} // end extern "C"
3733
3734static SourceRange getRawCursorExtent(CXCursor C) {
3735  if (clang_isReference(C.kind)) {
3736    switch (C.kind) {
3737    case CXCursor_ObjCSuperClassRef:
3738      return  getCursorObjCSuperClassRef(C).second;
3739
3740    case CXCursor_ObjCProtocolRef:
3741      return getCursorObjCProtocolRef(C).second;
3742
3743    case CXCursor_ObjCClassRef:
3744      return getCursorObjCClassRef(C).second;
3745
3746    case CXCursor_TypeRef:
3747      return getCursorTypeRef(C).second;
3748
3749    case CXCursor_TemplateRef:
3750      return getCursorTemplateRef(C).second;
3751
3752    case CXCursor_NamespaceRef:
3753      return getCursorNamespaceRef(C).second;
3754
3755    case CXCursor_MemberRef:
3756      return getCursorMemberRef(C).second;
3757
3758    case CXCursor_CXXBaseSpecifier:
3759      return getCursorCXXBaseSpecifier(C)->getSourceRange();
3760
3761    case CXCursor_LabelRef:
3762      return getCursorLabelRef(C).second;
3763
3764    case CXCursor_OverloadedDeclRef:
3765      return getCursorOverloadedDeclRef(C).second;
3766
3767    default:
3768      // FIXME: Need a way to enumerate all non-reference cases.
3769      llvm_unreachable("Missed a reference kind");
3770    }
3771  }
3772
3773  if (clang_isExpression(C.kind))
3774    return getCursorExpr(C)->getSourceRange();
3775
3776  if (clang_isStatement(C.kind))
3777    return getCursorStmt(C)->getSourceRange();
3778
3779  if (C.kind == CXCursor_PreprocessingDirective)
3780    return cxcursor::getCursorPreprocessingDirective(C);
3781
3782  if (C.kind == CXCursor_MacroExpansion)
3783    return cxcursor::getCursorMacroExpansion(C)->getSourceRange();
3784
3785  if (C.kind == CXCursor_MacroDefinition)
3786    return cxcursor::getCursorMacroDefinition(C)->getSourceRange();
3787
3788  if (C.kind == CXCursor_InclusionDirective)
3789    return cxcursor::getCursorInclusionDirective(C)->getSourceRange();
3790
3791  if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
3792    Decl *D = cxcursor::getCursorDecl(C);
3793    SourceRange R = D->getSourceRange();
3794    // FIXME: Multiple variables declared in a single declaration
3795    // currently lack the information needed to correctly determine their
3796    // ranges when accounting for the type-specifier.  We use context
3797    // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3798    // and if so, whether it is the first decl.
3799    if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3800      if (!cxcursor::isFirstInDeclGroup(C))
3801        R.setBegin(VD->getLocation());
3802    }
3803    return R;
3804  }
3805  return SourceRange();
3806}
3807
3808/// \brief Retrieves the "raw" cursor extent, which is then extended to include
3809/// the decl-specifier-seq for declarations.
3810static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr) {
3811  if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
3812    Decl *D = cxcursor::getCursorDecl(C);
3813    SourceRange R = D->getSourceRange();
3814
3815    // Adjust the start of the location for declarations preceded by
3816    // declaration specifiers.
3817    SourceLocation StartLoc;
3818    if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
3819      if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
3820        StartLoc = TI->getTypeLoc().getSourceRange().getBegin();
3821    } else if (TypedefDecl *Typedef = dyn_cast<TypedefDecl>(D)) {
3822      if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
3823        StartLoc = TI->getTypeLoc().getSourceRange().getBegin();
3824    }
3825
3826    if (StartLoc.isValid() && R.getBegin().isValid() &&
3827        SrcMgr.isBeforeInTranslationUnit(StartLoc, R.getBegin()))
3828      R.setBegin(StartLoc);
3829
3830    // FIXME: Multiple variables declared in a single declaration
3831    // currently lack the information needed to correctly determine their
3832    // ranges when accounting for the type-specifier.  We use context
3833    // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3834    // and if so, whether it is the first decl.
3835    if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3836      if (!cxcursor::isFirstInDeclGroup(C))
3837        R.setBegin(VD->getLocation());
3838    }
3839
3840    return R;
3841  }
3842
3843  return getRawCursorExtent(C);
3844}
3845
3846extern "C" {
3847
3848CXSourceRange clang_getCursorExtent(CXCursor C) {
3849  SourceRange R = getRawCursorExtent(C);
3850  if (R.isInvalid())
3851    return clang_getNullRange();
3852
3853  return cxloc::translateSourceRange(getCursorContext(C), R);
3854}
3855
3856CXCursor clang_getCursorReferenced(CXCursor C) {
3857  if (clang_isInvalid(C.kind))
3858    return clang_getNullCursor();
3859
3860  CXTranslationUnit tu = getCursorTU(C);
3861  if (clang_isDeclaration(C.kind)) {
3862    Decl *D = getCursorDecl(C);
3863    if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
3864      return MakeCursorOverloadedDeclRef(Using, D->getLocation(), tu);
3865    if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
3866      return MakeCursorOverloadedDeclRef(Classes, D->getLocation(), tu);
3867    if (ObjCForwardProtocolDecl *Protocols
3868                                        = dyn_cast<ObjCForwardProtocolDecl>(D))
3869      return MakeCursorOverloadedDeclRef(Protocols, D->getLocation(), tu);
3870    if (ObjCPropertyImplDecl *PropImpl =dyn_cast<ObjCPropertyImplDecl>(D))
3871      if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
3872        return MakeCXCursor(Property, tu);
3873
3874    return C;
3875  }
3876
3877  if (clang_isExpression(C.kind)) {
3878    Expr *E = getCursorExpr(C);
3879    Decl *D = getDeclFromExpr(E);
3880    if (D)
3881      return MakeCXCursor(D, tu);
3882
3883    if (OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
3884      return MakeCursorOverloadedDeclRef(Ovl, tu);
3885
3886    return clang_getNullCursor();
3887  }
3888
3889  if (clang_isStatement(C.kind)) {
3890    Stmt *S = getCursorStmt(C);
3891    if (GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
3892      if (LabelDecl *label = Goto->getLabel())
3893        if (LabelStmt *labelS = label->getStmt())
3894        return MakeCXCursor(labelS, getCursorDecl(C), tu);
3895
3896    return clang_getNullCursor();
3897  }
3898
3899  if (C.kind == CXCursor_MacroExpansion) {
3900    if (MacroDefinition *Def = getCursorMacroExpansion(C)->getDefinition())
3901      return MakeMacroDefinitionCursor(Def, tu);
3902  }
3903
3904  if (!clang_isReference(C.kind))
3905    return clang_getNullCursor();
3906
3907  switch (C.kind) {
3908    case CXCursor_ObjCSuperClassRef:
3909      return MakeCXCursor(getCursorObjCSuperClassRef(C).first, tu);
3910
3911    case CXCursor_ObjCProtocolRef: {
3912      return MakeCXCursor(getCursorObjCProtocolRef(C).first, tu);
3913
3914    case CXCursor_ObjCClassRef:
3915      return MakeCXCursor(getCursorObjCClassRef(C).first, tu );
3916
3917    case CXCursor_TypeRef:
3918      return MakeCXCursor(getCursorTypeRef(C).first, tu );
3919
3920    case CXCursor_TemplateRef:
3921      return MakeCXCursor(getCursorTemplateRef(C).first, tu );
3922
3923    case CXCursor_NamespaceRef:
3924      return MakeCXCursor(getCursorNamespaceRef(C).first, tu );
3925
3926    case CXCursor_MemberRef:
3927      return MakeCXCursor(getCursorMemberRef(C).first, tu );
3928
3929    case CXCursor_CXXBaseSpecifier: {
3930      CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
3931      return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
3932                                                         tu ));
3933    }
3934
3935    case CXCursor_LabelRef:
3936      // FIXME: We end up faking the "parent" declaration here because we
3937      // don't want to make CXCursor larger.
3938      return MakeCXCursor(getCursorLabelRef(C).first,
3939               static_cast<ASTUnit*>(tu->TUData)->getASTContext()
3940                          .getTranslationUnitDecl(),
3941                          tu);
3942
3943    case CXCursor_OverloadedDeclRef:
3944      return C;
3945
3946    default:
3947      // We would prefer to enumerate all non-reference cursor kinds here.
3948      llvm_unreachable("Unhandled reference cursor kind");
3949      break;
3950    }
3951  }
3952
3953  return clang_getNullCursor();
3954}
3955
3956CXCursor clang_getCursorDefinition(CXCursor C) {
3957  if (clang_isInvalid(C.kind))
3958    return clang_getNullCursor();
3959
3960  CXTranslationUnit TU = getCursorTU(C);
3961
3962  bool WasReference = false;
3963  if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
3964    C = clang_getCursorReferenced(C);
3965    WasReference = true;
3966  }
3967
3968  if (C.kind == CXCursor_MacroExpansion)
3969    return clang_getCursorReferenced(C);
3970
3971  if (!clang_isDeclaration(C.kind))
3972    return clang_getNullCursor();
3973
3974  Decl *D = getCursorDecl(C);
3975  if (!D)
3976    return clang_getNullCursor();
3977
3978  switch (D->getKind()) {
3979  // Declaration kinds that don't really separate the notions of
3980  // declaration and definition.
3981  case Decl::Namespace:
3982  case Decl::Typedef:
3983  case Decl::TypeAlias:
3984  case Decl::TypeAliasTemplate:
3985  case Decl::TemplateTypeParm:
3986  case Decl::EnumConstant:
3987  case Decl::Field:
3988  case Decl::IndirectField:
3989  case Decl::ObjCIvar:
3990  case Decl::ObjCAtDefsField:
3991  case Decl::ImplicitParam:
3992  case Decl::ParmVar:
3993  case Decl::NonTypeTemplateParm:
3994  case Decl::TemplateTemplateParm:
3995  case Decl::ObjCCategoryImpl:
3996  case Decl::ObjCImplementation:
3997  case Decl::AccessSpec:
3998  case Decl::LinkageSpec:
3999  case Decl::ObjCPropertyImpl:
4000  case Decl::FileScopeAsm:
4001  case Decl::StaticAssert:
4002  case Decl::Block:
4003  case Decl::Label:  // FIXME: Is this right??
4004    return C;
4005
4006  // Declaration kinds that don't make any sense here, but are
4007  // nonetheless harmless.
4008  case Decl::TranslationUnit:
4009    break;
4010
4011  // Declaration kinds for which the definition is not resolvable.
4012  case Decl::UnresolvedUsingTypename:
4013  case Decl::UnresolvedUsingValue:
4014    break;
4015
4016  case Decl::UsingDirective:
4017    return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
4018                        TU);
4019
4020  case Decl::NamespaceAlias:
4021    return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), TU);
4022
4023  case Decl::Enum:
4024  case Decl::Record:
4025  case Decl::CXXRecord:
4026  case Decl::ClassTemplateSpecialization:
4027  case Decl::ClassTemplatePartialSpecialization:
4028    if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
4029      return MakeCXCursor(Def, TU);
4030    return clang_getNullCursor();
4031
4032  case Decl::Function:
4033  case Decl::CXXMethod:
4034  case Decl::CXXConstructor:
4035  case Decl::CXXDestructor:
4036  case Decl::CXXConversion: {
4037    const FunctionDecl *Def = 0;
4038    if (cast<FunctionDecl>(D)->getBody(Def))
4039      return MakeCXCursor(const_cast<FunctionDecl *>(Def), TU);
4040    return clang_getNullCursor();
4041  }
4042
4043  case Decl::Var: {
4044    // Ask the variable if it has a definition.
4045    if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
4046      return MakeCXCursor(Def, TU);
4047    return clang_getNullCursor();
4048  }
4049
4050  case Decl::FunctionTemplate: {
4051    const FunctionDecl *Def = 0;
4052    if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
4053      return MakeCXCursor(Def->getDescribedFunctionTemplate(), TU);
4054    return clang_getNullCursor();
4055  }
4056
4057  case Decl::ClassTemplate: {
4058    if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
4059                                                            ->getDefinition())
4060      return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
4061                          TU);
4062    return clang_getNullCursor();
4063  }
4064
4065  case Decl::Using:
4066    return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
4067                                       D->getLocation(), TU);
4068
4069  case Decl::UsingShadow:
4070    return clang_getCursorDefinition(
4071                       MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
4072                                    TU));
4073
4074  case Decl::ObjCMethod: {
4075    ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
4076    if (Method->isThisDeclarationADefinition())
4077      return C;
4078
4079    // Dig out the method definition in the associated
4080    // @implementation, if we have it.
4081    // FIXME: The ASTs should make finding the definition easier.
4082    if (ObjCInterfaceDecl *Class
4083                       = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
4084      if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
4085        if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
4086                                                  Method->isInstanceMethod()))
4087          if (Def->isThisDeclarationADefinition())
4088            return MakeCXCursor(Def, TU);
4089
4090    return clang_getNullCursor();
4091  }
4092
4093  case Decl::ObjCCategory:
4094    if (ObjCCategoryImplDecl *Impl
4095                               = cast<ObjCCategoryDecl>(D)->getImplementation())
4096      return MakeCXCursor(Impl, TU);
4097    return clang_getNullCursor();
4098
4099  case Decl::ObjCProtocol:
4100    if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
4101      return C;
4102    return clang_getNullCursor();
4103
4104  case Decl::ObjCInterface:
4105    // There are two notions of a "definition" for an Objective-C
4106    // class: the interface and its implementation. When we resolved a
4107    // reference to an Objective-C class, produce the @interface as
4108    // the definition; when we were provided with the interface,
4109    // produce the @implementation as the definition.
4110    if (WasReference) {
4111      if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
4112        return C;
4113    } else if (ObjCImplementationDecl *Impl
4114                              = cast<ObjCInterfaceDecl>(D)->getImplementation())
4115      return MakeCXCursor(Impl, TU);
4116    return clang_getNullCursor();
4117
4118  case Decl::ObjCProperty:
4119    // FIXME: We don't really know where to find the
4120    // ObjCPropertyImplDecls that implement this property.
4121    return clang_getNullCursor();
4122
4123  case Decl::ObjCCompatibleAlias:
4124    if (ObjCInterfaceDecl *Class
4125          = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
4126      if (!Class->isForwardDecl())
4127        return MakeCXCursor(Class, TU);
4128
4129    return clang_getNullCursor();
4130
4131  case Decl::ObjCForwardProtocol:
4132    return MakeCursorOverloadedDeclRef(cast<ObjCForwardProtocolDecl>(D),
4133                                       D->getLocation(), TU);
4134
4135  case Decl::ObjCClass:
4136    return MakeCursorOverloadedDeclRef(cast<ObjCClassDecl>(D), D->getLocation(),
4137                                       TU);
4138
4139  case Decl::Friend:
4140    if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
4141      return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
4142    return clang_getNullCursor();
4143
4144  case Decl::FriendTemplate:
4145    if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
4146      return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
4147    return clang_getNullCursor();
4148  }
4149
4150  return clang_getNullCursor();
4151}
4152
4153unsigned clang_isCursorDefinition(CXCursor C) {
4154  if (!clang_isDeclaration(C.kind))
4155    return 0;
4156
4157  return clang_getCursorDefinition(C) == C;
4158}
4159
4160CXCursor clang_getCanonicalCursor(CXCursor C) {
4161  if (!clang_isDeclaration(C.kind))
4162    return C;
4163
4164  if (Decl *D = getCursorDecl(C)) {
4165    if (ObjCCategoryImplDecl *CatImplD = dyn_cast<ObjCCategoryImplDecl>(D))
4166      if (ObjCCategoryDecl *CatD = CatImplD->getCategoryDecl())
4167        return MakeCXCursor(CatD, getCursorTU(C));
4168
4169    if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
4170      if (ObjCInterfaceDecl *IFD = ImplD->getClassInterface())
4171        return MakeCXCursor(IFD, getCursorTU(C));
4172
4173    return MakeCXCursor(D->getCanonicalDecl(), getCursorTU(C));
4174  }
4175
4176  return C;
4177}
4178
4179unsigned clang_getNumOverloadedDecls(CXCursor C) {
4180  if (C.kind != CXCursor_OverloadedDeclRef)
4181    return 0;
4182
4183  OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
4184  if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
4185    return E->getNumDecls();
4186
4187  if (OverloadedTemplateStorage *S
4188                              = Storage.dyn_cast<OverloadedTemplateStorage*>())
4189    return S->size();
4190
4191  Decl *D = Storage.get<Decl*>();
4192  if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
4193    return Using->shadow_size();
4194  if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
4195    return Classes->size();
4196  if (ObjCForwardProtocolDecl *Protocols =dyn_cast<ObjCForwardProtocolDecl>(D))
4197    return Protocols->protocol_size();
4198
4199  return 0;
4200}
4201
4202CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
4203  if (cursor.kind != CXCursor_OverloadedDeclRef)
4204    return clang_getNullCursor();
4205
4206  if (index >= clang_getNumOverloadedDecls(cursor))
4207    return clang_getNullCursor();
4208
4209  CXTranslationUnit TU = getCursorTU(cursor);
4210  OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
4211  if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
4212    return MakeCXCursor(E->decls_begin()[index], TU);
4213
4214  if (OverloadedTemplateStorage *S
4215                              = Storage.dyn_cast<OverloadedTemplateStorage*>())
4216    return MakeCXCursor(S->begin()[index], TU);
4217
4218  Decl *D = Storage.get<Decl*>();
4219  if (UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
4220    // FIXME: This is, unfortunately, linear time.
4221    UsingDecl::shadow_iterator Pos = Using->shadow_begin();
4222    std::advance(Pos, index);
4223    return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), TU);
4224  }
4225
4226  if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
4227    return MakeCXCursor(Classes->begin()[index].getInterface(), TU);
4228
4229  if (ObjCForwardProtocolDecl *Protocols = dyn_cast<ObjCForwardProtocolDecl>(D))
4230    return MakeCXCursor(Protocols->protocol_begin()[index], TU);
4231
4232  return clang_getNullCursor();
4233}
4234
4235void clang_getDefinitionSpellingAndExtent(CXCursor C,
4236                                          const char **startBuf,
4237                                          const char **endBuf,
4238                                          unsigned *startLine,
4239                                          unsigned *startColumn,
4240                                          unsigned *endLine,
4241                                          unsigned *endColumn) {
4242  assert(getCursorDecl(C) && "CXCursor has null decl");
4243  NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
4244  FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
4245  CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
4246
4247  SourceManager &SM = FD->getASTContext().getSourceManager();
4248  *startBuf = SM.getCharacterData(Body->getLBracLoc());
4249  *endBuf = SM.getCharacterData(Body->getRBracLoc());
4250  *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
4251  *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
4252  *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
4253  *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
4254}
4255
4256namespace {
4257typedef llvm::SmallVector<SourceRange, 4> RefNamePieces;
4258RefNamePieces buildPieces(unsigned NameFlags, bool IsMemberRefExpr,
4259                          const DeclarationNameInfo &NI,
4260                          const SourceRange &QLoc,
4261                          const ExplicitTemplateArgumentList *TemplateArgs = 0){
4262  const bool WantQualifier = NameFlags & CXNameRange_WantQualifier;
4263  const bool WantTemplateArgs = NameFlags & CXNameRange_WantTemplateArgs;
4264  const bool WantSinglePiece = NameFlags & CXNameRange_WantSinglePiece;
4265
4266  const DeclarationName::NameKind Kind = NI.getName().getNameKind();
4267
4268  RefNamePieces Pieces;
4269
4270  if (WantQualifier && QLoc.isValid())
4271    Pieces.push_back(QLoc);
4272
4273  if (Kind != DeclarationName::CXXOperatorName || IsMemberRefExpr)
4274    Pieces.push_back(NI.getLoc());
4275
4276  if (WantTemplateArgs && TemplateArgs)
4277    Pieces.push_back(SourceRange(TemplateArgs->LAngleLoc,
4278                                 TemplateArgs->RAngleLoc));
4279
4280  if (Kind == DeclarationName::CXXOperatorName) {
4281    Pieces.push_back(SourceLocation::getFromRawEncoding(
4282                       NI.getInfo().CXXOperatorName.BeginOpNameLoc));
4283    Pieces.push_back(SourceLocation::getFromRawEncoding(
4284                       NI.getInfo().CXXOperatorName.EndOpNameLoc));
4285  }
4286
4287  if (WantSinglePiece) {
4288    SourceRange R(Pieces.front().getBegin(), Pieces.back().getEnd());
4289    Pieces.clear();
4290    Pieces.push_back(R);
4291  }
4292
4293  return Pieces;
4294}
4295}
4296
4297CXSourceRange clang_getCursorReferenceNameRange(CXCursor C, unsigned NameFlags,
4298                                                unsigned PieceIndex) {
4299  RefNamePieces Pieces;
4300
4301  switch (C.kind) {
4302  case CXCursor_MemberRefExpr:
4303    if (MemberExpr *E = dyn_cast<MemberExpr>(getCursorExpr(C)))
4304      Pieces = buildPieces(NameFlags, true, E->getMemberNameInfo(),
4305                           E->getQualifierLoc().getSourceRange());
4306    break;
4307
4308  case CXCursor_DeclRefExpr:
4309    if (DeclRefExpr *E = dyn_cast<DeclRefExpr>(getCursorExpr(C)))
4310      Pieces = buildPieces(NameFlags, false, E->getNameInfo(),
4311                           E->getQualifierLoc().getSourceRange(),
4312                           E->getExplicitTemplateArgsOpt());
4313    break;
4314
4315  case CXCursor_CallExpr:
4316    if (CXXOperatorCallExpr *OCE =
4317        dyn_cast<CXXOperatorCallExpr>(getCursorExpr(C))) {
4318      Expr *Callee = OCE->getCallee();
4319      if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Callee))
4320        Callee = ICE->getSubExpr();
4321
4322      if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Callee))
4323        Pieces = buildPieces(NameFlags, false, DRE->getNameInfo(),
4324                             DRE->getQualifierLoc().getSourceRange());
4325    }
4326    break;
4327
4328  default:
4329    break;
4330  }
4331
4332  if (Pieces.empty()) {
4333    if (PieceIndex == 0)
4334      return clang_getCursorExtent(C);
4335  } else if (PieceIndex < Pieces.size()) {
4336      SourceRange R = Pieces[PieceIndex];
4337      if (R.isValid())
4338        return cxloc::translateSourceRange(getCursorContext(C), R);
4339  }
4340
4341  return clang_getNullRange();
4342}
4343
4344void clang_enableStackTraces(void) {
4345  llvm::sys::PrintStackTraceOnErrorSignal();
4346}
4347
4348void clang_executeOnThread(void (*fn)(void*), void *user_data,
4349                           unsigned stack_size) {
4350  llvm::llvm_execute_on_thread(fn, user_data, stack_size);
4351}
4352
4353} // end: extern "C"
4354
4355//===----------------------------------------------------------------------===//
4356// Token-based Operations.
4357//===----------------------------------------------------------------------===//
4358
4359/* CXToken layout:
4360 *   int_data[0]: a CXTokenKind
4361 *   int_data[1]: starting token location
4362 *   int_data[2]: token length
4363 *   int_data[3]: reserved
4364 *   ptr_data: for identifiers and keywords, an IdentifierInfo*.
4365 *   otherwise unused.
4366 */
4367extern "C" {
4368
4369CXTokenKind clang_getTokenKind(CXToken CXTok) {
4370  return static_cast<CXTokenKind>(CXTok.int_data[0]);
4371}
4372
4373CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
4374  switch (clang_getTokenKind(CXTok)) {
4375  case CXToken_Identifier:
4376  case CXToken_Keyword:
4377    // We know we have an IdentifierInfo*, so use that.
4378    return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
4379                            ->getNameStart());
4380
4381  case CXToken_Literal: {
4382    // We have stashed the starting pointer in the ptr_data field. Use it.
4383    const char *Text = static_cast<const char *>(CXTok.ptr_data);
4384    return createCXString(StringRef(Text, CXTok.int_data[2]));
4385  }
4386
4387  case CXToken_Punctuation:
4388  case CXToken_Comment:
4389    break;
4390  }
4391
4392  // We have to find the starting buffer pointer the hard way, by
4393  // deconstructing the source location.
4394  ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
4395  if (!CXXUnit)
4396    return createCXString("");
4397
4398  SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
4399  std::pair<FileID, unsigned> LocInfo
4400    = CXXUnit->getSourceManager().getDecomposedLoc(Loc);
4401  bool Invalid = false;
4402  StringRef Buffer
4403    = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
4404  if (Invalid)
4405    return createCXString("");
4406
4407  return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
4408}
4409
4410CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
4411  ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
4412  if (!CXXUnit)
4413    return clang_getNullLocation();
4414
4415  return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
4416                        SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
4417}
4418
4419CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
4420  ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
4421  if (!CXXUnit)
4422    return clang_getNullRange();
4423
4424  return cxloc::translateSourceRange(CXXUnit->getASTContext(),
4425                        SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
4426}
4427
4428void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
4429                    CXToken **Tokens, unsigned *NumTokens) {
4430  if (Tokens)
4431    *Tokens = 0;
4432  if (NumTokens)
4433    *NumTokens = 0;
4434
4435  ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
4436  if (!CXXUnit || !Tokens || !NumTokens)
4437    return;
4438
4439  ASTUnit::ConcurrencyCheck Check(*CXXUnit);
4440
4441  SourceRange R = cxloc::translateCXSourceRange(Range);
4442  if (R.isInvalid())
4443    return;
4444
4445  SourceManager &SourceMgr = CXXUnit->getSourceManager();
4446  std::pair<FileID, unsigned> BeginLocInfo
4447    = SourceMgr.getDecomposedLoc(R.getBegin());
4448  std::pair<FileID, unsigned> EndLocInfo
4449    = SourceMgr.getDecomposedLoc(R.getEnd());
4450
4451  // Cannot tokenize across files.
4452  if (BeginLocInfo.first != EndLocInfo.first)
4453    return;
4454
4455  // Create a lexer
4456  bool Invalid = false;
4457  StringRef Buffer
4458    = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
4459  if (Invalid)
4460    return;
4461
4462  Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
4463            CXXUnit->getASTContext().getLangOptions(),
4464            Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
4465  Lex.SetCommentRetentionState(true);
4466
4467  // Lex tokens until we hit the end of the range.
4468  const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
4469  SmallVector<CXToken, 32> CXTokens;
4470  Token Tok;
4471  bool previousWasAt = false;
4472  do {
4473    // Lex the next token
4474    Lex.LexFromRawLexer(Tok);
4475    if (Tok.is(tok::eof))
4476      break;
4477
4478    // Initialize the CXToken.
4479    CXToken CXTok;
4480
4481    //   - Common fields
4482    CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
4483    CXTok.int_data[2] = Tok.getLength();
4484    CXTok.int_data[3] = 0;
4485
4486    //   - Kind-specific fields
4487    if (Tok.isLiteral()) {
4488      CXTok.int_data[0] = CXToken_Literal;
4489      CXTok.ptr_data = (void *)Tok.getLiteralData();
4490    } else if (Tok.is(tok::raw_identifier)) {
4491      // Lookup the identifier to determine whether we have a keyword.
4492      IdentifierInfo *II
4493        = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok);
4494
4495      if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
4496        CXTok.int_data[0] = CXToken_Keyword;
4497      }
4498      else {
4499        CXTok.int_data[0] = Tok.is(tok::identifier)
4500          ? CXToken_Identifier
4501          : CXToken_Keyword;
4502      }
4503      CXTok.ptr_data = II;
4504    } else if (Tok.is(tok::comment)) {
4505      CXTok.int_data[0] = CXToken_Comment;
4506      CXTok.ptr_data = 0;
4507    } else {
4508      CXTok.int_data[0] = CXToken_Punctuation;
4509      CXTok.ptr_data = 0;
4510    }
4511    CXTokens.push_back(CXTok);
4512    previousWasAt = Tok.is(tok::at);
4513  } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
4514
4515  if (CXTokens.empty())
4516    return;
4517
4518  *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
4519  memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
4520  *NumTokens = CXTokens.size();
4521}
4522
4523void clang_disposeTokens(CXTranslationUnit TU,
4524                         CXToken *Tokens, unsigned NumTokens) {
4525  free(Tokens);
4526}
4527
4528} // end: extern "C"
4529
4530//===----------------------------------------------------------------------===//
4531// Token annotation APIs.
4532//===----------------------------------------------------------------------===//
4533
4534typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
4535static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
4536                                                     CXCursor parent,
4537                                                     CXClientData client_data);
4538namespace {
4539class AnnotateTokensWorker {
4540  AnnotateTokensData &Annotated;
4541  CXToken *Tokens;
4542  CXCursor *Cursors;
4543  unsigned NumTokens;
4544  unsigned TokIdx;
4545  unsigned PreprocessingTokIdx;
4546  CursorVisitor AnnotateVis;
4547  SourceManager &SrcMgr;
4548  bool HasContextSensitiveKeywords;
4549
4550  bool MoreTokens() const { return TokIdx < NumTokens; }
4551  unsigned NextToken() const { return TokIdx; }
4552  void AdvanceToken() { ++TokIdx; }
4553  SourceLocation GetTokenLoc(unsigned tokI) {
4554    return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
4555  }
4556
4557public:
4558  AnnotateTokensWorker(AnnotateTokensData &annotated,
4559                       CXToken *tokens, CXCursor *cursors, unsigned numTokens,
4560                       CXTranslationUnit tu, SourceRange RegionOfInterest)
4561    : Annotated(annotated), Tokens(tokens), Cursors(cursors),
4562      NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0),
4563      AnnotateVis(tu,
4564                  AnnotateTokensVisitor, this,
4565                  Decl::MaxPCHLevel, true, RegionOfInterest),
4566      SrcMgr(static_cast<ASTUnit*>(tu->TUData)->getSourceManager()),
4567      HasContextSensitiveKeywords(false) { }
4568
4569  void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
4570  enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
4571  void AnnotateTokens(CXCursor parent);
4572  void AnnotateTokens() {
4573    AnnotateTokens(clang_getTranslationUnitCursor(AnnotateVis.getTU()));
4574  }
4575
4576  /// \brief Determine whether the annotator saw any cursors that have
4577  /// context-sensitive keywords.
4578  bool hasContextSensitiveKeywords() const {
4579    return HasContextSensitiveKeywords;
4580  }
4581};
4582}
4583
4584void AnnotateTokensWorker::AnnotateTokens(CXCursor parent) {
4585  // Walk the AST within the region of interest, annotating tokens
4586  // along the way.
4587  VisitChildren(parent);
4588
4589  for (unsigned I = 0 ; I < TokIdx ; ++I) {
4590    AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
4591    if (Pos != Annotated.end() &&
4592        (clang_isInvalid(Cursors[I].kind) ||
4593         Pos->second.kind != CXCursor_PreprocessingDirective))
4594      Cursors[I] = Pos->second;
4595  }
4596
4597  // Finish up annotating any tokens left.
4598  if (!MoreTokens())
4599    return;
4600
4601  const CXCursor &C = clang_getNullCursor();
4602  for (unsigned I = TokIdx ; I < NumTokens ; ++I) {
4603    AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
4604    Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second;
4605  }
4606}
4607
4608enum CXChildVisitResult
4609AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
4610  CXSourceLocation Loc = clang_getCursorLocation(cursor);
4611  SourceRange cursorRange = getRawCursorExtent(cursor);
4612  if (cursorRange.isInvalid())
4613    return CXChildVisit_Recurse;
4614
4615  if (!HasContextSensitiveKeywords) {
4616    // Objective-C properties can have context-sensitive keywords.
4617    if (cursor.kind == CXCursor_ObjCPropertyDecl) {
4618      if (ObjCPropertyDecl *Property
4619                  = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(cursor)))
4620        HasContextSensitiveKeywords = Property->getPropertyAttributesAsWritten() != 0;
4621    }
4622    // Objective-C methods can have context-sensitive keywords.
4623    else if (cursor.kind == CXCursor_ObjCInstanceMethodDecl ||
4624             cursor.kind == CXCursor_ObjCClassMethodDecl) {
4625      if (ObjCMethodDecl *Method
4626            = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
4627        if (Method->getObjCDeclQualifier())
4628          HasContextSensitiveKeywords = true;
4629        else {
4630          for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
4631                                           PEnd = Method->param_end();
4632               P != PEnd; ++P) {
4633            if ((*P)->getObjCDeclQualifier()) {
4634              HasContextSensitiveKeywords = true;
4635              break;
4636            }
4637          }
4638        }
4639      }
4640    }
4641    // C++ methods can have context-sensitive keywords.
4642    else if (cursor.kind == CXCursor_CXXMethod) {
4643      if (CXXMethodDecl *Method
4644                  = dyn_cast_or_null<CXXMethodDecl>(getCursorDecl(cursor))) {
4645        if (Method->hasAttr<FinalAttr>() || Method->hasAttr<OverrideAttr>())
4646          HasContextSensitiveKeywords = true;
4647      }
4648    }
4649    // C++ classes can have context-sensitive keywords.
4650    else if (cursor.kind == CXCursor_StructDecl ||
4651             cursor.kind == CXCursor_ClassDecl ||
4652             cursor.kind == CXCursor_ClassTemplate ||
4653             cursor.kind == CXCursor_ClassTemplatePartialSpecialization) {
4654      if (Decl *D = getCursorDecl(cursor))
4655        if (D->hasAttr<FinalAttr>())
4656          HasContextSensitiveKeywords = true;
4657    }
4658  }
4659
4660  if (clang_isPreprocessing(cursor.kind)) {
4661    // For macro expansions, just note where the beginning of the macro
4662    // expansion occurs.
4663    if (cursor.kind == CXCursor_MacroExpansion) {
4664      Annotated[Loc.int_data] = cursor;
4665      return CXChildVisit_Recurse;
4666    }
4667
4668    // Items in the preprocessing record are kept separate from items in
4669    // declarations, so we keep a separate token index.
4670    unsigned SavedTokIdx = TokIdx;
4671    TokIdx = PreprocessingTokIdx;
4672
4673    // Skip tokens up until we catch up to the beginning of the preprocessing
4674    // entry.
4675    while (MoreTokens()) {
4676      const unsigned I = NextToken();
4677      SourceLocation TokLoc = GetTokenLoc(I);
4678      switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4679      case RangeBefore:
4680        AdvanceToken();
4681        continue;
4682      case RangeAfter:
4683      case RangeOverlap:
4684        break;
4685      }
4686      break;
4687    }
4688
4689    // Look at all of the tokens within this range.
4690    while (MoreTokens()) {
4691      const unsigned I = NextToken();
4692      SourceLocation TokLoc = GetTokenLoc(I);
4693      switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4694      case RangeBefore:
4695        assert(0 && "Infeasible");
4696      case RangeAfter:
4697        break;
4698      case RangeOverlap:
4699        Cursors[I] = cursor;
4700        AdvanceToken();
4701        continue;
4702      }
4703      break;
4704    }
4705
4706    // Save the preprocessing token index; restore the non-preprocessing
4707    // token index.
4708    PreprocessingTokIdx = TokIdx;
4709    TokIdx = SavedTokIdx;
4710    return CXChildVisit_Recurse;
4711  }
4712
4713  if (cursorRange.isInvalid())
4714    return CXChildVisit_Continue;
4715
4716  SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data);
4717
4718  // Adjust the annotated range based specific declarations.
4719  const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
4720  if (cursorK >= CXCursor_FirstDecl && cursorK <= CXCursor_LastDecl) {
4721    Decl *D = cxcursor::getCursorDecl(cursor);
4722    // Don't visit synthesized ObjC methods, since they have no syntatic
4723    // representation in the source.
4724    if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
4725      if (MD->isSynthesized())
4726        return CXChildVisit_Continue;
4727    }
4728
4729    SourceLocation StartLoc;
4730    if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
4731      if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
4732        StartLoc = TI->getTypeLoc().getSourceRange().getBegin();
4733    } else if (TypedefDecl *Typedef = dyn_cast<TypedefDecl>(D)) {
4734      if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
4735        StartLoc = TI->getTypeLoc().getSourceRange().getBegin();
4736    }
4737
4738    if (StartLoc.isValid() && L.isValid() &&
4739        SrcMgr.isBeforeInTranslationUnit(StartLoc, L))
4740      cursorRange.setBegin(StartLoc);
4741  }
4742
4743  // If the location of the cursor occurs within a macro instantiation, record
4744  // the spelling location of the cursor in our annotation map.  We can then
4745  // paper over the token labelings during a post-processing step to try and
4746  // get cursor mappings for tokens that are the *arguments* of a macro
4747  // instantiation.
4748  if (L.isMacroID()) {
4749    unsigned rawEncoding = SrcMgr.getSpellingLoc(L).getRawEncoding();
4750    // Only invalidate the old annotation if it isn't part of a preprocessing
4751    // directive.  Here we assume that the default construction of CXCursor
4752    // results in CXCursor.kind being an initialized value (i.e., 0).  If
4753    // this isn't the case, we can fix by doing lookup + insertion.
4754
4755    CXCursor &oldC = Annotated[rawEncoding];
4756    if (!clang_isPreprocessing(oldC.kind))
4757      oldC = cursor;
4758  }
4759
4760  const enum CXCursorKind K = clang_getCursorKind(parent);
4761  const CXCursor updateC =
4762    (clang_isInvalid(K) || K == CXCursor_TranslationUnit)
4763     ? clang_getNullCursor() : parent;
4764
4765  while (MoreTokens()) {
4766    const unsigned I = NextToken();
4767    SourceLocation TokLoc = GetTokenLoc(I);
4768    switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4769      case RangeBefore:
4770        Cursors[I] = updateC;
4771        AdvanceToken();
4772        continue;
4773      case RangeAfter:
4774      case RangeOverlap:
4775        break;
4776    }
4777    break;
4778  }
4779
4780  // Avoid having the cursor of an expression "overwrite" the annotation of the
4781  // variable declaration that it belongs to.
4782  // This can happen for C++ constructor expressions whose range generally
4783  // include the variable declaration, e.g.:
4784  //  MyCXXClass foo; // Make sure we don't annotate 'foo' as a CallExpr cursor.
4785  if (clang_isExpression(cursorK)) {
4786    Expr *E = getCursorExpr(cursor);
4787    if (Decl *D = getCursorParentDecl(cursor)) {
4788      const unsigned I = NextToken();
4789      if (E->getLocStart().isValid() && D->getLocation().isValid() &&
4790          E->getLocStart() == D->getLocation() &&
4791          E->getLocStart() == GetTokenLoc(I)) {
4792        Cursors[I] = updateC;
4793        AdvanceToken();
4794      }
4795    }
4796  }
4797
4798  // Visit children to get their cursor information.
4799  const unsigned BeforeChildren = NextToken();
4800  VisitChildren(cursor);
4801  const unsigned AfterChildren = NextToken();
4802
4803  // Adjust 'Last' to the last token within the extent of the cursor.
4804  while (MoreTokens()) {
4805    const unsigned I = NextToken();
4806    SourceLocation TokLoc = GetTokenLoc(I);
4807    switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4808      case RangeBefore:
4809        assert(0 && "Infeasible");
4810      case RangeAfter:
4811        break;
4812      case RangeOverlap:
4813        Cursors[I] = updateC;
4814        AdvanceToken();
4815        continue;
4816    }
4817    break;
4818  }
4819  const unsigned Last = NextToken();
4820
4821  // Scan the tokens that are at the beginning of the cursor, but are not
4822  // capture by the child cursors.
4823
4824  // For AST elements within macros, rely on a post-annotate pass to
4825  // to correctly annotate the tokens with cursors.  Otherwise we can
4826  // get confusing results of having tokens that map to cursors that really
4827  // are expanded by an instantiation.
4828  if (L.isMacroID())
4829    cursor = clang_getNullCursor();
4830
4831  for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
4832    if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
4833      break;
4834
4835    Cursors[I] = cursor;
4836  }
4837  // Scan the tokens that are at the end of the cursor, but are not captured
4838  // but the child cursors.
4839  for (unsigned I = AfterChildren; I != Last; ++I)
4840    Cursors[I] = cursor;
4841
4842  TokIdx = Last;
4843  return CXChildVisit_Continue;
4844}
4845
4846static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
4847                                                     CXCursor parent,
4848                                                     CXClientData client_data) {
4849  return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
4850}
4851
4852namespace {
4853  struct clang_annotateTokens_Data {
4854    CXTranslationUnit TU;
4855    ASTUnit *CXXUnit;
4856    CXToken *Tokens;
4857    unsigned NumTokens;
4858    CXCursor *Cursors;
4859  };
4860}
4861
4862// This gets run a separate thread to avoid stack blowout.
4863static void clang_annotateTokensImpl(void *UserData) {
4864  CXTranslationUnit TU = ((clang_annotateTokens_Data*)UserData)->TU;
4865  ASTUnit *CXXUnit = ((clang_annotateTokens_Data*)UserData)->CXXUnit;
4866  CXToken *Tokens = ((clang_annotateTokens_Data*)UserData)->Tokens;
4867  const unsigned NumTokens = ((clang_annotateTokens_Data*)UserData)->NumTokens;
4868  CXCursor *Cursors = ((clang_annotateTokens_Data*)UserData)->Cursors;
4869
4870  // Determine the region of interest, which contains all of the tokens.
4871  SourceRange RegionOfInterest;
4872  RegionOfInterest.setBegin(
4873    cxloc::translateSourceLocation(clang_getTokenLocation(TU, Tokens[0])));
4874  RegionOfInterest.setEnd(
4875    cxloc::translateSourceLocation(clang_getTokenLocation(TU,
4876                                                         Tokens[NumTokens-1])));
4877
4878  // A mapping from the source locations found when re-lexing or traversing the
4879  // region of interest to the corresponding cursors.
4880  AnnotateTokensData Annotated;
4881
4882  // Relex the tokens within the source range to look for preprocessing
4883  // directives.
4884  SourceManager &SourceMgr = CXXUnit->getSourceManager();
4885  std::pair<FileID, unsigned> BeginLocInfo
4886    = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
4887  std::pair<FileID, unsigned> EndLocInfo
4888    = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
4889
4890  StringRef Buffer;
4891  bool Invalid = false;
4892  if (BeginLocInfo.first == EndLocInfo.first &&
4893      ((Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid)),true) &&
4894      !Invalid) {
4895    Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
4896              CXXUnit->getASTContext().getLangOptions(),
4897              Buffer.begin(), Buffer.data() + BeginLocInfo.second,
4898              Buffer.end());
4899    Lex.SetCommentRetentionState(true);
4900
4901    // Lex tokens in raw mode until we hit the end of the range, to avoid
4902    // entering #includes or expanding macros.
4903    while (true) {
4904      Token Tok;
4905      Lex.LexFromRawLexer(Tok);
4906
4907    reprocess:
4908      if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
4909        // We have found a preprocessing directive. Gobble it up so that we
4910        // don't see it while preprocessing these tokens later, but keep track
4911        // of all of the token locations inside this preprocessing directive so
4912        // that we can annotate them appropriately.
4913        //
4914        // FIXME: Some simple tests here could identify macro definitions and
4915        // #undefs, to provide specific cursor kinds for those.
4916        SmallVector<SourceLocation, 32> Locations;
4917        do {
4918          Locations.push_back(Tok.getLocation());
4919          Lex.LexFromRawLexer(Tok);
4920        } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
4921
4922        using namespace cxcursor;
4923        CXCursor Cursor
4924        = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
4925                                                       Locations.back()),
4926                                           TU);
4927        for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
4928          Annotated[Locations[I].getRawEncoding()] = Cursor;
4929        }
4930
4931        if (Tok.isAtStartOfLine())
4932          goto reprocess;
4933
4934        continue;
4935      }
4936
4937      if (Tok.is(tok::eof))
4938        break;
4939    }
4940  }
4941
4942  // Annotate all of the source locations in the region of interest that map to
4943  // a specific cursor.
4944  AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens,
4945                         TU, RegionOfInterest);
4946
4947  // FIXME: We use a ridiculous stack size here because the data-recursion
4948  // algorithm uses a large stack frame than the non-data recursive version,
4949  // and AnnotationTokensWorker currently transforms the data-recursion
4950  // algorithm back into a traditional recursion by explicitly calling
4951  // VisitChildren().  We will need to remove this explicit recursive call.
4952  W.AnnotateTokens();
4953
4954  // If we ran into any entities that involve context-sensitive keywords,
4955  // take another pass through the tokens to mark them as such.
4956  if (W.hasContextSensitiveKeywords()) {
4957    for (unsigned I = 0; I != NumTokens; ++I) {
4958      if (clang_getTokenKind(Tokens[I]) != CXToken_Identifier)
4959        continue;
4960
4961      if (Cursors[I].kind == CXCursor_ObjCPropertyDecl) {
4962        IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
4963        if (ObjCPropertyDecl *Property
4964            = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(Cursors[I]))) {
4965          if (Property->getPropertyAttributesAsWritten() != 0 &&
4966              llvm::StringSwitch<bool>(II->getName())
4967              .Case("readonly", true)
4968              .Case("assign", true)
4969              .Case("unsafe_unretained", true)
4970              .Case("readwrite", true)
4971              .Case("retain", true)
4972              .Case("copy", true)
4973              .Case("nonatomic", true)
4974              .Case("atomic", true)
4975              .Case("getter", true)
4976              .Case("setter", true)
4977              .Case("strong", true)
4978              .Case("weak", true)
4979              .Default(false))
4980            Tokens[I].int_data[0] = CXToken_Keyword;
4981        }
4982        continue;
4983      }
4984
4985      if (Cursors[I].kind == CXCursor_ObjCInstanceMethodDecl ||
4986          Cursors[I].kind == CXCursor_ObjCClassMethodDecl) {
4987        IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
4988        if (llvm::StringSwitch<bool>(II->getName())
4989            .Case("in", true)
4990            .Case("out", true)
4991            .Case("inout", true)
4992            .Case("oneway", true)
4993            .Case("bycopy", true)
4994            .Case("byref", true)
4995            .Default(false))
4996          Tokens[I].int_data[0] = CXToken_Keyword;
4997        continue;
4998      }
4999
5000      if (Cursors[I].kind == CXCursor_CXXMethod) {
5001        IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
5002        if (CXXMethodDecl *Method
5003            = dyn_cast_or_null<CXXMethodDecl>(getCursorDecl(Cursors[I]))) {
5004          if ((Method->hasAttr<FinalAttr>() ||
5005               Method->hasAttr<OverrideAttr>()) &&
5006              Method->getLocation().getRawEncoding() != Tokens[I].int_data[1] &&
5007              llvm::StringSwitch<bool>(II->getName())
5008              .Case("final", true)
5009              .Case("override", true)
5010              .Default(false))
5011            Tokens[I].int_data[0] = CXToken_Keyword;
5012        }
5013        continue;
5014      }
5015
5016      if (Cursors[I].kind == CXCursor_ClassDecl ||
5017          Cursors[I].kind == CXCursor_StructDecl ||
5018          Cursors[I].kind == CXCursor_ClassTemplate) {
5019        IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
5020        if (II->getName() == "final") {
5021          // We have to be careful with 'final', since it could be the name
5022          // of a member class rather than the context-sensitive keyword.
5023          // So, check whether the cursor associated with this
5024          Decl *D = getCursorDecl(Cursors[I]);
5025          if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(D)) {
5026            if ((Record->hasAttr<FinalAttr>()) &&
5027                Record->getIdentifier() != II)
5028              Tokens[I].int_data[0] = CXToken_Keyword;
5029          } else if (ClassTemplateDecl *ClassTemplate
5030                     = dyn_cast_or_null<ClassTemplateDecl>(D)) {
5031            CXXRecordDecl *Record = ClassTemplate->getTemplatedDecl();
5032            if ((Record->hasAttr<FinalAttr>()) &&
5033                Record->getIdentifier() != II)
5034              Tokens[I].int_data[0] = CXToken_Keyword;
5035          }
5036        }
5037        continue;
5038      }
5039    }
5040  }
5041}
5042
5043extern "C" {
5044
5045void clang_annotateTokens(CXTranslationUnit TU,
5046                          CXToken *Tokens, unsigned NumTokens,
5047                          CXCursor *Cursors) {
5048
5049  if (NumTokens == 0 || !Tokens || !Cursors)
5050    return;
5051
5052  // Any token we don't specifically annotate will have a NULL cursor.
5053  CXCursor C = clang_getNullCursor();
5054  for (unsigned I = 0; I != NumTokens; ++I)
5055    Cursors[I] = C;
5056
5057  ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
5058  if (!CXXUnit)
5059    return;
5060
5061  ASTUnit::ConcurrencyCheck Check(*CXXUnit);
5062
5063  clang_annotateTokens_Data data = { TU, CXXUnit, Tokens, NumTokens, Cursors };
5064  llvm::CrashRecoveryContext CRC;
5065  if (!RunSafely(CRC, clang_annotateTokensImpl, &data,
5066                 GetSafetyThreadStackSize() * 2)) {
5067    fprintf(stderr, "libclang: crash detected while annotating tokens\n");
5068  }
5069}
5070
5071} // end: extern "C"
5072
5073//===----------------------------------------------------------------------===//
5074// Operations for querying linkage of a cursor.
5075//===----------------------------------------------------------------------===//
5076
5077extern "C" {
5078CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
5079  if (!clang_isDeclaration(cursor.kind))
5080    return CXLinkage_Invalid;
5081
5082  Decl *D = cxcursor::getCursorDecl(cursor);
5083  if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
5084    switch (ND->getLinkage()) {
5085      case NoLinkage: return CXLinkage_NoLinkage;
5086      case InternalLinkage: return CXLinkage_Internal;
5087      case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
5088      case ExternalLinkage: return CXLinkage_External;
5089    };
5090
5091  return CXLinkage_Invalid;
5092}
5093} // end: extern "C"
5094
5095//===----------------------------------------------------------------------===//
5096// Operations for querying language of a cursor.
5097//===----------------------------------------------------------------------===//
5098
5099static CXLanguageKind getDeclLanguage(const Decl *D) {
5100  switch (D->getKind()) {
5101    default:
5102      break;
5103    case Decl::ImplicitParam:
5104    case Decl::ObjCAtDefsField:
5105    case Decl::ObjCCategory:
5106    case Decl::ObjCCategoryImpl:
5107    case Decl::ObjCClass:
5108    case Decl::ObjCCompatibleAlias:
5109    case Decl::ObjCForwardProtocol:
5110    case Decl::ObjCImplementation:
5111    case Decl::ObjCInterface:
5112    case Decl::ObjCIvar:
5113    case Decl::ObjCMethod:
5114    case Decl::ObjCProperty:
5115    case Decl::ObjCPropertyImpl:
5116    case Decl::ObjCProtocol:
5117      return CXLanguage_ObjC;
5118    case Decl::CXXConstructor:
5119    case Decl::CXXConversion:
5120    case Decl::CXXDestructor:
5121    case Decl::CXXMethod:
5122    case Decl::CXXRecord:
5123    case Decl::ClassTemplate:
5124    case Decl::ClassTemplatePartialSpecialization:
5125    case Decl::ClassTemplateSpecialization:
5126    case Decl::Friend:
5127    case Decl::FriendTemplate:
5128    case Decl::FunctionTemplate:
5129    case Decl::LinkageSpec:
5130    case Decl::Namespace:
5131    case Decl::NamespaceAlias:
5132    case Decl::NonTypeTemplateParm:
5133    case Decl::StaticAssert:
5134    case Decl::TemplateTemplateParm:
5135    case Decl::TemplateTypeParm:
5136    case Decl::UnresolvedUsingTypename:
5137    case Decl::UnresolvedUsingValue:
5138    case Decl::Using:
5139    case Decl::UsingDirective:
5140    case Decl::UsingShadow:
5141      return CXLanguage_CPlusPlus;
5142  }
5143
5144  return CXLanguage_C;
5145}
5146
5147extern "C" {
5148
5149enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
5150  if (clang_isDeclaration(cursor.kind))
5151    if (Decl *D = cxcursor::getCursorDecl(cursor)) {
5152      if (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted())
5153        return CXAvailability_Available;
5154
5155      switch (D->getAvailability()) {
5156      case AR_Available:
5157      case AR_NotYetIntroduced:
5158        return CXAvailability_Available;
5159
5160      case AR_Deprecated:
5161        return CXAvailability_Deprecated;
5162
5163      case AR_Unavailable:
5164        return CXAvailability_NotAvailable;
5165      }
5166    }
5167
5168  return CXAvailability_Available;
5169}
5170
5171CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
5172  if (clang_isDeclaration(cursor.kind))
5173    return getDeclLanguage(cxcursor::getCursorDecl(cursor));
5174
5175  return CXLanguage_Invalid;
5176}
5177
5178 /// \brief If the given cursor is the "templated" declaration
5179 /// descibing a class or function template, return the class or
5180 /// function template.
5181static Decl *maybeGetTemplateCursor(Decl *D) {
5182  if (!D)
5183    return 0;
5184
5185  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
5186    if (FunctionTemplateDecl *FunTmpl = FD->getDescribedFunctionTemplate())
5187      return FunTmpl;
5188
5189  if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
5190    if (ClassTemplateDecl *ClassTmpl = RD->getDescribedClassTemplate())
5191      return ClassTmpl;
5192
5193  return D;
5194}
5195
5196CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
5197  if (clang_isDeclaration(cursor.kind)) {
5198    if (Decl *D = getCursorDecl(cursor)) {
5199      DeclContext *DC = D->getDeclContext();
5200      if (!DC)
5201        return clang_getNullCursor();
5202
5203      return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
5204                          getCursorTU(cursor));
5205    }
5206  }
5207
5208  if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
5209    if (Decl *D = getCursorDecl(cursor))
5210      return MakeCXCursor(D, getCursorTU(cursor));
5211  }
5212
5213  return clang_getNullCursor();
5214}
5215
5216CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
5217  if (clang_isDeclaration(cursor.kind)) {
5218    if (Decl *D = getCursorDecl(cursor)) {
5219      DeclContext *DC = D->getLexicalDeclContext();
5220      if (!DC)
5221        return clang_getNullCursor();
5222
5223      return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
5224                          getCursorTU(cursor));
5225    }
5226  }
5227
5228  // FIXME: Note that we can't easily compute the lexical context of a
5229  // statement or expression, so we return nothing.
5230  return clang_getNullCursor();
5231}
5232
5233static void CollectOverriddenMethods(DeclContext *Ctx,
5234                                     ObjCMethodDecl *Method,
5235                            SmallVectorImpl<ObjCMethodDecl *> &Methods) {
5236  if (!Ctx)
5237    return;
5238
5239  // If we have a class or category implementation, jump straight to the
5240  // interface.
5241  if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(Ctx))
5242    return CollectOverriddenMethods(Impl->getClassInterface(), Method, Methods);
5243
5244  ObjCContainerDecl *Container = dyn_cast<ObjCContainerDecl>(Ctx);
5245  if (!Container)
5246    return;
5247
5248  // Check whether we have a matching method at this level.
5249  if (ObjCMethodDecl *Overridden = Container->getMethod(Method->getSelector(),
5250                                                    Method->isInstanceMethod()))
5251    if (Method != Overridden) {
5252      // We found an override at this level; there is no need to look
5253      // into other protocols or categories.
5254      Methods.push_back(Overridden);
5255      return;
5256    }
5257
5258  if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
5259    for (ObjCProtocolDecl::protocol_iterator P = Protocol->protocol_begin(),
5260                                          PEnd = Protocol->protocol_end();
5261         P != PEnd; ++P)
5262      CollectOverriddenMethods(*P, Method, Methods);
5263  }
5264
5265  if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Container)) {
5266    for (ObjCCategoryDecl::protocol_iterator P = Category->protocol_begin(),
5267                                          PEnd = Category->protocol_end();
5268         P != PEnd; ++P)
5269      CollectOverriddenMethods(*P, Method, Methods);
5270  }
5271
5272  if (ObjCInterfaceDecl *Interface = dyn_cast<ObjCInterfaceDecl>(Container)) {
5273    for (ObjCInterfaceDecl::protocol_iterator P = Interface->protocol_begin(),
5274                                           PEnd = Interface->protocol_end();
5275         P != PEnd; ++P)
5276      CollectOverriddenMethods(*P, Method, Methods);
5277
5278    for (ObjCCategoryDecl *Category = Interface->getCategoryList();
5279         Category; Category = Category->getNextClassCategory())
5280      CollectOverriddenMethods(Category, Method, Methods);
5281
5282    // We only look into the superclass if we haven't found anything yet.
5283    if (Methods.empty())
5284      if (ObjCInterfaceDecl *Super = Interface->getSuperClass())
5285        return CollectOverriddenMethods(Super, Method, Methods);
5286  }
5287}
5288
5289void clang_getOverriddenCursors(CXCursor cursor,
5290                                CXCursor **overridden,
5291                                unsigned *num_overridden) {
5292  if (overridden)
5293    *overridden = 0;
5294  if (num_overridden)
5295    *num_overridden = 0;
5296  if (!overridden || !num_overridden)
5297    return;
5298
5299  if (!clang_isDeclaration(cursor.kind))
5300    return;
5301
5302  Decl *D = getCursorDecl(cursor);
5303  if (!D)
5304    return;
5305
5306  // Handle C++ member functions.
5307  CXTranslationUnit TU = getCursorTU(cursor);
5308  if (CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
5309    *num_overridden = CXXMethod->size_overridden_methods();
5310    if (!*num_overridden)
5311      return;
5312
5313    *overridden = new CXCursor [*num_overridden];
5314    unsigned I = 0;
5315    for (CXXMethodDecl::method_iterator
5316              M = CXXMethod->begin_overridden_methods(),
5317           MEnd = CXXMethod->end_overridden_methods();
5318         M != MEnd; (void)++M, ++I)
5319      (*overridden)[I] = MakeCXCursor(const_cast<CXXMethodDecl*>(*M), TU);
5320    return;
5321  }
5322
5323  ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
5324  if (!Method)
5325    return;
5326
5327  // Handle Objective-C methods.
5328  SmallVector<ObjCMethodDecl *, 4> Methods;
5329  CollectOverriddenMethods(Method->getDeclContext(), Method, Methods);
5330
5331  if (Methods.empty())
5332    return;
5333
5334  *num_overridden = Methods.size();
5335  *overridden = new CXCursor [Methods.size()];
5336  for (unsigned I = 0, N = Methods.size(); I != N; ++I)
5337    (*overridden)[I] = MakeCXCursor(Methods[I], TU);
5338}
5339
5340void clang_disposeOverriddenCursors(CXCursor *overridden) {
5341  delete [] overridden;
5342}
5343
5344CXFile clang_getIncludedFile(CXCursor cursor) {
5345  if (cursor.kind != CXCursor_InclusionDirective)
5346    return 0;
5347
5348  InclusionDirective *ID = getCursorInclusionDirective(cursor);
5349  return (void *)ID->getFile();
5350}
5351
5352} // end: extern "C"
5353
5354
5355//===----------------------------------------------------------------------===//
5356// C++ AST instrospection.
5357//===----------------------------------------------------------------------===//
5358
5359extern "C" {
5360unsigned clang_CXXMethod_isStatic(CXCursor C) {
5361  if (!clang_isDeclaration(C.kind))
5362    return 0;
5363
5364  CXXMethodDecl *Method = 0;
5365  Decl *D = cxcursor::getCursorDecl(C);
5366  if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
5367    Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
5368  else
5369    Method = dyn_cast_or_null<CXXMethodDecl>(D);
5370  return (Method && Method->isStatic()) ? 1 : 0;
5371}
5372
5373unsigned clang_CXXMethod_isVirtual(CXCursor C) {
5374  if (!clang_isDeclaration(C.kind))
5375    return 0;
5376
5377  CXXMethodDecl *Method = 0;
5378  Decl *D = cxcursor::getCursorDecl(C);
5379  if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
5380    Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
5381  else
5382    Method = dyn_cast_or_null<CXXMethodDecl>(D);
5383  return (Method && Method->isVirtual()) ? 1 : 0;
5384}
5385
5386} // end: extern "C"
5387
5388//===----------------------------------------------------------------------===//
5389// Attribute introspection.
5390//===----------------------------------------------------------------------===//
5391
5392extern "C" {
5393CXType clang_getIBOutletCollectionType(CXCursor C) {
5394  if (C.kind != CXCursor_IBOutletCollectionAttr)
5395    return cxtype::MakeCXType(QualType(), cxcursor::getCursorTU(C));
5396
5397  IBOutletCollectionAttr *A =
5398    cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
5399
5400  return cxtype::MakeCXType(A->getInterFace(), cxcursor::getCursorTU(C));
5401}
5402} // end: extern "C"
5403
5404//===----------------------------------------------------------------------===//
5405// Inspecting memory usage.
5406//===----------------------------------------------------------------------===//
5407
5408typedef std::vector<CXTUResourceUsageEntry> MemUsageEntries;
5409
5410static inline void createCXTUResourceUsageEntry(MemUsageEntries &entries,
5411                                              enum CXTUResourceUsageKind k,
5412                                              unsigned long amount) {
5413  CXTUResourceUsageEntry entry = { k, amount };
5414  entries.push_back(entry);
5415}
5416
5417extern "C" {
5418
5419const char *clang_getTUResourceUsageName(CXTUResourceUsageKind kind) {
5420  const char *str = "";
5421  switch (kind) {
5422    case CXTUResourceUsage_AST:
5423      str = "ASTContext: expressions, declarations, and types";
5424      break;
5425    case CXTUResourceUsage_Identifiers:
5426      str = "ASTContext: identifiers";
5427      break;
5428    case CXTUResourceUsage_Selectors:
5429      str = "ASTContext: selectors";
5430      break;
5431    case CXTUResourceUsage_GlobalCompletionResults:
5432      str = "Code completion: cached global results";
5433      break;
5434    case CXTUResourceUsage_SourceManagerContentCache:
5435      str = "SourceManager: content cache allocator";
5436      break;
5437    case CXTUResourceUsage_AST_SideTables:
5438      str = "ASTContext: side tables";
5439      break;
5440    case CXTUResourceUsage_SourceManager_Membuffer_Malloc:
5441      str = "SourceManager: malloc'ed memory buffers";
5442      break;
5443    case CXTUResourceUsage_SourceManager_Membuffer_MMap:
5444      str = "SourceManager: mmap'ed memory buffers";
5445      break;
5446    case CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc:
5447      str = "ExternalASTSource: malloc'ed memory buffers";
5448      break;
5449    case CXTUResourceUsage_ExternalASTSource_Membuffer_MMap:
5450      str = "ExternalASTSource: mmap'ed memory buffers";
5451      break;
5452    case CXTUResourceUsage_Preprocessor:
5453      str = "Preprocessor: malloc'ed memory";
5454      break;
5455    case CXTUResourceUsage_PreprocessingRecord:
5456      str = "Preprocessor: PreprocessingRecord";
5457      break;
5458  }
5459  return str;
5460}
5461
5462CXTUResourceUsage clang_getCXTUResourceUsage(CXTranslationUnit TU) {
5463  if (!TU) {
5464    CXTUResourceUsage usage = { (void*) 0, 0, 0 };
5465    return usage;
5466  }
5467
5468  ASTUnit *astUnit = static_cast<ASTUnit*>(TU->TUData);
5469  llvm::OwningPtr<MemUsageEntries> entries(new MemUsageEntries());
5470  ASTContext &astContext = astUnit->getASTContext();
5471
5472  // How much memory is used by AST nodes and types?
5473  createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST,
5474    (unsigned long) astContext.getASTAllocatedMemory());
5475
5476  // How much memory is used by identifiers?
5477  createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Identifiers,
5478    (unsigned long) astContext.Idents.getAllocator().getTotalMemory());
5479
5480  // How much memory is used for selectors?
5481  createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Selectors,
5482    (unsigned long) astContext.Selectors.getTotalMemory());
5483
5484  // How much memory is used by ASTContext's side tables?
5485  createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST_SideTables,
5486    (unsigned long) astContext.getSideTableAllocatedMemory());
5487
5488  // How much memory is used for caching global code completion results?
5489  unsigned long completionBytes = 0;
5490  if (GlobalCodeCompletionAllocator *completionAllocator =
5491      astUnit->getCachedCompletionAllocator().getPtr()) {
5492    completionBytes = completionAllocator->getTotalMemory();
5493  }
5494  createCXTUResourceUsageEntry(*entries,
5495                               CXTUResourceUsage_GlobalCompletionResults,
5496                               completionBytes);
5497
5498  // How much memory is being used by SourceManager's content cache?
5499  createCXTUResourceUsageEntry(*entries,
5500          CXTUResourceUsage_SourceManagerContentCache,
5501          (unsigned long) astContext.getSourceManager().getContentCacheSize());
5502
5503  // How much memory is being used by the MemoryBuffer's in SourceManager?
5504  const SourceManager::MemoryBufferSizes &srcBufs =
5505    astUnit->getSourceManager().getMemoryBufferSizes();
5506
5507  createCXTUResourceUsageEntry(*entries,
5508                               CXTUResourceUsage_SourceManager_Membuffer_Malloc,
5509                               (unsigned long) srcBufs.malloc_bytes);
5510    createCXTUResourceUsageEntry(*entries,
5511                               CXTUResourceUsage_SourceManager_Membuffer_MMap,
5512                               (unsigned long) srcBufs.mmap_bytes);
5513
5514  // How much memory is being used by the ExternalASTSource?
5515  if (ExternalASTSource *esrc = astContext.getExternalSource()) {
5516    const ExternalASTSource::MemoryBufferSizes &sizes =
5517      esrc->getMemoryBufferSizes();
5518
5519    createCXTUResourceUsageEntry(*entries,
5520      CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc,
5521                                 (unsigned long) sizes.malloc_bytes);
5522    createCXTUResourceUsageEntry(*entries,
5523      CXTUResourceUsage_ExternalASTSource_Membuffer_MMap,
5524                                 (unsigned long) sizes.mmap_bytes);
5525  }
5526
5527  // How much memory is being used by the Preprocessor?
5528  Preprocessor &pp = astUnit->getPreprocessor();
5529  createCXTUResourceUsageEntry(*entries,
5530                               CXTUResourceUsage_Preprocessor,
5531                               pp.getTotalMemory());
5532
5533  if (PreprocessingRecord *pRec = pp.getPreprocessingRecord()) {
5534    createCXTUResourceUsageEntry(*entries,
5535                                 CXTUResourceUsage_PreprocessingRecord,
5536                                 pRec->getTotalMemory());
5537  }
5538
5539
5540  CXTUResourceUsage usage = { (void*) entries.get(),
5541                            (unsigned) entries->size(),
5542                            entries->size() ? &(*entries)[0] : 0 };
5543  entries.take();
5544  return usage;
5545}
5546
5547void clang_disposeCXTUResourceUsage(CXTUResourceUsage usage) {
5548  if (usage.data)
5549    delete (MemUsageEntries*) usage.data;
5550}
5551
5552} // end extern "C"
5553
5554void clang::PrintLibclangResourceUsage(CXTranslationUnit TU) {
5555  CXTUResourceUsage Usage = clang_getCXTUResourceUsage(TU);
5556  for (unsigned I = 0; I != Usage.numEntries; ++I)
5557    fprintf(stderr, "  %s: %lu\n",
5558            clang_getTUResourceUsageName(Usage.entries[I].kind),
5559            Usage.entries[I].amount);
5560
5561  clang_disposeCXTUResourceUsage(Usage);
5562}
5563
5564//===----------------------------------------------------------------------===//
5565// Misc. utility functions.
5566//===----------------------------------------------------------------------===//
5567
5568/// Default to using an 8 MB stack size on "safety" threads.
5569static unsigned SafetyStackThreadSize = 8 << 20;
5570
5571namespace clang {
5572
5573bool RunSafely(llvm::CrashRecoveryContext &CRC,
5574               void (*Fn)(void*), void *UserData,
5575               unsigned Size) {
5576  if (!Size)
5577    Size = GetSafetyThreadStackSize();
5578  if (Size)
5579    return CRC.RunSafelyOnThread(Fn, UserData, Size);
5580  return CRC.RunSafely(Fn, UserData);
5581}
5582
5583unsigned GetSafetyThreadStackSize() {
5584  return SafetyStackThreadSize;
5585}
5586
5587void SetSafetyThreadStackSize(unsigned Value) {
5588  SafetyStackThreadSize = Value;
5589}
5590
5591}
5592
5593extern "C" {
5594
5595CXString clang_getClangVersion() {
5596  return createCXString(getClangFullVersion());
5597}
5598
5599} // end: extern "C"
5600
5601