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