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