CIndex.cpp revision 99ba202f659e1885fa5ee114f97c97cf6a857491
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         CXTranslationUnit_CXXPrecompiledPreamble;
1977}
1978
1979CXTranslationUnit
1980clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
1981                                          const char *source_filename,
1982                                          int num_command_line_args,
1983                                          const char * const *command_line_args,
1984                                          unsigned num_unsaved_files,
1985                                          struct CXUnsavedFile *unsaved_files) {
1986  return clang_parseTranslationUnit(CIdx, source_filename,
1987                                    command_line_args, num_command_line_args,
1988                                    unsaved_files, num_unsaved_files,
1989                                 CXTranslationUnit_DetailedPreprocessingRecord);
1990}
1991
1992struct ParseTranslationUnitInfo {
1993  CXIndex CIdx;
1994  const char *source_filename;
1995  const char *const *command_line_args;
1996  int num_command_line_args;
1997  struct CXUnsavedFile *unsaved_files;
1998  unsigned num_unsaved_files;
1999  unsigned options;
2000  CXTranslationUnit result;
2001};
2002static void clang_parseTranslationUnit_Impl(void *UserData) {
2003  ParseTranslationUnitInfo *PTUI =
2004    static_cast<ParseTranslationUnitInfo*>(UserData);
2005  CXIndex CIdx = PTUI->CIdx;
2006  const char *source_filename = PTUI->source_filename;
2007  const char * const *command_line_args = PTUI->command_line_args;
2008  int num_command_line_args = PTUI->num_command_line_args;
2009  struct CXUnsavedFile *unsaved_files = PTUI->unsaved_files;
2010  unsigned num_unsaved_files = PTUI->num_unsaved_files;
2011  unsigned options = PTUI->options;
2012  PTUI->result = 0;
2013
2014  if (!CIdx)
2015    return;
2016
2017  CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
2018
2019  bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
2020  bool CompleteTranslationUnit
2021    = ((options & CXTranslationUnit_Incomplete) == 0);
2022  bool CacheCodeCompetionResults
2023    = options & CXTranslationUnit_CacheCompletionResults;
2024  bool CXXPrecompilePreamble
2025    = options & CXTranslationUnit_CXXPrecompiledPreamble;
2026  bool CXXChainedPCH
2027    = options & CXTranslationUnit_CXXChainedPCH;
2028
2029  // Configure the diagnostics.
2030  DiagnosticOptions DiagOpts;
2031  llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
2032  Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
2033
2034  llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
2035  for (unsigned I = 0; I != num_unsaved_files; ++I) {
2036    llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
2037    const llvm::MemoryBuffer *Buffer
2038      = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
2039    RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
2040                                           Buffer));
2041  }
2042
2043  llvm::SmallVector<const char *, 16> Args;
2044
2045  // The 'source_filename' argument is optional.  If the caller does not
2046  // specify it then it is assumed that the source file is specified
2047  // in the actual argument list.
2048  if (source_filename)
2049    Args.push_back(source_filename);
2050
2051  // Since the Clang C library is primarily used by batch tools dealing with
2052  // (often very broken) source code, where spell-checking can have a
2053  // significant negative impact on performance (particularly when
2054  // precompiled headers are involved), we disable it by default.
2055  // Only do this if we haven't found a spell-checking-related argument.
2056  bool FoundSpellCheckingArgument = false;
2057  for (int I = 0; I != num_command_line_args; ++I) {
2058    if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
2059        strcmp(command_line_args[I], "-fspell-checking") == 0) {
2060      FoundSpellCheckingArgument = true;
2061      break;
2062    }
2063  }
2064  if (!FoundSpellCheckingArgument)
2065    Args.push_back("-fno-spell-checking");
2066
2067  Args.insert(Args.end(), command_line_args,
2068              command_line_args + num_command_line_args);
2069
2070  // Do we need the detailed preprocessing record?
2071  if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
2072    Args.push_back("-Xclang");
2073    Args.push_back("-detailed-preprocessing-record");
2074  }
2075
2076  unsigned NumErrors = Diags->getNumErrors();
2077
2078#ifdef USE_CRASHTRACER
2079  ArgsCrashTracerInfo ACTI(Args);
2080#endif
2081
2082  llvm::OwningPtr<ASTUnit> Unit(
2083    ASTUnit::LoadFromCommandLine(Args.data(), Args.data() + Args.size(),
2084                                 Diags,
2085                                 CXXIdx->getClangResourcesPath(),
2086                                 CXXIdx->getOnlyLocalDecls(),
2087                                 RemappedFiles.data(),
2088                                 RemappedFiles.size(),
2089                                 /*CaptureDiagnostics=*/true,
2090                                 PrecompilePreamble,
2091                                 CompleteTranslationUnit,
2092                                 CacheCodeCompetionResults,
2093                                 CXXPrecompilePreamble,
2094                                 CXXChainedPCH));
2095
2096  if (NumErrors != Diags->getNumErrors()) {
2097    // Make sure to check that 'Unit' is non-NULL.
2098    if (CXXIdx->getDisplayDiagnostics() && Unit.get()) {
2099      for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
2100                                      DEnd = Unit->stored_diag_end();
2101           D != DEnd; ++D) {
2102        CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOptions());
2103        CXString Msg = clang_formatDiagnostic(&Diag,
2104                                    clang_defaultDiagnosticDisplayOptions());
2105        fprintf(stderr, "%s\n", clang_getCString(Msg));
2106        clang_disposeString(Msg);
2107      }
2108#ifdef LLVM_ON_WIN32
2109      // On Windows, force a flush, since there may be multiple copies of
2110      // stderr and stdout in the file system, all with different buffers
2111      // but writing to the same device.
2112      fflush(stderr);
2113#endif
2114    }
2115  }
2116
2117  PTUI->result = Unit.take();
2118}
2119CXTranslationUnit clang_parseTranslationUnit(CXIndex CIdx,
2120                                             const char *source_filename,
2121                                         const char * const *command_line_args,
2122                                             int num_command_line_args,
2123                                             struct CXUnsavedFile *unsaved_files,
2124                                             unsigned num_unsaved_files,
2125                                             unsigned options) {
2126  ParseTranslationUnitInfo PTUI = { CIdx, source_filename, command_line_args,
2127                                    num_command_line_args, unsaved_files, num_unsaved_files,
2128                                    options, 0 };
2129  llvm::CrashRecoveryContext CRC;
2130
2131  if (!CRC.RunSafely(clang_parseTranslationUnit_Impl, &PTUI)) {
2132    fprintf(stderr, "libclang: crash detected during parsing: {\n");
2133    fprintf(stderr, "  'source_filename' : '%s'\n", source_filename);
2134    fprintf(stderr, "  'command_line_args' : [");
2135    for (int i = 0; i != num_command_line_args; ++i) {
2136      if (i)
2137        fprintf(stderr, ", ");
2138      fprintf(stderr, "'%s'", command_line_args[i]);
2139    }
2140    fprintf(stderr, "],\n");
2141    fprintf(stderr, "  'unsaved_files' : [");
2142    for (unsigned i = 0; i != num_unsaved_files; ++i) {
2143      if (i)
2144        fprintf(stderr, ", ");
2145      fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
2146              unsaved_files[i].Length);
2147    }
2148    fprintf(stderr, "],\n");
2149    fprintf(stderr, "  'options' : %d,\n", options);
2150    fprintf(stderr, "}\n");
2151
2152    return 0;
2153  }
2154
2155  return PTUI.result;
2156}
2157
2158unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
2159  return CXSaveTranslationUnit_None;
2160}
2161
2162int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
2163                              unsigned options) {
2164  if (!TU)
2165    return 1;
2166
2167  return static_cast<ASTUnit *>(TU)->Save(FileName);
2168}
2169
2170void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
2171  if (CTUnit) {
2172    // If the translation unit has been marked as unsafe to free, just discard
2173    // it.
2174    if (static_cast<ASTUnit *>(CTUnit)->isUnsafeToFree())
2175      return;
2176
2177    delete static_cast<ASTUnit *>(CTUnit);
2178  }
2179}
2180
2181unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
2182  return CXReparse_None;
2183}
2184
2185struct ReparseTranslationUnitInfo {
2186  CXTranslationUnit TU;
2187  unsigned num_unsaved_files;
2188  struct CXUnsavedFile *unsaved_files;
2189  unsigned options;
2190  int result;
2191};
2192
2193static void clang_reparseTranslationUnit_Impl(void *UserData) {
2194  ReparseTranslationUnitInfo *RTUI =
2195    static_cast<ReparseTranslationUnitInfo*>(UserData);
2196  CXTranslationUnit TU = RTUI->TU;
2197  unsigned num_unsaved_files = RTUI->num_unsaved_files;
2198  struct CXUnsavedFile *unsaved_files = RTUI->unsaved_files;
2199  unsigned options = RTUI->options;
2200  (void) options;
2201  RTUI->result = 1;
2202
2203  if (!TU)
2204    return;
2205
2206  ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2207  ASTUnit::ConcurrencyCheck Check(*CXXUnit);
2208
2209  llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
2210  for (unsigned I = 0; I != num_unsaved_files; ++I) {
2211    llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
2212    const llvm::MemoryBuffer *Buffer
2213      = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
2214    RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
2215                                           Buffer));
2216  }
2217
2218  if (!CXXUnit->Reparse(RemappedFiles.data(), RemappedFiles.size()))
2219    RTUI->result = 0;
2220}
2221
2222int clang_reparseTranslationUnit(CXTranslationUnit TU,
2223                                 unsigned num_unsaved_files,
2224                                 struct CXUnsavedFile *unsaved_files,
2225                                 unsigned options) {
2226  ReparseTranslationUnitInfo RTUI = { TU, num_unsaved_files, unsaved_files,
2227                                      options, 0 };
2228  llvm::CrashRecoveryContext CRC;
2229
2230  if (!CRC.RunSafely(clang_reparseTranslationUnit_Impl, &RTUI)) {
2231    fprintf(stderr, "libclang: crash detected during reparsing\n");
2232    static_cast<ASTUnit *>(TU)->setUnsafeToFree(true);
2233    return 1;
2234  }
2235
2236  return RTUI.result;
2237}
2238
2239
2240CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
2241  if (!CTUnit)
2242    return createCXString("");
2243
2244  ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit);
2245  return createCXString(CXXUnit->getOriginalSourceFileName(), true);
2246}
2247
2248CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
2249  CXCursor Result = { CXCursor_TranslationUnit, { 0, 0, TU } };
2250  return Result;
2251}
2252
2253} // end: extern "C"
2254
2255//===----------------------------------------------------------------------===//
2256// CXSourceLocation and CXSourceRange Operations.
2257//===----------------------------------------------------------------------===//
2258
2259extern "C" {
2260CXSourceLocation clang_getNullLocation() {
2261  CXSourceLocation Result = { { 0, 0 }, 0 };
2262  return Result;
2263}
2264
2265unsigned clang_equalLocations(CXSourceLocation loc1, CXSourceLocation loc2) {
2266  return (loc1.ptr_data[0] == loc2.ptr_data[0] &&
2267          loc1.ptr_data[1] == loc2.ptr_data[1] &&
2268          loc1.int_data == loc2.int_data);
2269}
2270
2271CXSourceLocation clang_getLocation(CXTranslationUnit tu,
2272                                   CXFile file,
2273                                   unsigned line,
2274                                   unsigned column) {
2275  if (!tu || !file)
2276    return clang_getNullLocation();
2277
2278  ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
2279  SourceLocation SLoc
2280    = CXXUnit->getSourceManager().getLocation(
2281                                        static_cast<const FileEntry *>(file),
2282                                              line, column);
2283  if (SLoc.isInvalid()) return clang_getNullLocation();
2284
2285  return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
2286}
2287
2288CXSourceLocation clang_getLocationForOffset(CXTranslationUnit tu,
2289                                            CXFile file,
2290                                            unsigned offset) {
2291  if (!tu || !file)
2292    return clang_getNullLocation();
2293
2294  ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
2295  SourceLocation Start
2296    = CXXUnit->getSourceManager().getLocation(
2297                                        static_cast<const FileEntry *>(file),
2298                                              1, 1);
2299  if (Start.isInvalid()) return clang_getNullLocation();
2300
2301  SourceLocation SLoc = Start.getFileLocWithOffset(offset);
2302
2303  if (SLoc.isInvalid()) return clang_getNullLocation();
2304
2305  return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
2306}
2307
2308CXSourceRange clang_getNullRange() {
2309  CXSourceRange Result = { { 0, 0 }, 0, 0 };
2310  return Result;
2311}
2312
2313CXSourceRange clang_getRange(CXSourceLocation begin, CXSourceLocation end) {
2314  if (begin.ptr_data[0] != end.ptr_data[0] ||
2315      begin.ptr_data[1] != end.ptr_data[1])
2316    return clang_getNullRange();
2317
2318  CXSourceRange Result = { { begin.ptr_data[0], begin.ptr_data[1] },
2319                           begin.int_data, end.int_data };
2320  return Result;
2321}
2322
2323void clang_getInstantiationLocation(CXSourceLocation location,
2324                                    CXFile *file,
2325                                    unsigned *line,
2326                                    unsigned *column,
2327                                    unsigned *offset) {
2328  SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2329
2330  if (!location.ptr_data[0] || Loc.isInvalid()) {
2331    if (file)
2332      *file = 0;
2333    if (line)
2334      *line = 0;
2335    if (column)
2336      *column = 0;
2337    if (offset)
2338      *offset = 0;
2339    return;
2340  }
2341
2342  const SourceManager &SM =
2343    *static_cast<const SourceManager*>(location.ptr_data[0]);
2344  SourceLocation InstLoc = SM.getInstantiationLoc(Loc);
2345
2346  if (file)
2347    *file = (void *)SM.getFileEntryForID(SM.getFileID(InstLoc));
2348  if (line)
2349    *line = SM.getInstantiationLineNumber(InstLoc);
2350  if (column)
2351    *column = SM.getInstantiationColumnNumber(InstLoc);
2352  if (offset)
2353    *offset = SM.getDecomposedLoc(InstLoc).second;
2354}
2355
2356CXSourceLocation clang_getRangeStart(CXSourceRange range) {
2357  CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
2358                              range.begin_int_data };
2359  return Result;
2360}
2361
2362CXSourceLocation clang_getRangeEnd(CXSourceRange range) {
2363  CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
2364                              range.end_int_data };
2365  return Result;
2366}
2367
2368} // end: extern "C"
2369
2370//===----------------------------------------------------------------------===//
2371// CXFile Operations.
2372//===----------------------------------------------------------------------===//
2373
2374extern "C" {
2375CXString clang_getFileName(CXFile SFile) {
2376  if (!SFile)
2377    return createCXString(NULL);
2378
2379  FileEntry *FEnt = static_cast<FileEntry *>(SFile);
2380  return createCXString(FEnt->getName());
2381}
2382
2383time_t clang_getFileTime(CXFile SFile) {
2384  if (!SFile)
2385    return 0;
2386
2387  FileEntry *FEnt = static_cast<FileEntry *>(SFile);
2388  return FEnt->getModificationTime();
2389}
2390
2391CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
2392  if (!tu)
2393    return 0;
2394
2395  ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
2396
2397  FileManager &FMgr = CXXUnit->getFileManager();
2398  const FileEntry *File = FMgr.getFile(file_name, file_name+strlen(file_name));
2399  return const_cast<FileEntry *>(File);
2400}
2401
2402} // end: extern "C"
2403
2404//===----------------------------------------------------------------------===//
2405// CXCursor Operations.
2406//===----------------------------------------------------------------------===//
2407
2408static Decl *getDeclFromExpr(Stmt *E) {
2409  if (CastExpr *CE = dyn_cast<CastExpr>(E))
2410    return getDeclFromExpr(CE->getSubExpr());
2411
2412  if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
2413    return RefExpr->getDecl();
2414  if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2415    return RefExpr->getDecl();
2416  if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
2417    return ME->getMemberDecl();
2418  if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
2419    return RE->getDecl();
2420  if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E))
2421    return PRE->getProperty();
2422
2423  if (CallExpr *CE = dyn_cast<CallExpr>(E))
2424    return getDeclFromExpr(CE->getCallee());
2425  if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
2426    return OME->getMethodDecl();
2427
2428  if (ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
2429    return PE->getProtocol();
2430
2431  return 0;
2432}
2433
2434static SourceLocation getLocationFromExpr(Expr *E) {
2435  if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
2436    return /*FIXME:*/Msg->getLeftLoc();
2437  if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
2438    return DRE->getLocation();
2439  if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2440    return RefExpr->getLocation();
2441  if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
2442    return Member->getMemberLoc();
2443  if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
2444    return Ivar->getLocation();
2445  return E->getLocStart();
2446}
2447
2448extern "C" {
2449
2450unsigned clang_visitChildren(CXCursor parent,
2451                             CXCursorVisitor visitor,
2452                             CXClientData client_data) {
2453  ASTUnit *CXXUnit = getCursorASTUnit(parent);
2454
2455  CursorVisitor CursorVis(CXXUnit, visitor, client_data,
2456                          CXXUnit->getMaxPCHLevel());
2457  return CursorVis.VisitChildren(parent);
2458}
2459
2460static CXString getDeclSpelling(Decl *D) {
2461  NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
2462  if (!ND)
2463    return createCXString("");
2464
2465  if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
2466    return createCXString(OMD->getSelector().getAsString());
2467
2468  if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
2469    // No, this isn't the same as the code below. getIdentifier() is non-virtual
2470    // and returns different names. NamedDecl returns the class name and
2471    // ObjCCategoryImplDecl returns the category name.
2472    return createCXString(CIMP->getIdentifier()->getNameStart());
2473
2474  if (isa<UsingDirectiveDecl>(D))
2475    return createCXString("");
2476
2477  llvm::SmallString<1024> S;
2478  llvm::raw_svector_ostream os(S);
2479  ND->printName(os);
2480
2481  return createCXString(os.str());
2482}
2483
2484CXString clang_getCursorSpelling(CXCursor C) {
2485  if (clang_isTranslationUnit(C.kind))
2486    return clang_getTranslationUnitSpelling(C.data[2]);
2487
2488  if (clang_isReference(C.kind)) {
2489    switch (C.kind) {
2490    case CXCursor_ObjCSuperClassRef: {
2491      ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
2492      return createCXString(Super->getIdentifier()->getNameStart());
2493    }
2494    case CXCursor_ObjCClassRef: {
2495      ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
2496      return createCXString(Class->getIdentifier()->getNameStart());
2497    }
2498    case CXCursor_ObjCProtocolRef: {
2499      ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
2500      assert(OID && "getCursorSpelling(): Missing protocol decl");
2501      return createCXString(OID->getIdentifier()->getNameStart());
2502    }
2503    case CXCursor_CXXBaseSpecifier: {
2504      CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
2505      return createCXString(B->getType().getAsString());
2506    }
2507    case CXCursor_TypeRef: {
2508      TypeDecl *Type = getCursorTypeRef(C).first;
2509      assert(Type && "Missing type decl");
2510
2511      return createCXString(getCursorContext(C).getTypeDeclType(Type).
2512                              getAsString());
2513    }
2514    case CXCursor_TemplateRef: {
2515      TemplateDecl *Template = getCursorTemplateRef(C).first;
2516      assert(Template && "Missing template decl");
2517
2518      return createCXString(Template->getNameAsString());
2519    }
2520
2521    case CXCursor_NamespaceRef: {
2522      NamedDecl *NS = getCursorNamespaceRef(C).first;
2523      assert(NS && "Missing namespace decl");
2524
2525      return createCXString(NS->getNameAsString());
2526    }
2527
2528    case CXCursor_MemberRef: {
2529      FieldDecl *Field = getCursorMemberRef(C).first;
2530      assert(Field && "Missing member decl");
2531
2532      return createCXString(Field->getNameAsString());
2533    }
2534
2535    case CXCursor_LabelRef: {
2536      LabelStmt *Label = getCursorLabelRef(C).first;
2537      assert(Label && "Missing label");
2538
2539      return createCXString(Label->getID()->getName());
2540    }
2541
2542    case CXCursor_OverloadedDeclRef: {
2543      OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
2544      if (Decl *D = Storage.dyn_cast<Decl *>()) {
2545        if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
2546          return createCXString(ND->getNameAsString());
2547        return createCXString("");
2548      }
2549      if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
2550        return createCXString(E->getName().getAsString());
2551      OverloadedTemplateStorage *Ovl
2552        = Storage.get<OverloadedTemplateStorage*>();
2553      if (Ovl->size() == 0)
2554        return createCXString("");
2555      return createCXString((*Ovl->begin())->getNameAsString());
2556    }
2557
2558    default:
2559      return createCXString("<not implemented>");
2560    }
2561  }
2562
2563  if (clang_isExpression(C.kind)) {
2564    Decl *D = getDeclFromExpr(getCursorExpr(C));
2565    if (D)
2566      return getDeclSpelling(D);
2567    return createCXString("");
2568  }
2569
2570  if (clang_isStatement(C.kind)) {
2571    Stmt *S = getCursorStmt(C);
2572    if (LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
2573      return createCXString(Label->getID()->getName());
2574
2575    return createCXString("");
2576  }
2577
2578  if (C.kind == CXCursor_MacroInstantiation)
2579    return createCXString(getCursorMacroInstantiation(C)->getName()
2580                                                           ->getNameStart());
2581
2582  if (C.kind == CXCursor_MacroDefinition)
2583    return createCXString(getCursorMacroDefinition(C)->getName()
2584                                                           ->getNameStart());
2585
2586  if (C.kind == CXCursor_InclusionDirective)
2587    return createCXString(getCursorInclusionDirective(C)->getFileName());
2588
2589  if (clang_isDeclaration(C.kind))
2590    return getDeclSpelling(getCursorDecl(C));
2591
2592  return createCXString("");
2593}
2594
2595CXString clang_getCursorDisplayName(CXCursor C) {
2596  if (!clang_isDeclaration(C.kind))
2597    return clang_getCursorSpelling(C);
2598
2599  Decl *D = getCursorDecl(C);
2600  if (!D)
2601    return createCXString("");
2602
2603  PrintingPolicy &Policy = getCursorContext(C).PrintingPolicy;
2604  if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
2605    D = FunTmpl->getTemplatedDecl();
2606
2607  if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
2608    llvm::SmallString<64> Str;
2609    llvm::raw_svector_ostream OS(Str);
2610    OS << Function->getNameAsString();
2611    if (Function->getPrimaryTemplate())
2612      OS << "<>";
2613    OS << "(";
2614    for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
2615      if (I)
2616        OS << ", ";
2617      OS << Function->getParamDecl(I)->getType().getAsString(Policy);
2618    }
2619
2620    if (Function->isVariadic()) {
2621      if (Function->getNumParams())
2622        OS << ", ";
2623      OS << "...";
2624    }
2625    OS << ")";
2626    return createCXString(OS.str());
2627  }
2628
2629  if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
2630    llvm::SmallString<64> Str;
2631    llvm::raw_svector_ostream OS(Str);
2632    OS << ClassTemplate->getNameAsString();
2633    OS << "<";
2634    TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
2635    for (unsigned I = 0, N = Params->size(); I != N; ++I) {
2636      if (I)
2637        OS << ", ";
2638
2639      NamedDecl *Param = Params->getParam(I);
2640      if (Param->getIdentifier()) {
2641        OS << Param->getIdentifier()->getName();
2642        continue;
2643      }
2644
2645      // There is no parameter name, which makes this tricky. Try to come up
2646      // with something useful that isn't too long.
2647      if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
2648        OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
2649      else if (NonTypeTemplateParmDecl *NTTP
2650                                    = dyn_cast<NonTypeTemplateParmDecl>(Param))
2651        OS << NTTP->getType().getAsString(Policy);
2652      else
2653        OS << "template<...> class";
2654    }
2655
2656    OS << ">";
2657    return createCXString(OS.str());
2658  }
2659
2660  if (ClassTemplateSpecializationDecl *ClassSpec
2661                              = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
2662    // If the type was explicitly written, use that.
2663    if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
2664      return createCXString(TSInfo->getType().getAsString(Policy));
2665
2666    llvm::SmallString<64> Str;
2667    llvm::raw_svector_ostream OS(Str);
2668    OS << ClassSpec->getNameAsString();
2669    OS << TemplateSpecializationType::PrintTemplateArgumentList(
2670                            ClassSpec->getTemplateArgs().getFlatArgumentList(),
2671                                      ClassSpec->getTemplateArgs().flat_size(),
2672                                                                Policy);
2673    return createCXString(OS.str());
2674  }
2675
2676  return clang_getCursorSpelling(C);
2677}
2678
2679CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
2680  switch (Kind) {
2681  case CXCursor_FunctionDecl:
2682      return createCXString("FunctionDecl");
2683  case CXCursor_TypedefDecl:
2684      return createCXString("TypedefDecl");
2685  case CXCursor_EnumDecl:
2686      return createCXString("EnumDecl");
2687  case CXCursor_EnumConstantDecl:
2688      return createCXString("EnumConstantDecl");
2689  case CXCursor_StructDecl:
2690      return createCXString("StructDecl");
2691  case CXCursor_UnionDecl:
2692      return createCXString("UnionDecl");
2693  case CXCursor_ClassDecl:
2694      return createCXString("ClassDecl");
2695  case CXCursor_FieldDecl:
2696      return createCXString("FieldDecl");
2697  case CXCursor_VarDecl:
2698      return createCXString("VarDecl");
2699  case CXCursor_ParmDecl:
2700      return createCXString("ParmDecl");
2701  case CXCursor_ObjCInterfaceDecl:
2702      return createCXString("ObjCInterfaceDecl");
2703  case CXCursor_ObjCCategoryDecl:
2704      return createCXString("ObjCCategoryDecl");
2705  case CXCursor_ObjCProtocolDecl:
2706      return createCXString("ObjCProtocolDecl");
2707  case CXCursor_ObjCPropertyDecl:
2708      return createCXString("ObjCPropertyDecl");
2709  case CXCursor_ObjCIvarDecl:
2710      return createCXString("ObjCIvarDecl");
2711  case CXCursor_ObjCInstanceMethodDecl:
2712      return createCXString("ObjCInstanceMethodDecl");
2713  case CXCursor_ObjCClassMethodDecl:
2714      return createCXString("ObjCClassMethodDecl");
2715  case CXCursor_ObjCImplementationDecl:
2716      return createCXString("ObjCImplementationDecl");
2717  case CXCursor_ObjCCategoryImplDecl:
2718      return createCXString("ObjCCategoryImplDecl");
2719  case CXCursor_CXXMethod:
2720      return createCXString("CXXMethod");
2721  case CXCursor_UnexposedDecl:
2722      return createCXString("UnexposedDecl");
2723  case CXCursor_ObjCSuperClassRef:
2724      return createCXString("ObjCSuperClassRef");
2725  case CXCursor_ObjCProtocolRef:
2726      return createCXString("ObjCProtocolRef");
2727  case CXCursor_ObjCClassRef:
2728      return createCXString("ObjCClassRef");
2729  case CXCursor_TypeRef:
2730      return createCXString("TypeRef");
2731  case CXCursor_TemplateRef:
2732      return createCXString("TemplateRef");
2733  case CXCursor_NamespaceRef:
2734    return createCXString("NamespaceRef");
2735  case CXCursor_MemberRef:
2736    return createCXString("MemberRef");
2737  case CXCursor_LabelRef:
2738    return createCXString("LabelRef");
2739  case CXCursor_OverloadedDeclRef:
2740    return createCXString("OverloadedDeclRef");
2741  case CXCursor_UnexposedExpr:
2742      return createCXString("UnexposedExpr");
2743  case CXCursor_BlockExpr:
2744      return createCXString("BlockExpr");
2745  case CXCursor_DeclRefExpr:
2746      return createCXString("DeclRefExpr");
2747  case CXCursor_MemberRefExpr:
2748      return createCXString("MemberRefExpr");
2749  case CXCursor_CallExpr:
2750      return createCXString("CallExpr");
2751  case CXCursor_ObjCMessageExpr:
2752      return createCXString("ObjCMessageExpr");
2753  case CXCursor_UnexposedStmt:
2754      return createCXString("UnexposedStmt");
2755  case CXCursor_LabelStmt:
2756      return createCXString("LabelStmt");
2757  case CXCursor_InvalidFile:
2758      return createCXString("InvalidFile");
2759  case CXCursor_InvalidCode:
2760    return createCXString("InvalidCode");
2761  case CXCursor_NoDeclFound:
2762      return createCXString("NoDeclFound");
2763  case CXCursor_NotImplemented:
2764      return createCXString("NotImplemented");
2765  case CXCursor_TranslationUnit:
2766      return createCXString("TranslationUnit");
2767  case CXCursor_UnexposedAttr:
2768      return createCXString("UnexposedAttr");
2769  case CXCursor_IBActionAttr:
2770      return createCXString("attribute(ibaction)");
2771  case CXCursor_IBOutletAttr:
2772     return createCXString("attribute(iboutlet)");
2773  case CXCursor_IBOutletCollectionAttr:
2774      return createCXString("attribute(iboutletcollection)");
2775  case CXCursor_PreprocessingDirective:
2776    return createCXString("preprocessing directive");
2777  case CXCursor_MacroDefinition:
2778    return createCXString("macro definition");
2779  case CXCursor_MacroInstantiation:
2780    return createCXString("macro instantiation");
2781  case CXCursor_InclusionDirective:
2782    return createCXString("inclusion directive");
2783  case CXCursor_Namespace:
2784    return createCXString("Namespace");
2785  case CXCursor_LinkageSpec:
2786    return createCXString("LinkageSpec");
2787  case CXCursor_CXXBaseSpecifier:
2788    return createCXString("C++ base class specifier");
2789  case CXCursor_Constructor:
2790    return createCXString("CXXConstructor");
2791  case CXCursor_Destructor:
2792    return createCXString("CXXDestructor");
2793  case CXCursor_ConversionFunction:
2794    return createCXString("CXXConversion");
2795  case CXCursor_TemplateTypeParameter:
2796    return createCXString("TemplateTypeParameter");
2797  case CXCursor_NonTypeTemplateParameter:
2798    return createCXString("NonTypeTemplateParameter");
2799  case CXCursor_TemplateTemplateParameter:
2800    return createCXString("TemplateTemplateParameter");
2801  case CXCursor_FunctionTemplate:
2802    return createCXString("FunctionTemplate");
2803  case CXCursor_ClassTemplate:
2804    return createCXString("ClassTemplate");
2805  case CXCursor_ClassTemplatePartialSpecialization:
2806    return createCXString("ClassTemplatePartialSpecialization");
2807  case CXCursor_NamespaceAlias:
2808    return createCXString("NamespaceAlias");
2809  case CXCursor_UsingDirective:
2810    return createCXString("UsingDirective");
2811  case CXCursor_UsingDeclaration:
2812    return createCXString("UsingDeclaration");
2813  }
2814
2815  llvm_unreachable("Unhandled CXCursorKind");
2816  return createCXString(NULL);
2817}
2818
2819enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
2820                                         CXCursor parent,
2821                                         CXClientData client_data) {
2822  CXCursor *BestCursor = static_cast<CXCursor *>(client_data);
2823  *BestCursor = cursor;
2824  return CXChildVisit_Recurse;
2825}
2826
2827CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
2828  if (!TU)
2829    return clang_getNullCursor();
2830
2831  ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2832  ASTUnit::ConcurrencyCheck Check(*CXXUnit);
2833
2834  // Translate the given source location to make it point at the beginning of
2835  // the token under the cursor.
2836  SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
2837
2838  // Guard against an invalid SourceLocation, or we may assert in one
2839  // of the following calls.
2840  if (SLoc.isInvalid())
2841    return clang_getNullCursor();
2842
2843  SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
2844                                    CXXUnit->getASTContext().getLangOptions());
2845
2846  CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
2847  if (SLoc.isValid()) {
2848    // FIXME: Would be great to have a "hint" cursor, then walk from that
2849    // hint cursor upward until we find a cursor whose source range encloses
2850    // the region of interest, rather than starting from the translation unit.
2851    CXCursor Parent = clang_getTranslationUnitCursor(CXXUnit);
2852    CursorVisitor CursorVis(CXXUnit, GetCursorVisitor, &Result,
2853                            Decl::MaxPCHLevel, SourceLocation(SLoc));
2854    CursorVis.VisitChildren(Parent);
2855  }
2856  return Result;
2857}
2858
2859CXCursor clang_getNullCursor(void) {
2860  return MakeCXCursorInvalid(CXCursor_InvalidFile);
2861}
2862
2863unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
2864  return X == Y;
2865}
2866
2867unsigned clang_isInvalid(enum CXCursorKind K) {
2868  return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
2869}
2870
2871unsigned clang_isDeclaration(enum CXCursorKind K) {
2872  return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
2873}
2874
2875unsigned clang_isReference(enum CXCursorKind K) {
2876  return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
2877}
2878
2879unsigned clang_isExpression(enum CXCursorKind K) {
2880  return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
2881}
2882
2883unsigned clang_isStatement(enum CXCursorKind K) {
2884  return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
2885}
2886
2887unsigned clang_isTranslationUnit(enum CXCursorKind K) {
2888  return K == CXCursor_TranslationUnit;
2889}
2890
2891unsigned clang_isPreprocessing(enum CXCursorKind K) {
2892  return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
2893}
2894
2895unsigned clang_isUnexposed(enum CXCursorKind K) {
2896  switch (K) {
2897    case CXCursor_UnexposedDecl:
2898    case CXCursor_UnexposedExpr:
2899    case CXCursor_UnexposedStmt:
2900    case CXCursor_UnexposedAttr:
2901      return true;
2902    default:
2903      return false;
2904  }
2905}
2906
2907CXCursorKind clang_getCursorKind(CXCursor C) {
2908  return C.kind;
2909}
2910
2911CXSourceLocation clang_getCursorLocation(CXCursor C) {
2912  if (clang_isReference(C.kind)) {
2913    switch (C.kind) {
2914    case CXCursor_ObjCSuperClassRef: {
2915      std::pair<ObjCInterfaceDecl *, SourceLocation> P
2916        = getCursorObjCSuperClassRef(C);
2917      return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
2918    }
2919
2920    case CXCursor_ObjCProtocolRef: {
2921      std::pair<ObjCProtocolDecl *, SourceLocation> P
2922        = getCursorObjCProtocolRef(C);
2923      return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
2924    }
2925
2926    case CXCursor_ObjCClassRef: {
2927      std::pair<ObjCInterfaceDecl *, SourceLocation> P
2928        = getCursorObjCClassRef(C);
2929      return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
2930    }
2931
2932    case CXCursor_TypeRef: {
2933      std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
2934      return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
2935    }
2936
2937    case CXCursor_TemplateRef: {
2938      std::pair<TemplateDecl *, SourceLocation> P = getCursorTemplateRef(C);
2939      return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
2940    }
2941
2942    case CXCursor_NamespaceRef: {
2943      std::pair<NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
2944      return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
2945    }
2946
2947    case CXCursor_MemberRef: {
2948      std::pair<FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
2949      return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
2950    }
2951
2952    case CXCursor_CXXBaseSpecifier: {
2953      CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
2954      if (!BaseSpec)
2955        return clang_getNullLocation();
2956
2957      if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
2958        return cxloc::translateSourceLocation(getCursorContext(C),
2959                                            TSInfo->getTypeLoc().getBeginLoc());
2960
2961      return cxloc::translateSourceLocation(getCursorContext(C),
2962                                        BaseSpec->getSourceRange().getBegin());
2963    }
2964
2965    case CXCursor_LabelRef: {
2966      std::pair<LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
2967      return cxloc::translateSourceLocation(getCursorContext(C), P.second);
2968    }
2969
2970    case CXCursor_OverloadedDeclRef:
2971      return cxloc::translateSourceLocation(getCursorContext(C),
2972                                          getCursorOverloadedDeclRef(C).second);
2973
2974    default:
2975      // FIXME: Need a way to enumerate all non-reference cases.
2976      llvm_unreachable("Missed a reference kind");
2977    }
2978  }
2979
2980  if (clang_isExpression(C.kind))
2981    return cxloc::translateSourceLocation(getCursorContext(C),
2982                                   getLocationFromExpr(getCursorExpr(C)));
2983
2984  if (clang_isStatement(C.kind))
2985    return cxloc::translateSourceLocation(getCursorContext(C),
2986                                          getCursorStmt(C)->getLocStart());
2987
2988  if (C.kind == CXCursor_PreprocessingDirective) {
2989    SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
2990    return cxloc::translateSourceLocation(getCursorContext(C), L);
2991  }
2992
2993  if (C.kind == CXCursor_MacroInstantiation) {
2994    SourceLocation L
2995      = cxcursor::getCursorMacroInstantiation(C)->getSourceRange().getBegin();
2996    return cxloc::translateSourceLocation(getCursorContext(C), L);
2997  }
2998
2999  if (C.kind == CXCursor_MacroDefinition) {
3000    SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
3001    return cxloc::translateSourceLocation(getCursorContext(C), L);
3002  }
3003
3004  if (C.kind == CXCursor_InclusionDirective) {
3005    SourceLocation L
3006      = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
3007    return cxloc::translateSourceLocation(getCursorContext(C), L);
3008  }
3009
3010  if (C.kind < CXCursor_FirstDecl || C.kind > CXCursor_LastDecl)
3011    return clang_getNullLocation();
3012
3013  Decl *D = getCursorDecl(C);
3014  SourceLocation Loc = D->getLocation();
3015  if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
3016    Loc = Class->getClassLoc();
3017  return cxloc::translateSourceLocation(getCursorContext(C), Loc);
3018}
3019
3020} // end extern "C"
3021
3022static SourceRange getRawCursorExtent(CXCursor C) {
3023  if (clang_isReference(C.kind)) {
3024    switch (C.kind) {
3025    case CXCursor_ObjCSuperClassRef:
3026      return  getCursorObjCSuperClassRef(C).second;
3027
3028    case CXCursor_ObjCProtocolRef:
3029      return getCursorObjCProtocolRef(C).second;
3030
3031    case CXCursor_ObjCClassRef:
3032      return getCursorObjCClassRef(C).second;
3033
3034    case CXCursor_TypeRef:
3035      return getCursorTypeRef(C).second;
3036
3037    case CXCursor_TemplateRef:
3038      return getCursorTemplateRef(C).second;
3039
3040    case CXCursor_NamespaceRef:
3041      return getCursorNamespaceRef(C).second;
3042
3043    case CXCursor_MemberRef:
3044      return getCursorMemberRef(C).second;
3045
3046    case CXCursor_CXXBaseSpecifier:
3047      return getCursorCXXBaseSpecifier(C)->getSourceRange();
3048
3049    case CXCursor_LabelRef:
3050      return getCursorLabelRef(C).second;
3051
3052    case CXCursor_OverloadedDeclRef:
3053      return getCursorOverloadedDeclRef(C).second;
3054
3055    default:
3056      // FIXME: Need a way to enumerate all non-reference cases.
3057      llvm_unreachable("Missed a reference kind");
3058    }
3059  }
3060
3061  if (clang_isExpression(C.kind))
3062    return getCursorExpr(C)->getSourceRange();
3063
3064  if (clang_isStatement(C.kind))
3065    return getCursorStmt(C)->getSourceRange();
3066
3067  if (C.kind == CXCursor_PreprocessingDirective)
3068    return cxcursor::getCursorPreprocessingDirective(C);
3069
3070  if (C.kind == CXCursor_MacroInstantiation)
3071    return cxcursor::getCursorMacroInstantiation(C)->getSourceRange();
3072
3073  if (C.kind == CXCursor_MacroDefinition)
3074    return cxcursor::getCursorMacroDefinition(C)->getSourceRange();
3075
3076  if (C.kind == CXCursor_InclusionDirective)
3077    return cxcursor::getCursorInclusionDirective(C)->getSourceRange();
3078
3079  if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl)
3080    return getCursorDecl(C)->getSourceRange();
3081
3082  return SourceRange();}
3083
3084extern "C" {
3085
3086CXSourceRange clang_getCursorExtent(CXCursor C) {
3087  SourceRange R = getRawCursorExtent(C);
3088  if (R.isInvalid())
3089    return clang_getNullRange();
3090
3091  return cxloc::translateSourceRange(getCursorContext(C), R);
3092}
3093
3094CXCursor clang_getCursorReferenced(CXCursor C) {
3095  if (clang_isInvalid(C.kind))
3096    return clang_getNullCursor();
3097
3098  ASTUnit *CXXUnit = getCursorASTUnit(C);
3099  if (clang_isDeclaration(C.kind)) {
3100    Decl *D = getCursorDecl(C);
3101    if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
3102      return MakeCursorOverloadedDeclRef(Using, D->getLocation(), CXXUnit);
3103    if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
3104      return MakeCursorOverloadedDeclRef(Classes, D->getLocation(), CXXUnit);
3105    if (ObjCForwardProtocolDecl *Protocols
3106                                        = dyn_cast<ObjCForwardProtocolDecl>(D))
3107      return MakeCursorOverloadedDeclRef(Protocols, D->getLocation(), CXXUnit);
3108
3109    return C;
3110  }
3111
3112  if (clang_isExpression(C.kind)) {
3113    Expr *E = getCursorExpr(C);
3114    Decl *D = getDeclFromExpr(E);
3115    if (D)
3116      return MakeCXCursor(D, CXXUnit);
3117
3118    if (OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
3119      return MakeCursorOverloadedDeclRef(Ovl, CXXUnit);
3120
3121    return clang_getNullCursor();
3122  }
3123
3124  if (clang_isStatement(C.kind)) {
3125    Stmt *S = getCursorStmt(C);
3126    if (GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
3127      return MakeCXCursor(Goto->getLabel(), getCursorDecl(C),
3128                          getCursorASTUnit(C));
3129
3130    return clang_getNullCursor();
3131  }
3132
3133  if (C.kind == CXCursor_MacroInstantiation) {
3134    if (MacroDefinition *Def = getCursorMacroInstantiation(C)->getDefinition())
3135      return MakeMacroDefinitionCursor(Def, CXXUnit);
3136  }
3137
3138  if (!clang_isReference(C.kind))
3139    return clang_getNullCursor();
3140
3141  switch (C.kind) {
3142    case CXCursor_ObjCSuperClassRef:
3143      return MakeCXCursor(getCursorObjCSuperClassRef(C).first, CXXUnit);
3144
3145    case CXCursor_ObjCProtocolRef: {
3146      return MakeCXCursor(getCursorObjCProtocolRef(C).first, CXXUnit);
3147
3148    case CXCursor_ObjCClassRef:
3149      return MakeCXCursor(getCursorObjCClassRef(C).first, CXXUnit);
3150
3151    case CXCursor_TypeRef:
3152      return MakeCXCursor(getCursorTypeRef(C).first, CXXUnit);
3153
3154    case CXCursor_TemplateRef:
3155      return MakeCXCursor(getCursorTemplateRef(C).first, CXXUnit);
3156
3157    case CXCursor_NamespaceRef:
3158      return MakeCXCursor(getCursorNamespaceRef(C).first, CXXUnit);
3159
3160    case CXCursor_MemberRef:
3161      return MakeCXCursor(getCursorMemberRef(C).first, CXXUnit);
3162
3163    case CXCursor_CXXBaseSpecifier: {
3164      CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
3165      return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
3166                                                         CXXUnit));
3167    }
3168
3169    case CXCursor_LabelRef:
3170      // FIXME: We end up faking the "parent" declaration here because we
3171      // don't want to make CXCursor larger.
3172      return MakeCXCursor(getCursorLabelRef(C).first,
3173                          CXXUnit->getASTContext().getTranslationUnitDecl(),
3174                          CXXUnit);
3175
3176    case CXCursor_OverloadedDeclRef:
3177      return C;
3178
3179    default:
3180      // We would prefer to enumerate all non-reference cursor kinds here.
3181      llvm_unreachable("Unhandled reference cursor kind");
3182      break;
3183    }
3184  }
3185
3186  return clang_getNullCursor();
3187}
3188
3189CXCursor clang_getCursorDefinition(CXCursor C) {
3190  if (clang_isInvalid(C.kind))
3191    return clang_getNullCursor();
3192
3193  ASTUnit *CXXUnit = getCursorASTUnit(C);
3194
3195  bool WasReference = false;
3196  if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
3197    C = clang_getCursorReferenced(C);
3198    WasReference = true;
3199  }
3200
3201  if (C.kind == CXCursor_MacroInstantiation)
3202    return clang_getCursorReferenced(C);
3203
3204  if (!clang_isDeclaration(C.kind))
3205    return clang_getNullCursor();
3206
3207  Decl *D = getCursorDecl(C);
3208  if (!D)
3209    return clang_getNullCursor();
3210
3211  switch (D->getKind()) {
3212  // Declaration kinds that don't really separate the notions of
3213  // declaration and definition.
3214  case Decl::Namespace:
3215  case Decl::Typedef:
3216  case Decl::TemplateTypeParm:
3217  case Decl::EnumConstant:
3218  case Decl::Field:
3219  case Decl::ObjCIvar:
3220  case Decl::ObjCAtDefsField:
3221  case Decl::ImplicitParam:
3222  case Decl::ParmVar:
3223  case Decl::NonTypeTemplateParm:
3224  case Decl::TemplateTemplateParm:
3225  case Decl::ObjCCategoryImpl:
3226  case Decl::ObjCImplementation:
3227  case Decl::AccessSpec:
3228  case Decl::LinkageSpec:
3229  case Decl::ObjCPropertyImpl:
3230  case Decl::FileScopeAsm:
3231  case Decl::StaticAssert:
3232  case Decl::Block:
3233    return C;
3234
3235  // Declaration kinds that don't make any sense here, but are
3236  // nonetheless harmless.
3237  case Decl::TranslationUnit:
3238    break;
3239
3240  // Declaration kinds for which the definition is not resolvable.
3241  case Decl::UnresolvedUsingTypename:
3242  case Decl::UnresolvedUsingValue:
3243    break;
3244
3245  case Decl::UsingDirective:
3246    return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
3247                        CXXUnit);
3248
3249  case Decl::NamespaceAlias:
3250    return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), CXXUnit);
3251
3252  case Decl::Enum:
3253  case Decl::Record:
3254  case Decl::CXXRecord:
3255  case Decl::ClassTemplateSpecialization:
3256  case Decl::ClassTemplatePartialSpecialization:
3257    if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
3258      return MakeCXCursor(Def, CXXUnit);
3259    return clang_getNullCursor();
3260
3261  case Decl::Function:
3262  case Decl::CXXMethod:
3263  case Decl::CXXConstructor:
3264  case Decl::CXXDestructor:
3265  case Decl::CXXConversion: {
3266    const FunctionDecl *Def = 0;
3267    if (cast<FunctionDecl>(D)->getBody(Def))
3268      return MakeCXCursor(const_cast<FunctionDecl *>(Def), CXXUnit);
3269    return clang_getNullCursor();
3270  }
3271
3272  case Decl::Var: {
3273    // Ask the variable if it has a definition.
3274    if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
3275      return MakeCXCursor(Def, CXXUnit);
3276    return clang_getNullCursor();
3277  }
3278
3279  case Decl::FunctionTemplate: {
3280    const FunctionDecl *Def = 0;
3281    if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
3282      return MakeCXCursor(Def->getDescribedFunctionTemplate(), CXXUnit);
3283    return clang_getNullCursor();
3284  }
3285
3286  case Decl::ClassTemplate: {
3287    if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
3288                                                            ->getDefinition())
3289      return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
3290                          CXXUnit);
3291    return clang_getNullCursor();
3292  }
3293
3294  case Decl::Using:
3295    return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
3296                                       D->getLocation(), CXXUnit);
3297
3298  case Decl::UsingShadow:
3299    return clang_getCursorDefinition(
3300                       MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
3301                                    CXXUnit));
3302
3303  case Decl::ObjCMethod: {
3304    ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
3305    if (Method->isThisDeclarationADefinition())
3306      return C;
3307
3308    // Dig out the method definition in the associated
3309    // @implementation, if we have it.
3310    // FIXME: The ASTs should make finding the definition easier.
3311    if (ObjCInterfaceDecl *Class
3312                       = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
3313      if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
3314        if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
3315                                                  Method->isInstanceMethod()))
3316          if (Def->isThisDeclarationADefinition())
3317            return MakeCXCursor(Def, CXXUnit);
3318
3319    return clang_getNullCursor();
3320  }
3321
3322  case Decl::ObjCCategory:
3323    if (ObjCCategoryImplDecl *Impl
3324                               = cast<ObjCCategoryDecl>(D)->getImplementation())
3325      return MakeCXCursor(Impl, CXXUnit);
3326    return clang_getNullCursor();
3327
3328  case Decl::ObjCProtocol:
3329    if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
3330      return C;
3331    return clang_getNullCursor();
3332
3333  case Decl::ObjCInterface:
3334    // There are two notions of a "definition" for an Objective-C
3335    // class: the interface and its implementation. When we resolved a
3336    // reference to an Objective-C class, produce the @interface as
3337    // the definition; when we were provided with the interface,
3338    // produce the @implementation as the definition.
3339    if (WasReference) {
3340      if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
3341        return C;
3342    } else if (ObjCImplementationDecl *Impl
3343                              = cast<ObjCInterfaceDecl>(D)->getImplementation())
3344      return MakeCXCursor(Impl, CXXUnit);
3345    return clang_getNullCursor();
3346
3347  case Decl::ObjCProperty:
3348    // FIXME: We don't really know where to find the
3349    // ObjCPropertyImplDecls that implement this property.
3350    return clang_getNullCursor();
3351
3352  case Decl::ObjCCompatibleAlias:
3353    if (ObjCInterfaceDecl *Class
3354          = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
3355      if (!Class->isForwardDecl())
3356        return MakeCXCursor(Class, CXXUnit);
3357
3358    return clang_getNullCursor();
3359
3360  case Decl::ObjCForwardProtocol:
3361    return MakeCursorOverloadedDeclRef(cast<ObjCForwardProtocolDecl>(D),
3362                                       D->getLocation(), CXXUnit);
3363
3364  case Decl::ObjCClass:
3365    return MakeCursorOverloadedDeclRef(cast<ObjCClassDecl>(D), D->getLocation(),
3366                                       CXXUnit);
3367
3368  case Decl::Friend:
3369    if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
3370      return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
3371    return clang_getNullCursor();
3372
3373  case Decl::FriendTemplate:
3374    if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
3375      return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
3376    return clang_getNullCursor();
3377  }
3378
3379  return clang_getNullCursor();
3380}
3381
3382unsigned clang_isCursorDefinition(CXCursor C) {
3383  if (!clang_isDeclaration(C.kind))
3384    return 0;
3385
3386  return clang_getCursorDefinition(C) == C;
3387}
3388
3389unsigned clang_getNumOverloadedDecls(CXCursor C) {
3390  if (C.kind != CXCursor_OverloadedDeclRef)
3391    return 0;
3392
3393  OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
3394  if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
3395    return E->getNumDecls();
3396
3397  if (OverloadedTemplateStorage *S
3398                              = Storage.dyn_cast<OverloadedTemplateStorage*>())
3399    return S->size();
3400
3401  Decl *D = Storage.get<Decl*>();
3402  if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
3403    return Using->getNumShadowDecls();
3404  if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
3405    return Classes->size();
3406  if (ObjCForwardProtocolDecl *Protocols =dyn_cast<ObjCForwardProtocolDecl>(D))
3407    return Protocols->protocol_size();
3408
3409  return 0;
3410}
3411
3412CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
3413  if (cursor.kind != CXCursor_OverloadedDeclRef)
3414    return clang_getNullCursor();
3415
3416  if (index >= clang_getNumOverloadedDecls(cursor))
3417    return clang_getNullCursor();
3418
3419  ASTUnit *Unit = getCursorASTUnit(cursor);
3420  OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
3421  if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
3422    return MakeCXCursor(E->decls_begin()[index], Unit);
3423
3424  if (OverloadedTemplateStorage *S
3425                              = Storage.dyn_cast<OverloadedTemplateStorage*>())
3426    return MakeCXCursor(S->begin()[index], Unit);
3427
3428  Decl *D = Storage.get<Decl*>();
3429  if (UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
3430    // FIXME: This is, unfortunately, linear time.
3431    UsingDecl::shadow_iterator Pos = Using->shadow_begin();
3432    std::advance(Pos, index);
3433    return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), Unit);
3434  }
3435
3436  if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
3437    return MakeCXCursor(Classes->begin()[index].getInterface(), Unit);
3438
3439  if (ObjCForwardProtocolDecl *Protocols = dyn_cast<ObjCForwardProtocolDecl>(D))
3440    return MakeCXCursor(Protocols->protocol_begin()[index], Unit);
3441
3442  return clang_getNullCursor();
3443}
3444
3445void clang_getDefinitionSpellingAndExtent(CXCursor C,
3446                                          const char **startBuf,
3447                                          const char **endBuf,
3448                                          unsigned *startLine,
3449                                          unsigned *startColumn,
3450                                          unsigned *endLine,
3451                                          unsigned *endColumn) {
3452  assert(getCursorDecl(C) && "CXCursor has null decl");
3453  NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
3454  FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
3455  CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
3456
3457  SourceManager &SM = FD->getASTContext().getSourceManager();
3458  *startBuf = SM.getCharacterData(Body->getLBracLoc());
3459  *endBuf = SM.getCharacterData(Body->getRBracLoc());
3460  *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
3461  *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
3462  *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
3463  *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
3464}
3465
3466void clang_enableStackTraces(void) {
3467  llvm::sys::PrintStackTraceOnErrorSignal();
3468}
3469
3470} // end: extern "C"
3471
3472//===----------------------------------------------------------------------===//
3473// Token-based Operations.
3474//===----------------------------------------------------------------------===//
3475
3476/* CXToken layout:
3477 *   int_data[0]: a CXTokenKind
3478 *   int_data[1]: starting token location
3479 *   int_data[2]: token length
3480 *   int_data[3]: reserved
3481 *   ptr_data: for identifiers and keywords, an IdentifierInfo*.
3482 *   otherwise unused.
3483 */
3484extern "C" {
3485
3486CXTokenKind clang_getTokenKind(CXToken CXTok) {
3487  return static_cast<CXTokenKind>(CXTok.int_data[0]);
3488}
3489
3490CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
3491  switch (clang_getTokenKind(CXTok)) {
3492  case CXToken_Identifier:
3493  case CXToken_Keyword:
3494    // We know we have an IdentifierInfo*, so use that.
3495    return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
3496                            ->getNameStart());
3497
3498  case CXToken_Literal: {
3499    // We have stashed the starting pointer in the ptr_data field. Use it.
3500    const char *Text = static_cast<const char *>(CXTok.ptr_data);
3501    return createCXString(llvm::StringRef(Text, CXTok.int_data[2]));
3502  }
3503
3504  case CXToken_Punctuation:
3505  case CXToken_Comment:
3506    break;
3507  }
3508
3509  // We have to find the starting buffer pointer the hard way, by
3510  // deconstructing the source location.
3511  ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
3512  if (!CXXUnit)
3513    return createCXString("");
3514
3515  SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
3516  std::pair<FileID, unsigned> LocInfo
3517    = CXXUnit->getSourceManager().getDecomposedLoc(Loc);
3518  bool Invalid = false;
3519  llvm::StringRef Buffer
3520    = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
3521  if (Invalid)
3522    return createCXString("");
3523
3524  return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
3525}
3526
3527CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
3528  ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
3529  if (!CXXUnit)
3530    return clang_getNullLocation();
3531
3532  return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
3533                        SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
3534}
3535
3536CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
3537  ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
3538  if (!CXXUnit)
3539    return clang_getNullRange();
3540
3541  return cxloc::translateSourceRange(CXXUnit->getASTContext(),
3542                        SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
3543}
3544
3545void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
3546                    CXToken **Tokens, unsigned *NumTokens) {
3547  if (Tokens)
3548    *Tokens = 0;
3549  if (NumTokens)
3550    *NumTokens = 0;
3551
3552  ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
3553  if (!CXXUnit || !Tokens || !NumTokens)
3554    return;
3555
3556  ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3557
3558  SourceRange R = cxloc::translateCXSourceRange(Range);
3559  if (R.isInvalid())
3560    return;
3561
3562  SourceManager &SourceMgr = CXXUnit->getSourceManager();
3563  std::pair<FileID, unsigned> BeginLocInfo
3564    = SourceMgr.getDecomposedLoc(R.getBegin());
3565  std::pair<FileID, unsigned> EndLocInfo
3566    = SourceMgr.getDecomposedLoc(R.getEnd());
3567
3568  // Cannot tokenize across files.
3569  if (BeginLocInfo.first != EndLocInfo.first)
3570    return;
3571
3572  // Create a lexer
3573  bool Invalid = false;
3574  llvm::StringRef Buffer
3575    = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
3576  if (Invalid)
3577    return;
3578
3579  Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
3580            CXXUnit->getASTContext().getLangOptions(),
3581            Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
3582  Lex.SetCommentRetentionState(true);
3583
3584  // Lex tokens until we hit the end of the range.
3585  const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
3586  llvm::SmallVector<CXToken, 32> CXTokens;
3587  Token Tok;
3588  bool previousWasAt = false;
3589  do {
3590    // Lex the next token
3591    Lex.LexFromRawLexer(Tok);
3592    if (Tok.is(tok::eof))
3593      break;
3594
3595    // Initialize the CXToken.
3596    CXToken CXTok;
3597
3598    //   - Common fields
3599    CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
3600    CXTok.int_data[2] = Tok.getLength();
3601    CXTok.int_data[3] = 0;
3602
3603    //   - Kind-specific fields
3604    if (Tok.isLiteral()) {
3605      CXTok.int_data[0] = CXToken_Literal;
3606      CXTok.ptr_data = (void *)Tok.getLiteralData();
3607    } else if (Tok.is(tok::identifier)) {
3608      // Lookup the identifier to determine whether we have a keyword.
3609      std::pair<FileID, unsigned> LocInfo
3610        = SourceMgr.getDecomposedLoc(Tok.getLocation());
3611      bool Invalid = false;
3612      llvm::StringRef Buf
3613        = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
3614      if (Invalid)
3615        return;
3616
3617      const char *StartPos = Buf.data() + LocInfo.second;
3618      IdentifierInfo *II
3619        = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok, StartPos);
3620
3621      if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
3622        CXTok.int_data[0] = CXToken_Keyword;
3623      }
3624      else {
3625        CXTok.int_data[0] = II->getTokenID() == tok::identifier?
3626                                CXToken_Identifier
3627                              : CXToken_Keyword;
3628      }
3629      CXTok.ptr_data = II;
3630    } else if (Tok.is(tok::comment)) {
3631      CXTok.int_data[0] = CXToken_Comment;
3632      CXTok.ptr_data = 0;
3633    } else {
3634      CXTok.int_data[0] = CXToken_Punctuation;
3635      CXTok.ptr_data = 0;
3636    }
3637    CXTokens.push_back(CXTok);
3638    previousWasAt = Tok.is(tok::at);
3639  } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
3640
3641  if (CXTokens.empty())
3642    return;
3643
3644  *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
3645  memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
3646  *NumTokens = CXTokens.size();
3647}
3648
3649void clang_disposeTokens(CXTranslationUnit TU,
3650                         CXToken *Tokens, unsigned NumTokens) {
3651  free(Tokens);
3652}
3653
3654} // end: extern "C"
3655
3656//===----------------------------------------------------------------------===//
3657// Token annotation APIs.
3658//===----------------------------------------------------------------------===//
3659
3660typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
3661static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
3662                                                     CXCursor parent,
3663                                                     CXClientData client_data);
3664namespace {
3665class AnnotateTokensWorker {
3666  AnnotateTokensData &Annotated;
3667  CXToken *Tokens;
3668  CXCursor *Cursors;
3669  unsigned NumTokens;
3670  unsigned TokIdx;
3671  unsigned PreprocessingTokIdx;
3672  CursorVisitor AnnotateVis;
3673  SourceManager &SrcMgr;
3674
3675  bool MoreTokens() const { return TokIdx < NumTokens; }
3676  unsigned NextToken() const { return TokIdx; }
3677  void AdvanceToken() { ++TokIdx; }
3678  SourceLocation GetTokenLoc(unsigned tokI) {
3679    return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
3680  }
3681
3682public:
3683  AnnotateTokensWorker(AnnotateTokensData &annotated,
3684                       CXToken *tokens, CXCursor *cursors, unsigned numTokens,
3685                       ASTUnit *CXXUnit, SourceRange RegionOfInterest)
3686    : Annotated(annotated), Tokens(tokens), Cursors(cursors),
3687      NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0),
3688      AnnotateVis(CXXUnit, AnnotateTokensVisitor, this,
3689                  Decl::MaxPCHLevel, RegionOfInterest),
3690      SrcMgr(CXXUnit->getSourceManager()) {}
3691
3692  void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
3693  enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
3694  void AnnotateTokens(CXCursor parent);
3695};
3696}
3697
3698void AnnotateTokensWorker::AnnotateTokens(CXCursor parent) {
3699  // Walk the AST within the region of interest, annotating tokens
3700  // along the way.
3701  VisitChildren(parent);
3702
3703  for (unsigned I = 0 ; I < TokIdx ; ++I) {
3704    AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
3705    if (Pos != Annotated.end() &&
3706        (clang_isInvalid(Cursors[I].kind) ||
3707         Pos->second.kind != CXCursor_PreprocessingDirective))
3708      Cursors[I] = Pos->second;
3709  }
3710
3711  // Finish up annotating any tokens left.
3712  if (!MoreTokens())
3713    return;
3714
3715  const CXCursor &C = clang_getNullCursor();
3716  for (unsigned I = TokIdx ; I < NumTokens ; ++I) {
3717    AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
3718    Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second;
3719  }
3720}
3721
3722enum CXChildVisitResult
3723AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
3724  CXSourceLocation Loc = clang_getCursorLocation(cursor);
3725  SourceRange cursorRange = getRawCursorExtent(cursor);
3726
3727  if (clang_isPreprocessing(cursor.kind)) {
3728    // For macro instantiations, just note where the beginning of the macro
3729    // instantiation occurs.
3730    if (cursor.kind == CXCursor_MacroInstantiation) {
3731      Annotated[Loc.int_data] = cursor;
3732      return CXChildVisit_Recurse;
3733    }
3734
3735    if (cursorRange.isInvalid())
3736      return CXChildVisit_Continue;
3737
3738    // Items in the preprocessing record are kept separate from items in
3739    // declarations, so we keep a separate token index.
3740    unsigned SavedTokIdx = TokIdx;
3741    TokIdx = PreprocessingTokIdx;
3742
3743    // Skip tokens up until we catch up to the beginning of the preprocessing
3744    // entry.
3745    while (MoreTokens()) {
3746      const unsigned I = NextToken();
3747      SourceLocation TokLoc = GetTokenLoc(I);
3748      switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
3749      case RangeBefore:
3750        AdvanceToken();
3751        continue;
3752      case RangeAfter:
3753      case RangeOverlap:
3754        break;
3755      }
3756      break;
3757    }
3758
3759    // Look at all of the tokens within this range.
3760    while (MoreTokens()) {
3761      const unsigned I = NextToken();
3762      SourceLocation TokLoc = GetTokenLoc(I);
3763      switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
3764      case RangeBefore:
3765        assert(0 && "Infeasible");
3766      case RangeAfter:
3767        break;
3768      case RangeOverlap:
3769        Cursors[I] = cursor;
3770        AdvanceToken();
3771        continue;
3772      }
3773      break;
3774    }
3775
3776    // Save the preprocessing token index; restore the non-preprocessing
3777    // token index.
3778    PreprocessingTokIdx = TokIdx;
3779    TokIdx = SavedTokIdx;
3780    return CXChildVisit_Recurse;
3781  }
3782
3783  if (cursorRange.isInvalid())
3784    return CXChildVisit_Continue;
3785
3786  SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data);
3787
3788  // Adjust the annotated range based specific declarations.
3789  const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
3790  if (cursorK >= CXCursor_FirstDecl && cursorK <= CXCursor_LastDecl) {
3791    Decl *D = cxcursor::getCursorDecl(cursor);
3792    // Don't visit synthesized ObjC methods, since they have no syntatic
3793    // representation in the source.
3794    if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
3795      if (MD->isSynthesized())
3796        return CXChildVisit_Continue;
3797    }
3798    if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
3799      if (TypeSourceInfo *TI = DD->getTypeSourceInfo()) {
3800        TypeLoc TL = TI->getTypeLoc();
3801        SourceLocation TLoc = TL.getSourceRange().getBegin();
3802        if (TLoc.isValid() &&
3803            SrcMgr.isBeforeInTranslationUnit(TLoc, L))
3804          cursorRange.setBegin(TLoc);
3805      }
3806    }
3807  }
3808
3809  // If the location of the cursor occurs within a macro instantiation, record
3810  // the spelling location of the cursor in our annotation map.  We can then
3811  // paper over the token labelings during a post-processing step to try and
3812  // get cursor mappings for tokens that are the *arguments* of a macro
3813  // instantiation.
3814  if (L.isMacroID()) {
3815    unsigned rawEncoding = SrcMgr.getSpellingLoc(L).getRawEncoding();
3816    // Only invalidate the old annotation if it isn't part of a preprocessing
3817    // directive.  Here we assume that the default construction of CXCursor
3818    // results in CXCursor.kind being an initialized value (i.e., 0).  If
3819    // this isn't the case, we can fix by doing lookup + insertion.
3820
3821    CXCursor &oldC = Annotated[rawEncoding];
3822    if (!clang_isPreprocessing(oldC.kind))
3823      oldC = cursor;
3824  }
3825
3826  const enum CXCursorKind K = clang_getCursorKind(parent);
3827  const CXCursor updateC =
3828    (clang_isInvalid(K) || K == CXCursor_TranslationUnit)
3829     ? clang_getNullCursor() : parent;
3830
3831  while (MoreTokens()) {
3832    const unsigned I = NextToken();
3833    SourceLocation TokLoc = GetTokenLoc(I);
3834    switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
3835      case RangeBefore:
3836        Cursors[I] = updateC;
3837        AdvanceToken();
3838        continue;
3839      case RangeAfter:
3840      case RangeOverlap:
3841        break;
3842    }
3843    break;
3844  }
3845
3846  // Visit children to get their cursor information.
3847  const unsigned BeforeChildren = NextToken();
3848  VisitChildren(cursor);
3849  const unsigned AfterChildren = NextToken();
3850
3851  // Adjust 'Last' to the last token within the extent of the cursor.
3852  while (MoreTokens()) {
3853    const unsigned I = NextToken();
3854    SourceLocation TokLoc = GetTokenLoc(I);
3855    switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
3856      case RangeBefore:
3857        assert(0 && "Infeasible");
3858      case RangeAfter:
3859        break;
3860      case RangeOverlap:
3861        Cursors[I] = updateC;
3862        AdvanceToken();
3863        continue;
3864    }
3865    break;
3866  }
3867  const unsigned Last = NextToken();
3868
3869  // Scan the tokens that are at the beginning of the cursor, but are not
3870  // capture by the child cursors.
3871
3872  // For AST elements within macros, rely on a post-annotate pass to
3873  // to correctly annotate the tokens with cursors.  Otherwise we can
3874  // get confusing results of having tokens that map to cursors that really
3875  // are expanded by an instantiation.
3876  if (L.isMacroID())
3877    cursor = clang_getNullCursor();
3878
3879  for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
3880    if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
3881      break;
3882
3883    Cursors[I] = cursor;
3884  }
3885  // Scan the tokens that are at the end of the cursor, but are not captured
3886  // but the child cursors.
3887  for (unsigned I = AfterChildren; I != Last; ++I)
3888    Cursors[I] = cursor;
3889
3890  TokIdx = Last;
3891  return CXChildVisit_Continue;
3892}
3893
3894static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
3895                                                     CXCursor parent,
3896                                                     CXClientData client_data) {
3897  return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
3898}
3899
3900extern "C" {
3901
3902void clang_annotateTokens(CXTranslationUnit TU,
3903                          CXToken *Tokens, unsigned NumTokens,
3904                          CXCursor *Cursors) {
3905
3906  if (NumTokens == 0 || !Tokens || !Cursors)
3907    return;
3908
3909  // Any token we don't specifically annotate will have a NULL cursor.
3910  CXCursor C = clang_getNullCursor();
3911  for (unsigned I = 0; I != NumTokens; ++I)
3912    Cursors[I] = C;
3913
3914  ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
3915  if (!CXXUnit)
3916    return;
3917
3918  ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3919
3920  // Determine the region of interest, which contains all of the tokens.
3921  SourceRange RegionOfInterest;
3922  RegionOfInterest.setBegin(cxloc::translateSourceLocation(
3923                                        clang_getTokenLocation(TU, Tokens[0])));
3924  RegionOfInterest.setEnd(cxloc::translateSourceLocation(
3925                                clang_getTokenLocation(TU,
3926                                                       Tokens[NumTokens - 1])));
3927
3928  // A mapping from the source locations found when re-lexing or traversing the
3929  // region of interest to the corresponding cursors.
3930  AnnotateTokensData Annotated;
3931
3932  // Relex the tokens within the source range to look for preprocessing
3933  // directives.
3934  SourceManager &SourceMgr = CXXUnit->getSourceManager();
3935  std::pair<FileID, unsigned> BeginLocInfo
3936    = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
3937  std::pair<FileID, unsigned> EndLocInfo
3938    = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
3939
3940  llvm::StringRef Buffer;
3941  bool Invalid = false;
3942  if (BeginLocInfo.first == EndLocInfo.first &&
3943      ((Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid)),true) &&
3944      !Invalid) {
3945    Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
3946              CXXUnit->getASTContext().getLangOptions(),
3947              Buffer.begin(), Buffer.data() + BeginLocInfo.second,
3948              Buffer.end());
3949    Lex.SetCommentRetentionState(true);
3950
3951    // Lex tokens in raw mode until we hit the end of the range, to avoid
3952    // entering #includes or expanding macros.
3953    while (true) {
3954      Token Tok;
3955      Lex.LexFromRawLexer(Tok);
3956
3957    reprocess:
3958      if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
3959        // We have found a preprocessing directive. Gobble it up so that we
3960        // don't see it while preprocessing these tokens later, but keep track of
3961        // all of the token locations inside this preprocessing directive so that
3962        // we can annotate them appropriately.
3963        //
3964        // FIXME: Some simple tests here could identify macro definitions and
3965        // #undefs, to provide specific cursor kinds for those.
3966        std::vector<SourceLocation> Locations;
3967        do {
3968          Locations.push_back(Tok.getLocation());
3969          Lex.LexFromRawLexer(Tok);
3970        } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
3971
3972        using namespace cxcursor;
3973        CXCursor Cursor
3974          = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
3975                                                         Locations.back()),
3976                                           CXXUnit);
3977        for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
3978          Annotated[Locations[I].getRawEncoding()] = Cursor;
3979        }
3980
3981        if (Tok.isAtStartOfLine())
3982          goto reprocess;
3983
3984        continue;
3985      }
3986
3987      if (Tok.is(tok::eof))
3988        break;
3989    }
3990  }
3991
3992  // Annotate all of the source locations in the region of interest that map to
3993  // a specific cursor.
3994  AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens,
3995                         CXXUnit, RegionOfInterest);
3996  W.AnnotateTokens(clang_getTranslationUnitCursor(CXXUnit));
3997}
3998} // end: extern "C"
3999
4000//===----------------------------------------------------------------------===//
4001// Operations for querying linkage of a cursor.
4002//===----------------------------------------------------------------------===//
4003
4004extern "C" {
4005CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
4006  if (!clang_isDeclaration(cursor.kind))
4007    return CXLinkage_Invalid;
4008
4009  Decl *D = cxcursor::getCursorDecl(cursor);
4010  if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
4011    switch (ND->getLinkage()) {
4012      case NoLinkage: return CXLinkage_NoLinkage;
4013      case InternalLinkage: return CXLinkage_Internal;
4014      case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
4015      case ExternalLinkage: return CXLinkage_External;
4016    };
4017
4018  return CXLinkage_Invalid;
4019}
4020} // end: extern "C"
4021
4022//===----------------------------------------------------------------------===//
4023// Operations for querying language of a cursor.
4024//===----------------------------------------------------------------------===//
4025
4026static CXLanguageKind getDeclLanguage(const Decl *D) {
4027  switch (D->getKind()) {
4028    default:
4029      break;
4030    case Decl::ImplicitParam:
4031    case Decl::ObjCAtDefsField:
4032    case Decl::ObjCCategory:
4033    case Decl::ObjCCategoryImpl:
4034    case Decl::ObjCClass:
4035    case Decl::ObjCCompatibleAlias:
4036    case Decl::ObjCForwardProtocol:
4037    case Decl::ObjCImplementation:
4038    case Decl::ObjCInterface:
4039    case Decl::ObjCIvar:
4040    case Decl::ObjCMethod:
4041    case Decl::ObjCProperty:
4042    case Decl::ObjCPropertyImpl:
4043    case Decl::ObjCProtocol:
4044      return CXLanguage_ObjC;
4045    case Decl::CXXConstructor:
4046    case Decl::CXXConversion:
4047    case Decl::CXXDestructor:
4048    case Decl::CXXMethod:
4049    case Decl::CXXRecord:
4050    case Decl::ClassTemplate:
4051    case Decl::ClassTemplatePartialSpecialization:
4052    case Decl::ClassTemplateSpecialization:
4053    case Decl::Friend:
4054    case Decl::FriendTemplate:
4055    case Decl::FunctionTemplate:
4056    case Decl::LinkageSpec:
4057    case Decl::Namespace:
4058    case Decl::NamespaceAlias:
4059    case Decl::NonTypeTemplateParm:
4060    case Decl::StaticAssert:
4061    case Decl::TemplateTemplateParm:
4062    case Decl::TemplateTypeParm:
4063    case Decl::UnresolvedUsingTypename:
4064    case Decl::UnresolvedUsingValue:
4065    case Decl::Using:
4066    case Decl::UsingDirective:
4067    case Decl::UsingShadow:
4068      return CXLanguage_CPlusPlus;
4069  }
4070
4071  return CXLanguage_C;
4072}
4073
4074extern "C" {
4075
4076enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
4077  if (clang_isDeclaration(cursor.kind))
4078    if (Decl *D = cxcursor::getCursorDecl(cursor)) {
4079      if (D->hasAttr<UnavailableAttr>() ||
4080          (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted()))
4081        return CXAvailability_Available;
4082
4083      if (D->hasAttr<DeprecatedAttr>())
4084        return CXAvailability_Deprecated;
4085    }
4086
4087  return CXAvailability_Available;
4088}
4089
4090CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
4091  if (clang_isDeclaration(cursor.kind))
4092    return getDeclLanguage(cxcursor::getCursorDecl(cursor));
4093
4094  return CXLanguage_Invalid;
4095}
4096
4097CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
4098  if (clang_isDeclaration(cursor.kind)) {
4099    if (Decl *D = getCursorDecl(cursor)) {
4100      DeclContext *DC = D->getDeclContext();
4101      return MakeCXCursor(cast<Decl>(DC), getCursorASTUnit(cursor));
4102    }
4103  }
4104
4105  if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
4106    if (Decl *D = getCursorDecl(cursor))
4107      return MakeCXCursor(D, getCursorASTUnit(cursor));
4108  }
4109
4110  return clang_getNullCursor();
4111}
4112
4113CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
4114  if (clang_isDeclaration(cursor.kind)) {
4115    if (Decl *D = getCursorDecl(cursor)) {
4116      DeclContext *DC = D->getLexicalDeclContext();
4117      return MakeCXCursor(cast<Decl>(DC), getCursorASTUnit(cursor));
4118    }
4119  }
4120
4121  // FIXME: Note that we can't easily compute the lexical context of a
4122  // statement or expression, so we return nothing.
4123  return clang_getNullCursor();
4124}
4125
4126static void CollectOverriddenMethods(DeclContext *Ctx,
4127                                     ObjCMethodDecl *Method,
4128                            llvm::SmallVectorImpl<ObjCMethodDecl *> &Methods) {
4129  if (!Ctx)
4130    return;
4131
4132  // If we have a class or category implementation, jump straight to the
4133  // interface.
4134  if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(Ctx))
4135    return CollectOverriddenMethods(Impl->getClassInterface(), Method, Methods);
4136
4137  ObjCContainerDecl *Container = dyn_cast<ObjCContainerDecl>(Ctx);
4138  if (!Container)
4139    return;
4140
4141  // Check whether we have a matching method at this level.
4142  if (ObjCMethodDecl *Overridden = Container->getMethod(Method->getSelector(),
4143                                                    Method->isInstanceMethod()))
4144    if (Method != Overridden) {
4145      // We found an override at this level; there is no need to look
4146      // into other protocols or categories.
4147      Methods.push_back(Overridden);
4148      return;
4149    }
4150
4151  if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
4152    for (ObjCProtocolDecl::protocol_iterator P = Protocol->protocol_begin(),
4153                                          PEnd = Protocol->protocol_end();
4154         P != PEnd; ++P)
4155      CollectOverriddenMethods(*P, Method, Methods);
4156  }
4157
4158  if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Container)) {
4159    for (ObjCCategoryDecl::protocol_iterator P = Category->protocol_begin(),
4160                                          PEnd = Category->protocol_end();
4161         P != PEnd; ++P)
4162      CollectOverriddenMethods(*P, Method, Methods);
4163  }
4164
4165  if (ObjCInterfaceDecl *Interface = dyn_cast<ObjCInterfaceDecl>(Container)) {
4166    for (ObjCInterfaceDecl::protocol_iterator P = Interface->protocol_begin(),
4167                                           PEnd = Interface->protocol_end();
4168         P != PEnd; ++P)
4169      CollectOverriddenMethods(*P, Method, Methods);
4170
4171    for (ObjCCategoryDecl *Category = Interface->getCategoryList();
4172         Category; Category = Category->getNextClassCategory())
4173      CollectOverriddenMethods(Category, Method, Methods);
4174
4175    // We only look into the superclass if we haven't found anything yet.
4176    if (Methods.empty())
4177      if (ObjCInterfaceDecl *Super = Interface->getSuperClass())
4178        return CollectOverriddenMethods(Super, Method, Methods);
4179  }
4180}
4181
4182void clang_getOverriddenCursors(CXCursor cursor,
4183                                CXCursor **overridden,
4184                                unsigned *num_overridden) {
4185  if (overridden)
4186    *overridden = 0;
4187  if (num_overridden)
4188    *num_overridden = 0;
4189  if (!overridden || !num_overridden)
4190    return;
4191
4192  if (!clang_isDeclaration(cursor.kind))
4193    return;
4194
4195  Decl *D = getCursorDecl(cursor);
4196  if (!D)
4197    return;
4198
4199  // Handle C++ member functions.
4200  ASTUnit *CXXUnit = getCursorASTUnit(cursor);
4201  if (CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
4202    *num_overridden = CXXMethod->size_overridden_methods();
4203    if (!*num_overridden)
4204      return;
4205
4206    *overridden = new CXCursor [*num_overridden];
4207    unsigned I = 0;
4208    for (CXXMethodDecl::method_iterator
4209              M = CXXMethod->begin_overridden_methods(),
4210           MEnd = CXXMethod->end_overridden_methods();
4211         M != MEnd; (void)++M, ++I)
4212      (*overridden)[I] = MakeCXCursor(const_cast<CXXMethodDecl*>(*M), CXXUnit);
4213    return;
4214  }
4215
4216  ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
4217  if (!Method)
4218    return;
4219
4220  // Handle Objective-C methods.
4221  llvm::SmallVector<ObjCMethodDecl *, 4> Methods;
4222  CollectOverriddenMethods(Method->getDeclContext(), Method, Methods);
4223
4224  if (Methods.empty())
4225    return;
4226
4227  *num_overridden = Methods.size();
4228  *overridden = new CXCursor [Methods.size()];
4229  for (unsigned I = 0, N = Methods.size(); I != N; ++I)
4230    (*overridden)[I] = MakeCXCursor(Methods[I], CXXUnit);
4231}
4232
4233void clang_disposeOverriddenCursors(CXCursor *overridden) {
4234  delete [] overridden;
4235}
4236
4237CXFile clang_getIncludedFile(CXCursor cursor) {
4238  if (cursor.kind != CXCursor_InclusionDirective)
4239    return 0;
4240
4241  InclusionDirective *ID = getCursorInclusionDirective(cursor);
4242  return (void *)ID->getFile();
4243}
4244
4245} // end: extern "C"
4246
4247
4248//===----------------------------------------------------------------------===//
4249// C++ AST instrospection.
4250//===----------------------------------------------------------------------===//
4251
4252extern "C" {
4253unsigned clang_CXXMethod_isStatic(CXCursor C) {
4254  if (!clang_isDeclaration(C.kind))
4255    return 0;
4256
4257  CXXMethodDecl *Method = 0;
4258  Decl *D = cxcursor::getCursorDecl(C);
4259  if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
4260    Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
4261  else
4262    Method = dyn_cast_or_null<CXXMethodDecl>(D);
4263  return (Method && Method->isStatic()) ? 1 : 0;
4264}
4265
4266} // end: extern "C"
4267
4268//===----------------------------------------------------------------------===//
4269// Attribute introspection.
4270//===----------------------------------------------------------------------===//
4271
4272extern "C" {
4273CXType clang_getIBOutletCollectionType(CXCursor C) {
4274  if (C.kind != CXCursor_IBOutletCollectionAttr)
4275    return cxtype::MakeCXType(QualType(), cxcursor::getCursorASTUnit(C));
4276
4277  IBOutletCollectionAttr *A =
4278    cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
4279
4280  return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorASTUnit(C));
4281}
4282} // end: extern "C"
4283
4284//===----------------------------------------------------------------------===//
4285// CXString Operations.
4286//===----------------------------------------------------------------------===//
4287
4288extern "C" {
4289const char *clang_getCString(CXString string) {
4290  return string.Spelling;
4291}
4292
4293void clang_disposeString(CXString string) {
4294  if (string.MustFreeString && string.Spelling)
4295    free((void*)string.Spelling);
4296}
4297
4298} // end: extern "C"
4299
4300namespace clang { namespace cxstring {
4301CXString createCXString(const char *String, bool DupString){
4302  CXString Str;
4303  if (DupString) {
4304    Str.Spelling = strdup(String);
4305    Str.MustFreeString = 1;
4306  } else {
4307    Str.Spelling = String;
4308    Str.MustFreeString = 0;
4309  }
4310  return Str;
4311}
4312
4313CXString createCXString(llvm::StringRef String, bool DupString) {
4314  CXString Result;
4315  if (DupString || (!String.empty() && String.data()[String.size()] != 0)) {
4316    char *Spelling = (char *)malloc(String.size() + 1);
4317    memmove(Spelling, String.data(), String.size());
4318    Spelling[String.size()] = 0;
4319    Result.Spelling = Spelling;
4320    Result.MustFreeString = 1;
4321  } else {
4322    Result.Spelling = String.data();
4323    Result.MustFreeString = 0;
4324  }
4325  return Result;
4326}
4327}}
4328
4329//===----------------------------------------------------------------------===//
4330// Misc. utility functions.
4331//===----------------------------------------------------------------------===//
4332
4333extern "C" {
4334
4335CXString clang_getClangVersion() {
4336  return createCXString(getClangFullVersion());
4337}
4338
4339} // end: extern "C"
4340