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