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