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