CIndex.cpp revision ea94bbc4769697143e717df9b0310f874102b6c1
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 "CXSourceLocation.h"
18#include "CIndexDiagnostic.h"
19
20#include "clang/Basic/Version.h"
21
22#include "clang/AST/DeclVisitor.h"
23#include "clang/AST/StmtVisitor.h"
24#include "clang/AST/TypeLocVisitor.h"
25#include "clang/Basic/Diagnostic.h"
26#include "clang/Frontend/ASTUnit.h"
27#include "clang/Frontend/CompilerInstance.h"
28#include "clang/Frontend/FrontendDiagnostic.h"
29#include "clang/Lex/Lexer.h"
30#include "clang/Lex/PreprocessingRecord.h"
31#include "clang/Lex/Preprocessor.h"
32#include "llvm/Support/CrashRecoveryContext.h"
33#include "llvm/Support/MemoryBuffer.h"
34#include "llvm/Support/Timer.h"
35#include "llvm/System/Program.h"
36#include "llvm/System/Signals.h"
37
38// Needed to define L_TMPNAM on some systems.
39#include <cstdio>
40
41using namespace clang;
42using namespace clang::cxcursor;
43using namespace clang::cxstring;
44
45//===----------------------------------------------------------------------===//
46// Crash Reporting.
47//===----------------------------------------------------------------------===//
48
49#ifdef USE_CRASHTRACER
50#include "clang/Analysis/Support/SaveAndRestore.h"
51// Integrate with crash reporter.
52static const char *__crashreporter_info__ = 0;
53asm(".desc ___crashreporter_info__, 0x10");
54#define NUM_CRASH_STRINGS 32
55static unsigned crashtracer_counter = 0;
56static unsigned crashtracer_counter_id[NUM_CRASH_STRINGS] = { 0 };
57static const char *crashtracer_strings[NUM_CRASH_STRINGS] = { 0 };
58static const char *agg_crashtracer_strings[NUM_CRASH_STRINGS] = { 0 };
59
60static unsigned SetCrashTracerInfo(const char *str,
61                                   llvm::SmallString<1024> &AggStr) {
62
63  unsigned slot = 0;
64  while (crashtracer_strings[slot]) {
65    if (++slot == NUM_CRASH_STRINGS)
66      slot = 0;
67  }
68  crashtracer_strings[slot] = str;
69  crashtracer_counter_id[slot] = ++crashtracer_counter;
70
71  // We need to create an aggregate string because multiple threads
72  // may be in this method at one time.  The crash reporter string
73  // will attempt to overapproximate the set of in-flight invocations
74  // of this function.  Race conditions can still cause this goal
75  // to not be achieved.
76  {
77    llvm::raw_svector_ostream Out(AggStr);
78    for (unsigned i = 0; i < NUM_CRASH_STRINGS; ++i)
79      if (crashtracer_strings[i]) Out << crashtracer_strings[i] << '\n';
80  }
81  __crashreporter_info__ = agg_crashtracer_strings[slot] =  AggStr.c_str();
82  return slot;
83}
84
85static void ResetCrashTracerInfo(unsigned slot) {
86  unsigned max_slot = 0;
87  unsigned max_value = 0;
88
89  crashtracer_strings[slot] = agg_crashtracer_strings[slot] = 0;
90
91  for (unsigned i = 0 ; i < NUM_CRASH_STRINGS; ++i)
92    if (agg_crashtracer_strings[i] &&
93        crashtracer_counter_id[i] > max_value) {
94      max_slot = i;
95      max_value = crashtracer_counter_id[i];
96    }
97
98  __crashreporter_info__ = agg_crashtracer_strings[max_slot];
99}
100
101namespace {
102class ArgsCrashTracerInfo {
103  llvm::SmallString<1024> CrashString;
104  llvm::SmallString<1024> AggregateString;
105  unsigned crashtracerSlot;
106public:
107  ArgsCrashTracerInfo(llvm::SmallVectorImpl<const char*> &Args)
108    : crashtracerSlot(0)
109  {
110    {
111      llvm::raw_svector_ostream Out(CrashString);
112      Out << "ClangCIndex [" << getClangFullVersion() << "]"
113          << "[createTranslationUnitFromSourceFile]: clang";
114      for (llvm::SmallVectorImpl<const char*>::iterator I=Args.begin(),
115           E=Args.end(); I!=E; ++I)
116        Out << ' ' << *I;
117    }
118    crashtracerSlot = SetCrashTracerInfo(CrashString.c_str(),
119                                         AggregateString);
120  }
121
122  ~ArgsCrashTracerInfo() {
123    ResetCrashTracerInfo(crashtracerSlot);
124  }
125};
126}
127#endif
128
129/// \brief The result of comparing two source ranges.
130enum RangeComparisonResult {
131  /// \brief Either the ranges overlap or one of the ranges is invalid.
132  RangeOverlap,
133
134  /// \brief The first range ends before the second range starts.
135  RangeBefore,
136
137  /// \brief The first range starts after the second range ends.
138  RangeAfter
139};
140
141/// \brief Compare two source ranges to determine their relative position in
142/// the translation unit.
143static RangeComparisonResult RangeCompare(SourceManager &SM,
144                                          SourceRange R1,
145                                          SourceRange R2) {
146  assert(R1.isValid() && "First range is invalid?");
147  assert(R2.isValid() && "Second range is invalid?");
148  if (R1.getEnd() != R2.getBegin() &&
149      SM.isBeforeInTranslationUnit(R1.getEnd(), R2.getBegin()))
150    return RangeBefore;
151  if (R2.getEnd() != R1.getBegin() &&
152      SM.isBeforeInTranslationUnit(R2.getEnd(), R1.getBegin()))
153    return RangeAfter;
154  return RangeOverlap;
155}
156
157/// \brief Determine if a source location falls within, before, or after a
158///   a given source range.
159static RangeComparisonResult LocationCompare(SourceManager &SM,
160                                             SourceLocation L, SourceRange R) {
161  assert(R.isValid() && "First range is invalid?");
162  assert(L.isValid() && "Second range is invalid?");
163  if (L == R.getBegin() || L == R.getEnd())
164    return RangeOverlap;
165  if (SM.isBeforeInTranslationUnit(L, R.getBegin()))
166    return RangeBefore;
167  if (SM.isBeforeInTranslationUnit(R.getEnd(), L))
168    return RangeAfter;
169  return RangeOverlap;
170}
171
172/// \brief Translate a Clang source range into a CIndex source range.
173///
174/// Clang internally represents ranges where the end location points to the
175/// start of the token at the end. However, for external clients it is more
176/// useful to have a CXSourceRange be a proper half-open interval. This routine
177/// does the appropriate translation.
178CXSourceRange cxloc::translateSourceRange(const SourceManager &SM,
179                                          const LangOptions &LangOpts,
180                                          const CharSourceRange &R) {
181  // We want the last character in this location, so we will adjust the
182  // location accordingly.
183  // FIXME: How do do this with a macro instantiation location?
184  SourceLocation EndLoc = R.getEnd();
185  if (R.isTokenRange() && !EndLoc.isInvalid() && EndLoc.isFileID()) {
186    unsigned Length = Lexer::MeasureTokenLength(EndLoc, SM, LangOpts);
187    EndLoc = EndLoc.getFileLocWithOffset(Length);
188  }
189
190  CXSourceRange Result = { { (void *)&SM, (void *)&LangOpts },
191                           R.getBegin().getRawEncoding(),
192                           EndLoc.getRawEncoding() };
193  return Result;
194}
195
196//===----------------------------------------------------------------------===//
197// Cursor visitor.
198//===----------------------------------------------------------------------===//
199
200namespace {
201
202// Cursor visitor.
203class CursorVisitor : public DeclVisitor<CursorVisitor, bool>,
204                      public TypeLocVisitor<CursorVisitor, bool>,
205                      public StmtVisitor<CursorVisitor, bool>
206{
207  /// \brief The translation unit we are traversing.
208  ASTUnit *TU;
209
210  /// \brief The parent cursor whose children we are traversing.
211  CXCursor Parent;
212
213  /// \brief The declaration that serves at the parent of any statement or
214  /// expression nodes.
215  Decl *StmtParent;
216
217  /// \brief The visitor function.
218  CXCursorVisitor Visitor;
219
220  /// \brief The opaque client data, to be passed along to the visitor.
221  CXClientData ClientData;
222
223  // MaxPCHLevel - the maximum PCH level of declarations that we will pass on
224  // to the visitor. Declarations with a PCH level greater than this value will
225  // be suppressed.
226  unsigned MaxPCHLevel;
227
228  /// \brief When valid, a source range to which the cursor should restrict
229  /// its search.
230  SourceRange RegionOfInterest;
231
232  using DeclVisitor<CursorVisitor, bool>::Visit;
233  using TypeLocVisitor<CursorVisitor, bool>::Visit;
234  using StmtVisitor<CursorVisitor, bool>::Visit;
235
236  /// \brief Determine whether this particular source range comes before, comes
237  /// after, or overlaps the region of interest.
238  ///
239  /// \param R a half-open source range retrieved from the abstract syntax tree.
240  RangeComparisonResult CompareRegionOfInterest(SourceRange R);
241
242  class SetParentRAII {
243    CXCursor &Parent;
244    Decl *&StmtParent;
245    CXCursor OldParent;
246
247  public:
248    SetParentRAII(CXCursor &Parent, Decl *&StmtParent, CXCursor NewParent)
249      : Parent(Parent), StmtParent(StmtParent), OldParent(Parent)
250    {
251      Parent = NewParent;
252      if (clang_isDeclaration(Parent.kind))
253        StmtParent = getCursorDecl(Parent);
254    }
255
256    ~SetParentRAII() {
257      Parent = OldParent;
258      if (clang_isDeclaration(Parent.kind))
259        StmtParent = getCursorDecl(Parent);
260    }
261  };
262
263public:
264  CursorVisitor(ASTUnit *TU, CXCursorVisitor Visitor, CXClientData ClientData,
265                unsigned MaxPCHLevel,
266                SourceRange RegionOfInterest = SourceRange())
267    : TU(TU), Visitor(Visitor), ClientData(ClientData),
268      MaxPCHLevel(MaxPCHLevel), RegionOfInterest(RegionOfInterest)
269  {
270    Parent.kind = CXCursor_NoDeclFound;
271    Parent.data[0] = 0;
272    Parent.data[1] = 0;
273    Parent.data[2] = 0;
274    StmtParent = 0;
275  }
276
277  bool Visit(CXCursor Cursor, bool CheckedRegionOfInterest = false);
278
279  std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
280    getPreprocessedEntities();
281
282  bool VisitChildren(CXCursor Parent);
283
284  // Declaration visitors
285  bool VisitAttributes(Decl *D);
286  bool VisitBlockDecl(BlockDecl *B);
287  bool VisitDeclContext(DeclContext *DC);
288  bool VisitTranslationUnitDecl(TranslationUnitDecl *D);
289  bool VisitTypedefDecl(TypedefDecl *D);
290  bool VisitTagDecl(TagDecl *D);
291  bool VisitEnumConstantDecl(EnumConstantDecl *D);
292  bool VisitDeclaratorDecl(DeclaratorDecl *DD);
293  bool VisitFunctionDecl(FunctionDecl *ND);
294  bool VisitFieldDecl(FieldDecl *D);
295  bool VisitVarDecl(VarDecl *);
296  bool VisitObjCMethodDecl(ObjCMethodDecl *ND);
297  bool VisitObjCContainerDecl(ObjCContainerDecl *D);
298  bool VisitObjCCategoryDecl(ObjCCategoryDecl *ND);
299  bool VisitObjCProtocolDecl(ObjCProtocolDecl *PID);
300  bool VisitObjCPropertyDecl(ObjCPropertyDecl *PD);
301  bool VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
302  bool VisitObjCImplDecl(ObjCImplDecl *D);
303  bool VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
304  bool VisitObjCImplementationDecl(ObjCImplementationDecl *D);
305  // FIXME: ObjCPropertyDecl requires TypeSourceInfo, getter/setter locations,
306  // etc.
307  // FIXME: ObjCCompatibleAliasDecl requires aliased-class locations.
308  bool VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D);
309  bool VisitObjCClassDecl(ObjCClassDecl *D);
310  bool VisitLinkageSpecDecl(LinkageSpecDecl *D);
311  bool VisitNamespaceDecl(NamespaceDecl *D);
312
313  // Type visitors
314  // FIXME: QualifiedTypeLoc doesn't provide any location information
315  bool VisitBuiltinTypeLoc(BuiltinTypeLoc TL);
316  bool VisitTypedefTypeLoc(TypedefTypeLoc TL);
317  bool VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL);
318  bool VisitTagTypeLoc(TagTypeLoc TL);
319  // FIXME: TemplateTypeParmTypeLoc doesn't provide any location information
320  bool VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL);
321  bool VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL);
322  bool VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL);
323  bool VisitPointerTypeLoc(PointerTypeLoc TL);
324  bool VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL);
325  bool VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL);
326  bool VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL);
327  bool VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL);
328  bool VisitFunctionTypeLoc(FunctionTypeLoc TL);
329  bool VisitArrayTypeLoc(ArrayTypeLoc TL);
330  // FIXME: Implement for TemplateSpecializationTypeLoc
331  // FIXME: Implement visitors here when the unimplemented TypeLocs get
332  // implemented
333  bool VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL);
334  bool VisitTypeOfTypeLoc(TypeOfTypeLoc TL);
335
336  // Statement visitors
337  bool VisitStmt(Stmt *S);
338  bool VisitDeclStmt(DeclStmt *S);
339  // FIXME: LabelStmt label?
340  bool VisitIfStmt(IfStmt *S);
341  bool VisitSwitchStmt(SwitchStmt *S);
342  bool VisitCaseStmt(CaseStmt *S);
343  bool VisitWhileStmt(WhileStmt *S);
344  bool VisitForStmt(ForStmt *S);
345//  bool VisitSwitchCase(SwitchCase *S);
346
347  // Expression visitors
348  // FIXME: DeclRefExpr with template arguments, nested-name-specifier
349  // FIXME: MemberExpr with template arguments, nested-name-specifier
350  bool VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E);
351  bool VisitBlockExpr(BlockExpr *B);
352  bool VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
353  bool VisitExplicitCastExpr(ExplicitCastExpr *E);
354  bool VisitObjCMessageExpr(ObjCMessageExpr *E);
355  bool VisitObjCEncodeExpr(ObjCEncodeExpr *E);
356  bool VisitOffsetOfExpr(OffsetOfExpr *E);
357  bool VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E);
358  // FIXME: AddrLabelExpr (once we have cursors for labels)
359  bool VisitTypesCompatibleExpr(TypesCompatibleExpr *E);
360  bool VisitVAArgExpr(VAArgExpr *E);
361  // FIXME: InitListExpr (for the designators)
362  // FIXME: DesignatedInitExpr
363};
364
365} // end anonymous namespace
366
367static SourceRange getRawCursorExtent(CXCursor C);
368
369RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
370  return RangeCompare(TU->getSourceManager(), R, RegionOfInterest);
371}
372
373/// \brief Visit the given cursor and, if requested by the visitor,
374/// its children.
375///
376/// \param Cursor the cursor to visit.
377///
378/// \param CheckRegionOfInterest if true, then the caller already checked that
379/// this cursor is within the region of interest.
380///
381/// \returns true if the visitation should be aborted, false if it
382/// should continue.
383bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
384  if (clang_isInvalid(Cursor.kind))
385    return false;
386
387  if (clang_isDeclaration(Cursor.kind)) {
388    Decl *D = getCursorDecl(Cursor);
389    assert(D && "Invalid declaration cursor");
390    if (D->getPCHLevel() > MaxPCHLevel)
391      return false;
392
393    if (D->isImplicit())
394      return false;
395  }
396
397  // If we have a range of interest, and this cursor doesn't intersect with it,
398  // we're done.
399  if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
400    SourceRange Range = getRawCursorExtent(Cursor);
401    if (Range.isInvalid() || CompareRegionOfInterest(Range))
402      return false;
403  }
404
405  switch (Visitor(Cursor, Parent, ClientData)) {
406  case CXChildVisit_Break:
407    return true;
408
409  case CXChildVisit_Continue:
410    return false;
411
412  case CXChildVisit_Recurse:
413    return VisitChildren(Cursor);
414  }
415
416  return false;
417}
418
419std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
420CursorVisitor::getPreprocessedEntities() {
421  PreprocessingRecord &PPRec
422    = *TU->getPreprocessor().getPreprocessingRecord();
423
424  bool OnlyLocalDecls
425    = !TU->isMainFileAST() && TU->getOnlyLocalDecls();
426
427  // There is no region of interest; we have to walk everything.
428  if (RegionOfInterest.isInvalid())
429    return std::make_pair(PPRec.begin(OnlyLocalDecls),
430                          PPRec.end(OnlyLocalDecls));
431
432  // Find the file in which the region of interest lands.
433  SourceManager &SM = TU->getSourceManager();
434  std::pair<FileID, unsigned> Begin
435    = SM.getDecomposedInstantiationLoc(RegionOfInterest.getBegin());
436  std::pair<FileID, unsigned> End
437    = SM.getDecomposedInstantiationLoc(RegionOfInterest.getEnd());
438
439  // The region of interest spans files; we have to walk everything.
440  if (Begin.first != End.first)
441    return std::make_pair(PPRec.begin(OnlyLocalDecls),
442                          PPRec.end(OnlyLocalDecls));
443
444  ASTUnit::PreprocessedEntitiesByFileMap &ByFileMap
445    = TU->getPreprocessedEntitiesByFile();
446  if (ByFileMap.empty()) {
447    // Build the mapping from files to sets of preprocessed entities.
448    for (PreprocessingRecord::iterator E = PPRec.begin(OnlyLocalDecls),
449                                    EEnd = PPRec.end(OnlyLocalDecls);
450         E != EEnd; ++E) {
451      std::pair<FileID, unsigned> P
452        = SM.getDecomposedInstantiationLoc((*E)->getSourceRange().getBegin());
453      ByFileMap[P.first].push_back(*E);
454    }
455  }
456
457  return std::make_pair(ByFileMap[Begin.first].begin(),
458                        ByFileMap[Begin.first].end());
459}
460
461/// \brief Visit the children of the given cursor.
462///
463/// \returns true if the visitation should be aborted, false if it
464/// should continue.
465bool CursorVisitor::VisitChildren(CXCursor Cursor) {
466  if (clang_isReference(Cursor.kind)) {
467    // By definition, references have no children.
468    return false;
469  }
470
471  // Set the Parent field to Cursor, then back to its old value once we're
472  // done.
473  SetParentRAII SetParent(Parent, StmtParent, Cursor);
474
475  if (clang_isDeclaration(Cursor.kind)) {
476    Decl *D = getCursorDecl(Cursor);
477    assert(D && "Invalid declaration cursor");
478    return VisitAttributes(D) || Visit(D);
479  }
480
481  if (clang_isStatement(Cursor.kind))
482    return Visit(getCursorStmt(Cursor));
483  if (clang_isExpression(Cursor.kind))
484    return Visit(getCursorExpr(Cursor));
485
486  if (clang_isTranslationUnit(Cursor.kind)) {
487    ASTUnit *CXXUnit = getCursorASTUnit(Cursor);
488    if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
489        RegionOfInterest.isInvalid()) {
490      for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(),
491                                    TLEnd = CXXUnit->top_level_end();
492           TL != TLEnd; ++TL) {
493        if (Visit(MakeCXCursor(*TL, CXXUnit), true))
494          return true;
495      }
496    } else if (VisitDeclContext(
497                            CXXUnit->getASTContext().getTranslationUnitDecl()))
498      return true;
499
500    // Walk the preprocessing record.
501    if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
502      // FIXME: Once we have the ability to deserialize a preprocessing record,
503      // do so.
504      PreprocessingRecord::iterator E, EEnd;
505      for (llvm::tie(E, EEnd) = getPreprocessedEntities(); E != EEnd; ++E) {
506        if (MacroInstantiation *MI = dyn_cast<MacroInstantiation>(*E)) {
507          if (Visit(MakeMacroInstantiationCursor(MI, CXXUnit)))
508            return true;
509
510          continue;
511        }
512
513        if (MacroDefinition *MD = dyn_cast<MacroDefinition>(*E)) {
514          if (Visit(MakeMacroDefinitionCursor(MD, CXXUnit)))
515            return true;
516
517          continue;
518        }
519      }
520    }
521    return false;
522  }
523
524  // Nothing to visit at the moment.
525  return false;
526}
527
528bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
529  if (Visit(B->getSignatureAsWritten()->getTypeLoc()))
530    return true;
531
532  if (Stmt *Body = B->getBody())
533    return Visit(MakeCXCursor(Body, StmtParent, TU));
534
535  return false;
536}
537
538bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
539  for (DeclContext::decl_iterator
540       I = DC->decls_begin(), E = DC->decls_end(); I != E; ++I) {
541
542    Decl *D = *I;
543    if (D->getLexicalDeclContext() != DC)
544      continue;
545
546    CXCursor Cursor = MakeCXCursor(D, TU);
547
548    if (RegionOfInterest.isValid()) {
549      SourceRange Range = getRawCursorExtent(Cursor);
550      if (Range.isInvalid())
551        continue;
552
553      switch (CompareRegionOfInterest(Range)) {
554      case RangeBefore:
555        // This declaration comes before the region of interest; skip it.
556        continue;
557
558      case RangeAfter:
559        // This declaration comes after the region of interest; we're done.
560        return false;
561
562      case RangeOverlap:
563        // This declaration overlaps the region of interest; visit it.
564        break;
565      }
566    }
567
568    if (Visit(Cursor, true))
569      return true;
570  }
571
572  return false;
573}
574
575bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
576  llvm_unreachable("Translation units are visited directly by Visit()");
577  return false;
578}
579
580bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
581  if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
582    return Visit(TSInfo->getTypeLoc());
583
584  return false;
585}
586
587bool CursorVisitor::VisitTagDecl(TagDecl *D) {
588  return VisitDeclContext(D);
589}
590
591bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
592  if (Expr *Init = D->getInitExpr())
593    return Visit(MakeCXCursor(Init, StmtParent, TU));
594  return false;
595}
596
597bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
598  if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
599    if (Visit(TSInfo->getTypeLoc()))
600      return true;
601
602  return false;
603}
604
605bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
606  if (VisitDeclaratorDecl(ND))
607    return true;
608
609  if (ND->isThisDeclarationADefinition() &&
610      Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
611    return true;
612
613  return false;
614}
615
616bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
617  if (VisitDeclaratorDecl(D))
618    return true;
619
620  if (Expr *BitWidth = D->getBitWidth())
621    return Visit(MakeCXCursor(BitWidth, StmtParent, TU));
622
623  return false;
624}
625
626bool CursorVisitor::VisitVarDecl(VarDecl *D) {
627  if (VisitDeclaratorDecl(D))
628    return true;
629
630  if (Expr *Init = D->getInit())
631    return Visit(MakeCXCursor(Init, StmtParent, TU));
632
633  return false;
634}
635
636bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
637  if (TypeSourceInfo *TSInfo = ND->getResultTypeSourceInfo())
638    if (Visit(TSInfo->getTypeLoc()))
639      return true;
640
641  for (ObjCMethodDecl::param_iterator P = ND->param_begin(),
642       PEnd = ND->param_end();
643       P != PEnd; ++P) {
644    if (Visit(MakeCXCursor(*P, TU)))
645      return true;
646  }
647
648  if (ND->isThisDeclarationADefinition() &&
649      Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
650    return true;
651
652  return false;
653}
654
655bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
656  return VisitDeclContext(D);
657}
658
659bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
660  if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
661                                   TU)))
662    return true;
663
664  ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
665  for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
666         E = ND->protocol_end(); I != E; ++I, ++PL)
667    if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
668      return true;
669
670  return VisitObjCContainerDecl(ND);
671}
672
673bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
674  ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
675  for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
676       E = PID->protocol_end(); I != E; ++I, ++PL)
677    if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
678      return true;
679
680  return VisitObjCContainerDecl(PID);
681}
682
683bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
684  if (Visit(PD->getTypeSourceInfo()->getTypeLoc()))
685    return true;
686
687  // FIXME: This implements a workaround with @property declarations also being
688  // installed in the DeclContext for the @interface.  Eventually this code
689  // should be removed.
690  ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
691  if (!CDecl || !CDecl->IsClassExtension())
692    return false;
693
694  ObjCInterfaceDecl *ID = CDecl->getClassInterface();
695  if (!ID)
696    return false;
697
698  IdentifierInfo *PropertyId = PD->getIdentifier();
699  ObjCPropertyDecl *prevDecl =
700    ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId);
701
702  if (!prevDecl)
703    return false;
704
705  // Visit synthesized methods since they will be skipped when visiting
706  // the @interface.
707  if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
708    if (MD->isSynthesized())
709      if (Visit(MakeCXCursor(MD, TU)))
710        return true;
711
712  if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
713    if (MD->isSynthesized())
714      if (Visit(MakeCXCursor(MD, TU)))
715        return true;
716
717  return false;
718}
719
720bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
721  // Issue callbacks for super class.
722  if (D->getSuperClass() &&
723      Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
724                                        D->getSuperClassLoc(),
725                                        TU)))
726    return true;
727
728  ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
729  for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
730         E = D->protocol_end(); I != E; ++I, ++PL)
731    if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
732      return true;
733
734  return VisitObjCContainerDecl(D);
735}
736
737bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
738  return VisitObjCContainerDecl(D);
739}
740
741bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
742  // 'ID' could be null when dealing with invalid code.
743  if (ObjCInterfaceDecl *ID = D->getClassInterface())
744    if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
745      return true;
746
747  return VisitObjCImplDecl(D);
748}
749
750bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
751#if 0
752  // Issue callbacks for super class.
753  // FIXME: No source location information!
754  if (D->getSuperClass() &&
755      Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
756                                        D->getSuperClassLoc(),
757                                        TU)))
758    return true;
759#endif
760
761  return VisitObjCImplDecl(D);
762}
763
764bool CursorVisitor::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D) {
765  ObjCForwardProtocolDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
766  for (ObjCForwardProtocolDecl::protocol_iterator I = D->protocol_begin(),
767                                                  E = D->protocol_end();
768       I != E; ++I, ++PL)
769    if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
770      return true;
771
772  return false;
773}
774
775bool CursorVisitor::VisitObjCClassDecl(ObjCClassDecl *D) {
776  for (ObjCClassDecl::iterator C = D->begin(), CEnd = D->end(); C != CEnd; ++C)
777    if (Visit(MakeCursorObjCClassRef(C->getInterface(), C->getLocation(), TU)))
778      return true;
779
780  return false;
781}
782
783bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
784  return VisitDeclContext(D);
785}
786
787bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
788  return VisitDeclContext(D);
789}
790
791bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
792  ASTContext &Context = TU->getASTContext();
793
794  // Some builtin types (such as Objective-C's "id", "sel", and
795  // "Class") have associated declarations. Create cursors for those.
796  QualType VisitType;
797  switch (TL.getType()->getAs<BuiltinType>()->getKind()) {
798  case BuiltinType::Void:
799  case BuiltinType::Bool:
800  case BuiltinType::Char_U:
801  case BuiltinType::UChar:
802  case BuiltinType::Char16:
803  case BuiltinType::Char32:
804  case BuiltinType::UShort:
805  case BuiltinType::UInt:
806  case BuiltinType::ULong:
807  case BuiltinType::ULongLong:
808  case BuiltinType::UInt128:
809  case BuiltinType::Char_S:
810  case BuiltinType::SChar:
811  case BuiltinType::WChar:
812  case BuiltinType::Short:
813  case BuiltinType::Int:
814  case BuiltinType::Long:
815  case BuiltinType::LongLong:
816  case BuiltinType::Int128:
817  case BuiltinType::Float:
818  case BuiltinType::Double:
819  case BuiltinType::LongDouble:
820  case BuiltinType::NullPtr:
821  case BuiltinType::Overload:
822  case BuiltinType::Dependent:
823    break;
824
825  case BuiltinType::UndeducedAuto: // FIXME: Deserves a cursor?
826    break;
827
828  case BuiltinType::ObjCId:
829    VisitType = Context.getObjCIdType();
830    break;
831
832  case BuiltinType::ObjCClass:
833    VisitType = Context.getObjCClassType();
834    break;
835
836  case BuiltinType::ObjCSel:
837    VisitType = Context.getObjCSelType();
838    break;
839  }
840
841  if (!VisitType.isNull()) {
842    if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
843      return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
844                                     TU));
845  }
846
847  return false;
848}
849
850bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
851  return Visit(MakeCursorTypeRef(TL.getTypedefDecl(), TL.getNameLoc(), TU));
852}
853
854bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
855  return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
856}
857
858bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
859  return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
860}
861
862bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
863  if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
864    return true;
865
866  return false;
867}
868
869bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
870  if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
871    return true;
872
873  for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
874    if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
875                                        TU)))
876      return true;
877  }
878
879  return false;
880}
881
882bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
883  return Visit(TL.getPointeeLoc());
884}
885
886bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
887  return Visit(TL.getPointeeLoc());
888}
889
890bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
891  return Visit(TL.getPointeeLoc());
892}
893
894bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
895  return Visit(TL.getPointeeLoc());
896}
897
898bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
899  return Visit(TL.getPointeeLoc());
900}
901
902bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
903  return Visit(TL.getPointeeLoc());
904}
905
906bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
907  if (Visit(TL.getResultLoc()))
908    return true;
909
910  for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
911    if (Decl *D = TL.getArg(I))
912      if (Visit(MakeCXCursor(D, TU)))
913        return true;
914
915  return false;
916}
917
918bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
919  if (Visit(TL.getElementLoc()))
920    return true;
921
922  if (Expr *Size = TL.getSizeExpr())
923    return Visit(MakeCXCursor(Size, StmtParent, TU));
924
925  return false;
926}
927
928bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
929  return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
930}
931
932bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
933  if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
934    return Visit(TSInfo->getTypeLoc());
935
936  return false;
937}
938
939bool CursorVisitor::VisitStmt(Stmt *S) {
940  for (Stmt::child_iterator Child = S->child_begin(), ChildEnd = S->child_end();
941       Child != ChildEnd; ++Child) {
942    if (Stmt *C = *Child)
943      if (Visit(MakeCXCursor(C, StmtParent, TU)))
944        return true;
945  }
946
947  return false;
948}
949
950bool CursorVisitor::VisitCaseStmt(CaseStmt *S) {
951  // Specially handle CaseStmts because they can be nested, e.g.:
952  //
953  //    case 1:
954  //    case 2:
955  //
956  // In this case the second CaseStmt is the child of the first.  Walking
957  // these recursively can blow out the stack.
958  CXCursor Cursor = MakeCXCursor(S, StmtParent, TU);
959  while (true) {
960    // Set the Parent field to Cursor, then back to its old value once we're
961    //   done.
962    SetParentRAII SetParent(Parent, StmtParent, Cursor);
963
964    if (Stmt *LHS = S->getLHS())
965      if (Visit(MakeCXCursor(LHS, StmtParent, TU)))
966        return true;
967    if (Stmt *RHS = S->getRHS())
968      if (Visit(MakeCXCursor(RHS, StmtParent, TU)))
969        return true;
970    if (Stmt *SubStmt = S->getSubStmt()) {
971      if (!isa<CaseStmt>(SubStmt))
972        return Visit(MakeCXCursor(SubStmt, StmtParent, TU));
973
974      // Specially handle 'CaseStmt' so that we don't blow out the stack.
975      CaseStmt *CS = cast<CaseStmt>(SubStmt);
976      Cursor = MakeCXCursor(CS, StmtParent, TU);
977      if (RegionOfInterest.isValid()) {
978        SourceRange Range = CS->getSourceRange();
979        if (Range.isInvalid() || CompareRegionOfInterest(Range))
980          return false;
981      }
982
983      switch (Visitor(Cursor, Parent, ClientData)) {
984        case CXChildVisit_Break: return true;
985        case CXChildVisit_Continue: return false;
986        case CXChildVisit_Recurse:
987          // Perform tail-recursion manually.
988          S = CS;
989          continue;
990      }
991    }
992    return false;
993  }
994}
995
996bool CursorVisitor::VisitDeclStmt(DeclStmt *S) {
997  for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
998       D != DEnd; ++D) {
999    if (*D && Visit(MakeCXCursor(*D, TU)))
1000      return true;
1001  }
1002
1003  return false;
1004}
1005
1006bool CursorVisitor::VisitIfStmt(IfStmt *S) {
1007  if (VarDecl *Var = S->getConditionVariable()) {
1008    if (Visit(MakeCXCursor(Var, TU)))
1009      return true;
1010  }
1011
1012  if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1013    return true;
1014  if (S->getThen() && Visit(MakeCXCursor(S->getThen(), StmtParent, TU)))
1015    return true;
1016  if (S->getElse() && Visit(MakeCXCursor(S->getElse(), StmtParent, TU)))
1017    return true;
1018
1019  return false;
1020}
1021
1022bool CursorVisitor::VisitSwitchStmt(SwitchStmt *S) {
1023  if (VarDecl *Var = S->getConditionVariable()) {
1024    if (Visit(MakeCXCursor(Var, TU)))
1025      return true;
1026  }
1027
1028  if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1029    return true;
1030  if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
1031    return true;
1032
1033  return false;
1034}
1035
1036bool CursorVisitor::VisitWhileStmt(WhileStmt *S) {
1037  if (VarDecl *Var = S->getConditionVariable()) {
1038    if (Visit(MakeCXCursor(Var, TU)))
1039      return true;
1040  }
1041
1042  if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1043    return true;
1044  if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
1045    return true;
1046
1047  return false;
1048}
1049
1050bool CursorVisitor::VisitForStmt(ForStmt *S) {
1051  if (S->getInit() && Visit(MakeCXCursor(S->getInit(), StmtParent, TU)))
1052    return true;
1053  if (VarDecl *Var = S->getConditionVariable()) {
1054    if (Visit(MakeCXCursor(Var, TU)))
1055      return true;
1056  }
1057
1058  if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1059    return true;
1060  if (S->getInc() && Visit(MakeCXCursor(S->getInc(), StmtParent, TU)))
1061    return true;
1062  if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
1063    return true;
1064
1065  return false;
1066}
1067
1068bool CursorVisitor::VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
1069  if (Visit(MakeCXCursor(E->getArg(0), StmtParent, TU)))
1070    return true;
1071
1072  if (Visit(MakeCXCursor(E->getCallee(), StmtParent, TU)))
1073    return true;
1074
1075  for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I)
1076    if (Visit(MakeCXCursor(E->getArg(I), StmtParent, TU)))
1077      return true;
1078
1079  return false;
1080}
1081
1082bool CursorVisitor::VisitBlockExpr(BlockExpr *B) {
1083  return Visit(B->getBlockDecl());
1084}
1085
1086bool CursorVisitor::VisitOffsetOfExpr(OffsetOfExpr *E) {
1087  // FIXME: Visit fields as well?
1088  if (Visit(E->getTypeSourceInfo()->getTypeLoc()))
1089    return true;
1090
1091  return VisitExpr(E);
1092}
1093
1094bool CursorVisitor::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E) {
1095  if (E->isArgumentType()) {
1096    if (TypeSourceInfo *TSInfo = E->getArgumentTypeInfo())
1097      return Visit(TSInfo->getTypeLoc());
1098
1099    return false;
1100  }
1101
1102  return VisitExpr(E);
1103}
1104
1105bool CursorVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
1106  if (TypeSourceInfo *TSInfo = E->getTypeInfoAsWritten())
1107    if (Visit(TSInfo->getTypeLoc()))
1108      return true;
1109
1110  return VisitCastExpr(E);
1111}
1112
1113bool CursorVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
1114  if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
1115    if (Visit(TSInfo->getTypeLoc()))
1116      return true;
1117
1118  return VisitExpr(E);
1119}
1120
1121bool CursorVisitor::VisitTypesCompatibleExpr(TypesCompatibleExpr *E) {
1122  return Visit(E->getArgTInfo1()->getTypeLoc()) ||
1123         Visit(E->getArgTInfo2()->getTypeLoc());
1124}
1125
1126bool CursorVisitor::VisitVAArgExpr(VAArgExpr *E) {
1127  if (Visit(E->getWrittenTypeInfo()->getTypeLoc()))
1128    return true;
1129
1130  return Visit(MakeCXCursor(E->getSubExpr(), StmtParent, TU));
1131}
1132
1133bool CursorVisitor::VisitObjCMessageExpr(ObjCMessageExpr *E) {
1134  if (TypeSourceInfo *TSInfo = E->getClassReceiverTypeInfo())
1135    if (Visit(TSInfo->getTypeLoc()))
1136      return true;
1137
1138  return VisitExpr(E);
1139}
1140
1141bool CursorVisitor::VisitObjCEncodeExpr(ObjCEncodeExpr *E) {
1142  return Visit(E->getEncodedTypeSourceInfo()->getTypeLoc());
1143}
1144
1145
1146bool CursorVisitor::VisitAttributes(Decl *D) {
1147  for (const Attr *A = D->getAttrs(); A; A = A->getNext())
1148    if (Visit(MakeCXCursor(A, D, TU)))
1149        return true;
1150
1151  return false;
1152}
1153
1154extern "C" {
1155CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
1156                          int displayDiagnostics) {
1157  // We use crash recovery to make some of our APIs more reliable, implicitly
1158  // enable it.
1159  llvm::CrashRecoveryContext::Enable();
1160
1161  CIndexer *CIdxr = new CIndexer();
1162  if (excludeDeclarationsFromPCH)
1163    CIdxr->setOnlyLocalDecls();
1164  if (displayDiagnostics)
1165    CIdxr->setDisplayDiagnostics();
1166  return CIdxr;
1167}
1168
1169void clang_disposeIndex(CXIndex CIdx) {
1170  if (CIdx)
1171    delete static_cast<CIndexer *>(CIdx);
1172  if (getenv("LIBCLANG_TIMING"))
1173    llvm::TimerGroup::printAll(llvm::errs());
1174}
1175
1176void clang_setUseExternalASTGeneration(CXIndex CIdx, int value) {
1177  if (CIdx) {
1178    CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
1179    CXXIdx->setUseExternalASTGeneration(value);
1180  }
1181}
1182
1183CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
1184                                              const char *ast_filename) {
1185  if (!CIdx)
1186    return 0;
1187
1188  CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
1189
1190  llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
1191  return ASTUnit::LoadFromPCHFile(ast_filename, Diags,
1192                                  CXXIdx->getOnlyLocalDecls(),
1193                                  0, 0, true);
1194}
1195
1196unsigned clang_defaultEditingTranslationUnitOptions() {
1197  return CXTranslationUnit_PrecompiledPreamble;
1198}
1199
1200CXTranslationUnit
1201clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
1202                                          const char *source_filename,
1203                                          int num_command_line_args,
1204                                          const char **command_line_args,
1205                                          unsigned num_unsaved_files,
1206                                          struct CXUnsavedFile *unsaved_files) {
1207  return clang_parseTranslationUnit(CIdx, source_filename,
1208                                    command_line_args, num_command_line_args,
1209                                    unsaved_files, num_unsaved_files,
1210                                 CXTranslationUnit_DetailedPreprocessingRecord);
1211}
1212
1213struct ParseTranslationUnitInfo {
1214  CXIndex CIdx;
1215  const char *source_filename;
1216  const char **command_line_args;
1217  int num_command_line_args;
1218  struct CXUnsavedFile *unsaved_files;
1219  unsigned num_unsaved_files;
1220  unsigned options;
1221  CXTranslationUnit result;
1222};
1223void clang_parseTranslationUnit_Impl(void *UserData) {
1224  ParseTranslationUnitInfo *PTUI =
1225    static_cast<ParseTranslationUnitInfo*>(UserData);
1226  CXIndex CIdx = PTUI->CIdx;
1227  const char *source_filename = PTUI->source_filename;
1228  const char **command_line_args = PTUI->command_line_args;
1229  int num_command_line_args = PTUI->num_command_line_args;
1230  struct CXUnsavedFile *unsaved_files = PTUI->unsaved_files;
1231  unsigned num_unsaved_files = PTUI->num_unsaved_files;
1232  unsigned options = PTUI->options;
1233  PTUI->result = 0;
1234
1235  if (!CIdx)
1236    return;
1237
1238  CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
1239
1240  bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
1241  bool CompleteTranslationUnit
1242    = ((options & CXTranslationUnit_Incomplete) == 0);
1243  bool CacheCodeCompetionResults
1244    = options & CXTranslationUnit_CacheCompletionResults;
1245
1246  // Configure the diagnostics.
1247  DiagnosticOptions DiagOpts;
1248  llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
1249  Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
1250
1251  llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
1252  for (unsigned I = 0; I != num_unsaved_files; ++I) {
1253    llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
1254    const llvm::MemoryBuffer *Buffer
1255      = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
1256    RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
1257                                           Buffer));
1258  }
1259
1260  if (!CXXIdx->getUseExternalASTGeneration()) {
1261    llvm::SmallVector<const char *, 16> Args;
1262
1263    // The 'source_filename' argument is optional.  If the caller does not
1264    // specify it then it is assumed that the source file is specified
1265    // in the actual argument list.
1266    if (source_filename)
1267      Args.push_back(source_filename);
1268
1269    // Since the Clang C library is primarily used by batch tools dealing with
1270    // (often very broken) source code, where spell-checking can have a
1271    // significant negative impact on performance (particularly when
1272    // precompiled headers are involved), we disable it by default.
1273    // Note that we place this argument early in the list, so that it can be
1274    // overridden by the caller with "-fspell-checking".
1275    Args.push_back("-fno-spell-checking");
1276
1277    Args.insert(Args.end(), command_line_args,
1278                command_line_args + num_command_line_args);
1279
1280    // Do we need the detailed preprocessing record?
1281    if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
1282      Args.push_back("-Xclang");
1283      Args.push_back("-detailed-preprocessing-record");
1284    }
1285
1286    unsigned NumErrors = Diags->getNumErrors();
1287
1288#ifdef USE_CRASHTRACER
1289    ArgsCrashTracerInfo ACTI(Args);
1290#endif
1291
1292    llvm::OwningPtr<ASTUnit> Unit(
1293      ASTUnit::LoadFromCommandLine(Args.data(), Args.data() + Args.size(),
1294                                   Diags,
1295                                   CXXIdx->getClangResourcesPath(),
1296                                   CXXIdx->getOnlyLocalDecls(),
1297                                   RemappedFiles.data(),
1298                                   RemappedFiles.size(),
1299                                   /*CaptureDiagnostics=*/true,
1300                                   PrecompilePreamble,
1301                                   CompleteTranslationUnit,
1302                                   CacheCodeCompetionResults));
1303
1304    if (NumErrors != Diags->getNumErrors()) {
1305      // Make sure to check that 'Unit' is non-NULL.
1306      if (CXXIdx->getDisplayDiagnostics() && Unit.get()) {
1307        for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
1308                                        DEnd = Unit->stored_diag_end();
1309             D != DEnd; ++D) {
1310          CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOptions());
1311          CXString Msg = clang_formatDiagnostic(&Diag,
1312                                      clang_defaultDiagnosticDisplayOptions());
1313          fprintf(stderr, "%s\n", clang_getCString(Msg));
1314          clang_disposeString(Msg);
1315        }
1316#ifdef LLVM_ON_WIN32
1317        // On Windows, force a flush, since there may be multiple copies of
1318        // stderr and stdout in the file system, all with different buffers
1319        // but writing to the same device.
1320        fflush(stderr);
1321#endif
1322      }
1323    }
1324
1325    PTUI->result = Unit.take();
1326    return;
1327  }
1328
1329  // Build up the arguments for invoking 'clang'.
1330  std::vector<const char *> argv;
1331
1332  // First add the complete path to the 'clang' executable.
1333  llvm::sys::Path ClangPath = static_cast<CIndexer *>(CIdx)->getClangPath();
1334  argv.push_back(ClangPath.c_str());
1335
1336  // Add the '-emit-ast' option as our execution mode for 'clang'.
1337  argv.push_back("-emit-ast");
1338
1339  // The 'source_filename' argument is optional.  If the caller does not
1340  // specify it then it is assumed that the source file is specified
1341  // in the actual argument list.
1342  if (source_filename)
1343    argv.push_back(source_filename);
1344
1345  // Generate a temporary name for the AST file.
1346  argv.push_back("-o");
1347  char astTmpFile[L_tmpnam];
1348  argv.push_back(tmpnam(astTmpFile));
1349
1350  // Since the Clang C library is primarily used by batch tools dealing with
1351  // (often very broken) source code, where spell-checking can have a
1352  // significant negative impact on performance (particularly when
1353  // precompiled headers are involved), we disable it by default.
1354  // Note that we place this argument early in the list, so that it can be
1355  // overridden by the caller with "-fspell-checking".
1356  argv.push_back("-fno-spell-checking");
1357
1358  // Remap any unsaved files to temporary files.
1359  std::vector<llvm::sys::Path> TemporaryFiles;
1360  std::vector<std::string> RemapArgs;
1361  if (RemapFiles(num_unsaved_files, unsaved_files, RemapArgs, TemporaryFiles))
1362    return;
1363
1364  // The pointers into the elements of RemapArgs are stable because we
1365  // won't be adding anything to RemapArgs after this point.
1366  for (unsigned i = 0, e = RemapArgs.size(); i != e; ++i)
1367    argv.push_back(RemapArgs[i].c_str());
1368
1369  // Process the compiler options, stripping off '-o', '-c', '-fsyntax-only'.
1370  for (int i = 0; i < num_command_line_args; ++i)
1371    if (const char *arg = command_line_args[i]) {
1372      if (strcmp(arg, "-o") == 0) {
1373        ++i; // Also skip the matching argument.
1374        continue;
1375      }
1376      if (strcmp(arg, "-emit-ast") == 0 ||
1377          strcmp(arg, "-c") == 0 ||
1378          strcmp(arg, "-fsyntax-only") == 0) {
1379        continue;
1380      }
1381
1382      // Keep the argument.
1383      argv.push_back(arg);
1384    }
1385
1386  // Generate a temporary name for the diagnostics file.
1387  char tmpFileResults[L_tmpnam];
1388  char *tmpResultsFileName = tmpnam(tmpFileResults);
1389  llvm::sys::Path DiagnosticsFile(tmpResultsFileName);
1390  TemporaryFiles.push_back(DiagnosticsFile);
1391  argv.push_back("-fdiagnostics-binary");
1392
1393  // Do we need the detailed preprocessing record?
1394  if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
1395    argv.push_back("-Xclang");
1396    argv.push_back("-detailed-preprocessing-record");
1397  }
1398
1399  // Add the null terminator.
1400  argv.push_back(NULL);
1401
1402  // Invoke 'clang'.
1403  llvm::sys::Path DevNull; // leave empty, causes redirection to /dev/null
1404                           // on Unix or NUL (Windows).
1405  std::string ErrMsg;
1406  const llvm::sys::Path *Redirects[] = { &DevNull, &DevNull, &DiagnosticsFile,
1407                                         NULL };
1408  llvm::sys::Program::ExecuteAndWait(ClangPath, &argv[0], /* env */ NULL,
1409      /* redirects */ &Redirects[0],
1410      /* secondsToWait */ 0, /* memoryLimits */ 0, &ErrMsg);
1411
1412  if (!ErrMsg.empty()) {
1413    std::string AllArgs;
1414    for (std::vector<const char*>::iterator I = argv.begin(), E = argv.end();
1415         I != E; ++I) {
1416      AllArgs += ' ';
1417      if (*I)
1418        AllArgs += *I;
1419    }
1420
1421    Diags->Report(diag::err_fe_invoking) << AllArgs << ErrMsg;
1422  }
1423
1424  ASTUnit *ATU = ASTUnit::LoadFromPCHFile(astTmpFile, Diags,
1425                                          CXXIdx->getOnlyLocalDecls(),
1426                                          RemappedFiles.data(),
1427                                          RemappedFiles.size(),
1428                                          /*CaptureDiagnostics=*/true);
1429  if (ATU) {
1430    LoadSerializedDiagnostics(DiagnosticsFile,
1431                              num_unsaved_files, unsaved_files,
1432                              ATU->getFileManager(),
1433                              ATU->getSourceManager(),
1434                              ATU->getStoredDiagnostics());
1435  } else if (CXXIdx->getDisplayDiagnostics()) {
1436    // We failed to load the ASTUnit, but we can still deserialize the
1437    // diagnostics and emit them.
1438    FileManager FileMgr;
1439    Diagnostic Diag;
1440    SourceManager SourceMgr(Diag);
1441    // FIXME: Faked LangOpts!
1442    LangOptions LangOpts;
1443    llvm::SmallVector<StoredDiagnostic, 4> Diags;
1444    LoadSerializedDiagnostics(DiagnosticsFile,
1445                              num_unsaved_files, unsaved_files,
1446                              FileMgr, SourceMgr, Diags);
1447    for (llvm::SmallVector<StoredDiagnostic, 4>::iterator D = Diags.begin(),
1448                                                       DEnd = Diags.end();
1449         D != DEnd; ++D) {
1450      CXStoredDiagnostic Diag(*D, LangOpts);
1451      CXString Msg = clang_formatDiagnostic(&Diag,
1452                                      clang_defaultDiagnosticDisplayOptions());
1453      fprintf(stderr, "%s\n", clang_getCString(Msg));
1454      clang_disposeString(Msg);
1455    }
1456
1457#ifdef LLVM_ON_WIN32
1458    // On Windows, force a flush, since there may be multiple copies of
1459    // stderr and stdout in the file system, all with different buffers
1460    // but writing to the same device.
1461    fflush(stderr);
1462#endif
1463  }
1464
1465  if (ATU) {
1466    // Make the translation unit responsible for destroying all temporary files.
1467    for (unsigned i = 0, e = TemporaryFiles.size(); i != e; ++i)
1468      ATU->addTemporaryFile(TemporaryFiles[i]);
1469    ATU->addTemporaryFile(llvm::sys::Path(ATU->getPCHFileName()));
1470  } else {
1471    // Destroy all of the temporary files now; they can't be referenced any
1472    // longer.
1473    llvm::sys::Path(astTmpFile).eraseFromDisk();
1474    for (unsigned i = 0, e = TemporaryFiles.size(); i != e; ++i)
1475      TemporaryFiles[i].eraseFromDisk();
1476  }
1477
1478  PTUI->result = ATU;
1479}
1480CXTranslationUnit clang_parseTranslationUnit(CXIndex CIdx,
1481                                             const char *source_filename,
1482                                             const char **command_line_args,
1483                                             int num_command_line_args,
1484                                             struct CXUnsavedFile *unsaved_files,
1485                                             unsigned num_unsaved_files,
1486                                             unsigned options) {
1487  ParseTranslationUnitInfo PTUI = { CIdx, source_filename, command_line_args,
1488                                    num_command_line_args, unsaved_files, num_unsaved_files,
1489                                    options, 0 };
1490  llvm::CrashRecoveryContext CRC;
1491
1492  if (!CRC.RunSafely(clang_parseTranslationUnit_Impl, &PTUI)) {
1493    // FIXME: Find a way to report the crash.
1494    return 0;
1495  }
1496
1497  return PTUI.result;
1498}
1499
1500unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
1501  return CXSaveTranslationUnit_None;
1502}
1503
1504int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
1505                              unsigned options) {
1506  if (!TU)
1507    return 1;
1508
1509  return static_cast<ASTUnit *>(TU)->Save(FileName);
1510}
1511
1512void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
1513  if (CTUnit) {
1514    // If the translation unit has been marked as unsafe to free, just discard
1515    // it.
1516    if (static_cast<ASTUnit *>(CTUnit)->isUnsafeToFree())
1517      return;
1518
1519    delete static_cast<ASTUnit *>(CTUnit);
1520  }
1521}
1522
1523unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
1524  return CXReparse_None;
1525}
1526
1527struct ReparseTranslationUnitInfo {
1528  CXTranslationUnit TU;
1529  unsigned num_unsaved_files;
1530  struct CXUnsavedFile *unsaved_files;
1531  unsigned options;
1532  int result;
1533};
1534void clang_reparseTranslationUnit_Impl(void *UserData) {
1535  ReparseTranslationUnitInfo *RTUI =
1536    static_cast<ReparseTranslationUnitInfo*>(UserData);
1537  CXTranslationUnit TU = RTUI->TU;
1538  unsigned num_unsaved_files = RTUI->num_unsaved_files;
1539  struct CXUnsavedFile *unsaved_files = RTUI->unsaved_files;
1540  unsigned options = RTUI->options;
1541  (void) options;
1542  RTUI->result = 1;
1543
1544  if (!TU)
1545    return;
1546
1547  llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
1548  for (unsigned I = 0; I != num_unsaved_files; ++I) {
1549    llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
1550    const llvm::MemoryBuffer *Buffer
1551      = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
1552    RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
1553                                           Buffer));
1554  }
1555
1556  if (!static_cast<ASTUnit *>(TU)->Reparse(RemappedFiles.data(),
1557                                           RemappedFiles.size()))
1558      RTUI->result = 0;
1559}
1560int clang_reparseTranslationUnit(CXTranslationUnit TU,
1561                                 unsigned num_unsaved_files,
1562                                 struct CXUnsavedFile *unsaved_files,
1563                                 unsigned options) {
1564  ReparseTranslationUnitInfo RTUI = { TU, num_unsaved_files, unsaved_files,
1565                                      options, 0 };
1566  llvm::CrashRecoveryContext CRC;
1567
1568  if (!CRC.RunSafely(clang_reparseTranslationUnit_Impl, &RTUI)) {
1569    // FIXME: Find a way to report the crash.
1570    static_cast<ASTUnit *>(TU)->setUnsafeToFree(true);
1571    return 1;
1572  }
1573
1574  return RTUI.result;
1575}
1576
1577
1578CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
1579  if (!CTUnit)
1580    return createCXString("");
1581
1582  ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit);
1583  return createCXString(CXXUnit->getOriginalSourceFileName(), true);
1584}
1585
1586CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
1587  CXCursor Result = { CXCursor_TranslationUnit, { 0, 0, TU } };
1588  return Result;
1589}
1590
1591} // end: extern "C"
1592
1593//===----------------------------------------------------------------------===//
1594// CXSourceLocation and CXSourceRange Operations.
1595//===----------------------------------------------------------------------===//
1596
1597extern "C" {
1598CXSourceLocation clang_getNullLocation() {
1599  CXSourceLocation Result = { { 0, 0 }, 0 };
1600  return Result;
1601}
1602
1603unsigned clang_equalLocations(CXSourceLocation loc1, CXSourceLocation loc2) {
1604  return (loc1.ptr_data[0] == loc2.ptr_data[0] &&
1605          loc1.ptr_data[1] == loc2.ptr_data[1] &&
1606          loc1.int_data == loc2.int_data);
1607}
1608
1609CXSourceLocation clang_getLocation(CXTranslationUnit tu,
1610                                   CXFile file,
1611                                   unsigned line,
1612                                   unsigned column) {
1613  if (!tu || !file)
1614    return clang_getNullLocation();
1615
1616  ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
1617  SourceLocation SLoc
1618    = CXXUnit->getSourceManager().getLocation(
1619                                        static_cast<const FileEntry *>(file),
1620                                              line, column);
1621
1622  return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
1623}
1624
1625CXSourceRange clang_getNullRange() {
1626  CXSourceRange Result = { { 0, 0 }, 0, 0 };
1627  return Result;
1628}
1629
1630CXSourceRange clang_getRange(CXSourceLocation begin, CXSourceLocation end) {
1631  if (begin.ptr_data[0] != end.ptr_data[0] ||
1632      begin.ptr_data[1] != end.ptr_data[1])
1633    return clang_getNullRange();
1634
1635  CXSourceRange Result = { { begin.ptr_data[0], begin.ptr_data[1] },
1636                           begin.int_data, end.int_data };
1637  return Result;
1638}
1639
1640void clang_getInstantiationLocation(CXSourceLocation location,
1641                                    CXFile *file,
1642                                    unsigned *line,
1643                                    unsigned *column,
1644                                    unsigned *offset) {
1645  SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
1646
1647  if (!location.ptr_data[0] || Loc.isInvalid()) {
1648    if (file)
1649      *file = 0;
1650    if (line)
1651      *line = 0;
1652    if (column)
1653      *column = 0;
1654    if (offset)
1655      *offset = 0;
1656    return;
1657  }
1658
1659  const SourceManager &SM =
1660    *static_cast<const SourceManager*>(location.ptr_data[0]);
1661  SourceLocation InstLoc = SM.getInstantiationLoc(Loc);
1662
1663  if (file)
1664    *file = (void *)SM.getFileEntryForID(SM.getFileID(InstLoc));
1665  if (line)
1666    *line = SM.getInstantiationLineNumber(InstLoc);
1667  if (column)
1668    *column = SM.getInstantiationColumnNumber(InstLoc);
1669  if (offset)
1670    *offset = SM.getDecomposedLoc(InstLoc).second;
1671}
1672
1673CXSourceLocation clang_getRangeStart(CXSourceRange range) {
1674  CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
1675                              range.begin_int_data };
1676  return Result;
1677}
1678
1679CXSourceLocation clang_getRangeEnd(CXSourceRange range) {
1680  CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
1681                              range.end_int_data };
1682  return Result;
1683}
1684
1685} // end: extern "C"
1686
1687//===----------------------------------------------------------------------===//
1688// CXFile Operations.
1689//===----------------------------------------------------------------------===//
1690
1691extern "C" {
1692CXString clang_getFileName(CXFile SFile) {
1693  if (!SFile)
1694    return createCXString(NULL);
1695
1696  FileEntry *FEnt = static_cast<FileEntry *>(SFile);
1697  return createCXString(FEnt->getName());
1698}
1699
1700time_t clang_getFileTime(CXFile SFile) {
1701  if (!SFile)
1702    return 0;
1703
1704  FileEntry *FEnt = static_cast<FileEntry *>(SFile);
1705  return FEnt->getModificationTime();
1706}
1707
1708CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
1709  if (!tu)
1710    return 0;
1711
1712  ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
1713
1714  FileManager &FMgr = CXXUnit->getFileManager();
1715  const FileEntry *File = FMgr.getFile(file_name, file_name+strlen(file_name));
1716  return const_cast<FileEntry *>(File);
1717}
1718
1719} // end: extern "C"
1720
1721//===----------------------------------------------------------------------===//
1722// CXCursor Operations.
1723//===----------------------------------------------------------------------===//
1724
1725static Decl *getDeclFromExpr(Stmt *E) {
1726  if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
1727    return RefExpr->getDecl();
1728  if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
1729    return ME->getMemberDecl();
1730  if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
1731    return RE->getDecl();
1732
1733  if (CallExpr *CE = dyn_cast<CallExpr>(E))
1734    return getDeclFromExpr(CE->getCallee());
1735  if (CastExpr *CE = dyn_cast<CastExpr>(E))
1736    return getDeclFromExpr(CE->getSubExpr());
1737  if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
1738    return OME->getMethodDecl();
1739
1740  return 0;
1741}
1742
1743static SourceLocation getLocationFromExpr(Expr *E) {
1744  if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
1745    return /*FIXME:*/Msg->getLeftLoc();
1746  if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
1747    return DRE->getLocation();
1748  if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
1749    return Member->getMemberLoc();
1750  if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
1751    return Ivar->getLocation();
1752  return E->getLocStart();
1753}
1754
1755extern "C" {
1756
1757unsigned clang_visitChildren(CXCursor parent,
1758                             CXCursorVisitor visitor,
1759                             CXClientData client_data) {
1760  ASTUnit *CXXUnit = getCursorASTUnit(parent);
1761
1762  CursorVisitor CursorVis(CXXUnit, visitor, client_data,
1763                          CXXUnit->getMaxPCHLevel());
1764  return CursorVis.VisitChildren(parent);
1765}
1766
1767static CXString getDeclSpelling(Decl *D) {
1768  NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
1769  if (!ND)
1770    return createCXString("");
1771
1772  if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
1773    return createCXString(OMD->getSelector().getAsString());
1774
1775  if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
1776    // No, this isn't the same as the code below. getIdentifier() is non-virtual
1777    // and returns different names. NamedDecl returns the class name and
1778    // ObjCCategoryImplDecl returns the category name.
1779    return createCXString(CIMP->getIdentifier()->getNameStart());
1780
1781  llvm::SmallString<1024> S;
1782  llvm::raw_svector_ostream os(S);
1783  ND->printName(os);
1784
1785  return createCXString(os.str());
1786}
1787
1788CXString clang_getCursorSpelling(CXCursor C) {
1789  if (clang_isTranslationUnit(C.kind))
1790    return clang_getTranslationUnitSpelling(C.data[2]);
1791
1792  if (clang_isReference(C.kind)) {
1793    switch (C.kind) {
1794    case CXCursor_ObjCSuperClassRef: {
1795      ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
1796      return createCXString(Super->getIdentifier()->getNameStart());
1797    }
1798    case CXCursor_ObjCClassRef: {
1799      ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
1800      return createCXString(Class->getIdentifier()->getNameStart());
1801    }
1802    case CXCursor_ObjCProtocolRef: {
1803      ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
1804      assert(OID && "getCursorSpelling(): Missing protocol decl");
1805      return createCXString(OID->getIdentifier()->getNameStart());
1806    }
1807    case CXCursor_TypeRef: {
1808      TypeDecl *Type = getCursorTypeRef(C).first;
1809      assert(Type && "Missing type decl");
1810
1811      return createCXString(getCursorContext(C).getTypeDeclType(Type).
1812                              getAsString());
1813    }
1814
1815    default:
1816      return createCXString("<not implemented>");
1817    }
1818  }
1819
1820  if (clang_isExpression(C.kind)) {
1821    Decl *D = getDeclFromExpr(getCursorExpr(C));
1822    if (D)
1823      return getDeclSpelling(D);
1824    return createCXString("");
1825  }
1826
1827  if (C.kind == CXCursor_MacroInstantiation)
1828    return createCXString(getCursorMacroInstantiation(C)->getName()
1829                                                           ->getNameStart());
1830
1831  if (C.kind == CXCursor_MacroDefinition)
1832    return createCXString(getCursorMacroDefinition(C)->getName()
1833                                                           ->getNameStart());
1834
1835  if (clang_isDeclaration(C.kind))
1836    return getDeclSpelling(getCursorDecl(C));
1837
1838  return createCXString("");
1839}
1840
1841CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
1842  switch (Kind) {
1843  case CXCursor_FunctionDecl:
1844      return createCXString("FunctionDecl");
1845  case CXCursor_TypedefDecl:
1846      return createCXString("TypedefDecl");
1847  case CXCursor_EnumDecl:
1848      return createCXString("EnumDecl");
1849  case CXCursor_EnumConstantDecl:
1850      return createCXString("EnumConstantDecl");
1851  case CXCursor_StructDecl:
1852      return createCXString("StructDecl");
1853  case CXCursor_UnionDecl:
1854      return createCXString("UnionDecl");
1855  case CXCursor_ClassDecl:
1856      return createCXString("ClassDecl");
1857  case CXCursor_FieldDecl:
1858      return createCXString("FieldDecl");
1859  case CXCursor_VarDecl:
1860      return createCXString("VarDecl");
1861  case CXCursor_ParmDecl:
1862      return createCXString("ParmDecl");
1863  case CXCursor_ObjCInterfaceDecl:
1864      return createCXString("ObjCInterfaceDecl");
1865  case CXCursor_ObjCCategoryDecl:
1866      return createCXString("ObjCCategoryDecl");
1867  case CXCursor_ObjCProtocolDecl:
1868      return createCXString("ObjCProtocolDecl");
1869  case CXCursor_ObjCPropertyDecl:
1870      return createCXString("ObjCPropertyDecl");
1871  case CXCursor_ObjCIvarDecl:
1872      return createCXString("ObjCIvarDecl");
1873  case CXCursor_ObjCInstanceMethodDecl:
1874      return createCXString("ObjCInstanceMethodDecl");
1875  case CXCursor_ObjCClassMethodDecl:
1876      return createCXString("ObjCClassMethodDecl");
1877  case CXCursor_ObjCImplementationDecl:
1878      return createCXString("ObjCImplementationDecl");
1879  case CXCursor_ObjCCategoryImplDecl:
1880      return createCXString("ObjCCategoryImplDecl");
1881  case CXCursor_CXXMethod:
1882      return createCXString("CXXMethod");
1883  case CXCursor_UnexposedDecl:
1884      return createCXString("UnexposedDecl");
1885  case CXCursor_ObjCSuperClassRef:
1886      return createCXString("ObjCSuperClassRef");
1887  case CXCursor_ObjCProtocolRef:
1888      return createCXString("ObjCProtocolRef");
1889  case CXCursor_ObjCClassRef:
1890      return createCXString("ObjCClassRef");
1891  case CXCursor_TypeRef:
1892      return createCXString("TypeRef");
1893  case CXCursor_UnexposedExpr:
1894      return createCXString("UnexposedExpr");
1895  case CXCursor_BlockExpr:
1896      return createCXString("BlockExpr");
1897  case CXCursor_DeclRefExpr:
1898      return createCXString("DeclRefExpr");
1899  case CXCursor_MemberRefExpr:
1900      return createCXString("MemberRefExpr");
1901  case CXCursor_CallExpr:
1902      return createCXString("CallExpr");
1903  case CXCursor_ObjCMessageExpr:
1904      return createCXString("ObjCMessageExpr");
1905  case CXCursor_UnexposedStmt:
1906      return createCXString("UnexposedStmt");
1907  case CXCursor_InvalidFile:
1908      return createCXString("InvalidFile");
1909  case CXCursor_InvalidCode:
1910    return createCXString("InvalidCode");
1911  case CXCursor_NoDeclFound:
1912      return createCXString("NoDeclFound");
1913  case CXCursor_NotImplemented:
1914      return createCXString("NotImplemented");
1915  case CXCursor_TranslationUnit:
1916      return createCXString("TranslationUnit");
1917  case CXCursor_UnexposedAttr:
1918      return createCXString("UnexposedAttr");
1919  case CXCursor_IBActionAttr:
1920      return createCXString("attribute(ibaction)");
1921  case CXCursor_IBOutletAttr:
1922     return createCXString("attribute(iboutlet)");
1923  case CXCursor_IBOutletCollectionAttr:
1924      return createCXString("attribute(iboutletcollection)");
1925  case CXCursor_PreprocessingDirective:
1926    return createCXString("preprocessing directive");
1927  case CXCursor_MacroDefinition:
1928    return createCXString("macro definition");
1929  case CXCursor_MacroInstantiation:
1930    return createCXString("macro instantiation");
1931  case CXCursor_Namespace:
1932    return createCXString("Namespace");
1933  case CXCursor_LinkageSpec:
1934    return createCXString("LinkageSpec");
1935  }
1936
1937  llvm_unreachable("Unhandled CXCursorKind");
1938  return createCXString(NULL);
1939}
1940
1941enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
1942                                         CXCursor parent,
1943                                         CXClientData client_data) {
1944  CXCursor *BestCursor = static_cast<CXCursor *>(client_data);
1945  *BestCursor = cursor;
1946  return CXChildVisit_Recurse;
1947}
1948
1949CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
1950  if (!TU)
1951    return clang_getNullCursor();
1952
1953  ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
1954  ASTUnit::ConcurrencyCheck Check(*CXXUnit);
1955
1956  // Translate the given source location to make it point at the beginning of
1957  // the token under the cursor.
1958  SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
1959
1960  // Guard against an invalid SourceLocation, or we may assert in one
1961  // of the following calls.
1962  if (SLoc.isInvalid())
1963    return clang_getNullCursor();
1964
1965  SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
1966                                    CXXUnit->getASTContext().getLangOptions());
1967
1968  CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
1969  if (SLoc.isValid()) {
1970    // FIXME: Would be great to have a "hint" cursor, then walk from that
1971    // hint cursor upward until we find a cursor whose source range encloses
1972    // the region of interest, rather than starting from the translation unit.
1973    CXCursor Parent = clang_getTranslationUnitCursor(CXXUnit);
1974    CursorVisitor CursorVis(CXXUnit, GetCursorVisitor, &Result,
1975                            Decl::MaxPCHLevel, SourceLocation(SLoc));
1976    CursorVis.VisitChildren(Parent);
1977  }
1978  return Result;
1979}
1980
1981CXCursor clang_getNullCursor(void) {
1982  return MakeCXCursorInvalid(CXCursor_InvalidFile);
1983}
1984
1985unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
1986  return X == Y;
1987}
1988
1989unsigned clang_isInvalid(enum CXCursorKind K) {
1990  return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
1991}
1992
1993unsigned clang_isDeclaration(enum CXCursorKind K) {
1994  return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
1995}
1996
1997unsigned clang_isReference(enum CXCursorKind K) {
1998  return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
1999}
2000
2001unsigned clang_isExpression(enum CXCursorKind K) {
2002  return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
2003}
2004
2005unsigned clang_isStatement(enum CXCursorKind K) {
2006  return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
2007}
2008
2009unsigned clang_isTranslationUnit(enum CXCursorKind K) {
2010  return K == CXCursor_TranslationUnit;
2011}
2012
2013unsigned clang_isPreprocessing(enum CXCursorKind K) {
2014  return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
2015}
2016
2017unsigned clang_isUnexposed(enum CXCursorKind K) {
2018  switch (K) {
2019    case CXCursor_UnexposedDecl:
2020    case CXCursor_UnexposedExpr:
2021    case CXCursor_UnexposedStmt:
2022    case CXCursor_UnexposedAttr:
2023      return true;
2024    default:
2025      return false;
2026  }
2027}
2028
2029CXCursorKind clang_getCursorKind(CXCursor C) {
2030  return C.kind;
2031}
2032
2033CXSourceLocation clang_getCursorLocation(CXCursor C) {
2034  if (clang_isReference(C.kind)) {
2035    switch (C.kind) {
2036    case CXCursor_ObjCSuperClassRef: {
2037      std::pair<ObjCInterfaceDecl *, SourceLocation> P
2038        = getCursorObjCSuperClassRef(C);
2039      return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
2040    }
2041
2042    case CXCursor_ObjCProtocolRef: {
2043      std::pair<ObjCProtocolDecl *, SourceLocation> P
2044        = getCursorObjCProtocolRef(C);
2045      return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
2046    }
2047
2048    case CXCursor_ObjCClassRef: {
2049      std::pair<ObjCInterfaceDecl *, SourceLocation> P
2050        = getCursorObjCClassRef(C);
2051      return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
2052    }
2053
2054    case CXCursor_TypeRef: {
2055      std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
2056      return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
2057    }
2058
2059    default:
2060      // FIXME: Need a way to enumerate all non-reference cases.
2061      llvm_unreachable("Missed a reference kind");
2062    }
2063  }
2064
2065  if (clang_isExpression(C.kind))
2066    return cxloc::translateSourceLocation(getCursorContext(C),
2067                                   getLocationFromExpr(getCursorExpr(C)));
2068
2069  if (C.kind == CXCursor_PreprocessingDirective) {
2070    SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
2071    return cxloc::translateSourceLocation(getCursorContext(C), L);
2072  }
2073
2074  if (C.kind == CXCursor_MacroInstantiation) {
2075    SourceLocation L
2076      = cxcursor::getCursorMacroInstantiation(C)->getSourceRange().getBegin();
2077    return cxloc::translateSourceLocation(getCursorContext(C), L);
2078  }
2079
2080  if (C.kind == CXCursor_MacroDefinition) {
2081    SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
2082    return cxloc::translateSourceLocation(getCursorContext(C), L);
2083  }
2084
2085  if (C.kind < CXCursor_FirstDecl || C.kind > CXCursor_LastDecl)
2086    return clang_getNullLocation();
2087
2088  Decl *D = getCursorDecl(C);
2089  SourceLocation Loc = D->getLocation();
2090  if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
2091    Loc = Class->getClassLoc();
2092  return cxloc::translateSourceLocation(getCursorContext(C), Loc);
2093}
2094
2095} // end extern "C"
2096
2097static SourceRange getRawCursorExtent(CXCursor C) {
2098  if (clang_isReference(C.kind)) {
2099    switch (C.kind) {
2100    case CXCursor_ObjCSuperClassRef:
2101      return  getCursorObjCSuperClassRef(C).second;
2102
2103    case CXCursor_ObjCProtocolRef:
2104      return getCursorObjCProtocolRef(C).second;
2105
2106    case CXCursor_ObjCClassRef:
2107      return getCursorObjCClassRef(C).second;
2108
2109    case CXCursor_TypeRef:
2110      return getCursorTypeRef(C).second;
2111
2112    default:
2113      // FIXME: Need a way to enumerate all non-reference cases.
2114      llvm_unreachable("Missed a reference kind");
2115    }
2116  }
2117
2118  if (clang_isExpression(C.kind))
2119    return getCursorExpr(C)->getSourceRange();
2120
2121  if (clang_isStatement(C.kind))
2122    return getCursorStmt(C)->getSourceRange();
2123
2124  if (C.kind == CXCursor_PreprocessingDirective)
2125    return cxcursor::getCursorPreprocessingDirective(C);
2126
2127  if (C.kind == CXCursor_MacroInstantiation)
2128    return cxcursor::getCursorMacroInstantiation(C)->getSourceRange();
2129
2130  if (C.kind == CXCursor_MacroDefinition)
2131    return cxcursor::getCursorMacroDefinition(C)->getSourceRange();
2132
2133  if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl)
2134    return getCursorDecl(C)->getSourceRange();
2135
2136  return SourceRange();
2137}
2138
2139extern "C" {
2140
2141CXSourceRange clang_getCursorExtent(CXCursor C) {
2142  SourceRange R = getRawCursorExtent(C);
2143  if (R.isInvalid())
2144    return clang_getNullRange();
2145
2146  return cxloc::translateSourceRange(getCursorContext(C), R);
2147}
2148
2149CXCursor clang_getCursorReferenced(CXCursor C) {
2150  if (clang_isInvalid(C.kind))
2151    return clang_getNullCursor();
2152
2153  ASTUnit *CXXUnit = getCursorASTUnit(C);
2154  if (clang_isDeclaration(C.kind))
2155    return C;
2156
2157  if (clang_isExpression(C.kind)) {
2158    Decl *D = getDeclFromExpr(getCursorExpr(C));
2159    if (D)
2160      return MakeCXCursor(D, CXXUnit);
2161    return clang_getNullCursor();
2162  }
2163
2164  if (C.kind == CXCursor_MacroInstantiation) {
2165    if (MacroDefinition *Def = getCursorMacroInstantiation(C)->getDefinition())
2166      return MakeMacroDefinitionCursor(Def, CXXUnit);
2167  }
2168
2169  if (!clang_isReference(C.kind))
2170    return clang_getNullCursor();
2171
2172  switch (C.kind) {
2173    case CXCursor_ObjCSuperClassRef:
2174      return MakeCXCursor(getCursorObjCSuperClassRef(C).first, CXXUnit);
2175
2176    case CXCursor_ObjCProtocolRef: {
2177      return MakeCXCursor(getCursorObjCProtocolRef(C).first, CXXUnit);
2178
2179    case CXCursor_ObjCClassRef:
2180      return MakeCXCursor(getCursorObjCClassRef(C).first, CXXUnit);
2181
2182    case CXCursor_TypeRef:
2183      return MakeCXCursor(getCursorTypeRef(C).first, CXXUnit);
2184
2185    default:
2186      // We would prefer to enumerate all non-reference cursor kinds here.
2187      llvm_unreachable("Unhandled reference cursor kind");
2188      break;
2189    }
2190  }
2191
2192  return clang_getNullCursor();
2193}
2194
2195CXCursor clang_getCursorDefinition(CXCursor C) {
2196  if (clang_isInvalid(C.kind))
2197    return clang_getNullCursor();
2198
2199  ASTUnit *CXXUnit = getCursorASTUnit(C);
2200
2201  bool WasReference = false;
2202  if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
2203    C = clang_getCursorReferenced(C);
2204    WasReference = true;
2205  }
2206
2207  if (C.kind == CXCursor_MacroInstantiation)
2208    return clang_getCursorReferenced(C);
2209
2210  if (!clang_isDeclaration(C.kind))
2211    return clang_getNullCursor();
2212
2213  Decl *D = getCursorDecl(C);
2214  if (!D)
2215    return clang_getNullCursor();
2216
2217  switch (D->getKind()) {
2218  // Declaration kinds that don't really separate the notions of
2219  // declaration and definition.
2220  case Decl::Namespace:
2221  case Decl::Typedef:
2222  case Decl::TemplateTypeParm:
2223  case Decl::EnumConstant:
2224  case Decl::Field:
2225  case Decl::ObjCIvar:
2226  case Decl::ObjCAtDefsField:
2227  case Decl::ImplicitParam:
2228  case Decl::ParmVar:
2229  case Decl::NonTypeTemplateParm:
2230  case Decl::TemplateTemplateParm:
2231  case Decl::ObjCCategoryImpl:
2232  case Decl::ObjCImplementation:
2233  case Decl::AccessSpec:
2234  case Decl::LinkageSpec:
2235  case Decl::ObjCPropertyImpl:
2236  case Decl::FileScopeAsm:
2237  case Decl::StaticAssert:
2238  case Decl::Block:
2239    return C;
2240
2241  // Declaration kinds that don't make any sense here, but are
2242  // nonetheless harmless.
2243  case Decl::TranslationUnit:
2244    break;
2245
2246  // Declaration kinds for which the definition is not resolvable.
2247  case Decl::UnresolvedUsingTypename:
2248  case Decl::UnresolvedUsingValue:
2249    break;
2250
2251  case Decl::UsingDirective:
2252    return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
2253                        CXXUnit);
2254
2255  case Decl::NamespaceAlias:
2256    return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), CXXUnit);
2257
2258  case Decl::Enum:
2259  case Decl::Record:
2260  case Decl::CXXRecord:
2261  case Decl::ClassTemplateSpecialization:
2262  case Decl::ClassTemplatePartialSpecialization:
2263    if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
2264      return MakeCXCursor(Def, CXXUnit);
2265    return clang_getNullCursor();
2266
2267  case Decl::Function:
2268  case Decl::CXXMethod:
2269  case Decl::CXXConstructor:
2270  case Decl::CXXDestructor:
2271  case Decl::CXXConversion: {
2272    const FunctionDecl *Def = 0;
2273    if (cast<FunctionDecl>(D)->getBody(Def))
2274      return MakeCXCursor(const_cast<FunctionDecl *>(Def), CXXUnit);
2275    return clang_getNullCursor();
2276  }
2277
2278  case Decl::Var: {
2279    // Ask the variable if it has a definition.
2280    if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
2281      return MakeCXCursor(Def, CXXUnit);
2282    return clang_getNullCursor();
2283  }
2284
2285  case Decl::FunctionTemplate: {
2286    const FunctionDecl *Def = 0;
2287    if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
2288      return MakeCXCursor(Def->getDescribedFunctionTemplate(), CXXUnit);
2289    return clang_getNullCursor();
2290  }
2291
2292  case Decl::ClassTemplate: {
2293    if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
2294                                                            ->getDefinition())
2295      return MakeCXCursor(
2296                         cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
2297                          CXXUnit);
2298    return clang_getNullCursor();
2299  }
2300
2301  case Decl::Using: {
2302    UsingDecl *Using = cast<UsingDecl>(D);
2303    CXCursor Def = clang_getNullCursor();
2304    for (UsingDecl::shadow_iterator S = Using->shadow_begin(),
2305                                 SEnd = Using->shadow_end();
2306         S != SEnd; ++S) {
2307      if (Def != clang_getNullCursor()) {
2308        // FIXME: We have no way to return multiple results.
2309        return clang_getNullCursor();
2310      }
2311
2312      Def = clang_getCursorDefinition(MakeCXCursor((*S)->getTargetDecl(),
2313                                                   CXXUnit));
2314    }
2315
2316    return Def;
2317  }
2318
2319  case Decl::UsingShadow:
2320    return clang_getCursorDefinition(
2321                       MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
2322                                    CXXUnit));
2323
2324  case Decl::ObjCMethod: {
2325    ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
2326    if (Method->isThisDeclarationADefinition())
2327      return C;
2328
2329    // Dig out the method definition in the associated
2330    // @implementation, if we have it.
2331    // FIXME: The ASTs should make finding the definition easier.
2332    if (ObjCInterfaceDecl *Class
2333                       = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
2334      if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
2335        if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
2336                                                  Method->isInstanceMethod()))
2337          if (Def->isThisDeclarationADefinition())
2338            return MakeCXCursor(Def, CXXUnit);
2339
2340    return clang_getNullCursor();
2341  }
2342
2343  case Decl::ObjCCategory:
2344    if (ObjCCategoryImplDecl *Impl
2345                               = cast<ObjCCategoryDecl>(D)->getImplementation())
2346      return MakeCXCursor(Impl, CXXUnit);
2347    return clang_getNullCursor();
2348
2349  case Decl::ObjCProtocol:
2350    if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
2351      return C;
2352    return clang_getNullCursor();
2353
2354  case Decl::ObjCInterface:
2355    // There are two notions of a "definition" for an Objective-C
2356    // class: the interface and its implementation. When we resolved a
2357    // reference to an Objective-C class, produce the @interface as
2358    // the definition; when we were provided with the interface,
2359    // produce the @implementation as the definition.
2360    if (WasReference) {
2361      if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
2362        return C;
2363    } else if (ObjCImplementationDecl *Impl
2364                              = cast<ObjCInterfaceDecl>(D)->getImplementation())
2365      return MakeCXCursor(Impl, CXXUnit);
2366    return clang_getNullCursor();
2367
2368  case Decl::ObjCProperty:
2369    // FIXME: We don't really know where to find the
2370    // ObjCPropertyImplDecls that implement this property.
2371    return clang_getNullCursor();
2372
2373  case Decl::ObjCCompatibleAlias:
2374    if (ObjCInterfaceDecl *Class
2375          = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
2376      if (!Class->isForwardDecl())
2377        return MakeCXCursor(Class, CXXUnit);
2378
2379    return clang_getNullCursor();
2380
2381  case Decl::ObjCForwardProtocol: {
2382    ObjCForwardProtocolDecl *Forward = cast<ObjCForwardProtocolDecl>(D);
2383    if (Forward->protocol_size() == 1)
2384      return clang_getCursorDefinition(
2385                                     MakeCXCursor(*Forward->protocol_begin(),
2386                                                  CXXUnit));
2387
2388    // FIXME: Cannot return multiple definitions.
2389    return clang_getNullCursor();
2390  }
2391
2392  case Decl::ObjCClass: {
2393    ObjCClassDecl *Class = cast<ObjCClassDecl>(D);
2394    if (Class->size() == 1) {
2395      ObjCInterfaceDecl *IFace = Class->begin()->getInterface();
2396      if (!IFace->isForwardDecl())
2397        return MakeCXCursor(IFace, CXXUnit);
2398      return clang_getNullCursor();
2399    }
2400
2401    // FIXME: Cannot return multiple definitions.
2402    return clang_getNullCursor();
2403  }
2404
2405  case Decl::Friend:
2406    if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
2407      return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
2408    return clang_getNullCursor();
2409
2410  case Decl::FriendTemplate:
2411    if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
2412      return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
2413    return clang_getNullCursor();
2414  }
2415
2416  return clang_getNullCursor();
2417}
2418
2419unsigned clang_isCursorDefinition(CXCursor C) {
2420  if (!clang_isDeclaration(C.kind))
2421    return 0;
2422
2423  return clang_getCursorDefinition(C) == C;
2424}
2425
2426void clang_getDefinitionSpellingAndExtent(CXCursor C,
2427                                          const char **startBuf,
2428                                          const char **endBuf,
2429                                          unsigned *startLine,
2430                                          unsigned *startColumn,
2431                                          unsigned *endLine,
2432                                          unsigned *endColumn) {
2433  assert(getCursorDecl(C) && "CXCursor has null decl");
2434  NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
2435  FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
2436  CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
2437
2438  SourceManager &SM = FD->getASTContext().getSourceManager();
2439  *startBuf = SM.getCharacterData(Body->getLBracLoc());
2440  *endBuf = SM.getCharacterData(Body->getRBracLoc());
2441  *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
2442  *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
2443  *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
2444  *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
2445}
2446
2447void clang_enableStackTraces(void) {
2448  llvm::sys::PrintStackTraceOnErrorSignal();
2449}
2450
2451} // end: extern "C"
2452
2453//===----------------------------------------------------------------------===//
2454// Token-based Operations.
2455//===----------------------------------------------------------------------===//
2456
2457/* CXToken layout:
2458 *   int_data[0]: a CXTokenKind
2459 *   int_data[1]: starting token location
2460 *   int_data[2]: token length
2461 *   int_data[3]: reserved
2462 *   ptr_data: for identifiers and keywords, an IdentifierInfo*.
2463 *   otherwise unused.
2464 */
2465extern "C" {
2466
2467CXTokenKind clang_getTokenKind(CXToken CXTok) {
2468  return static_cast<CXTokenKind>(CXTok.int_data[0]);
2469}
2470
2471CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
2472  switch (clang_getTokenKind(CXTok)) {
2473  case CXToken_Identifier:
2474  case CXToken_Keyword:
2475    // We know we have an IdentifierInfo*, so use that.
2476    return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
2477                            ->getNameStart());
2478
2479  case CXToken_Literal: {
2480    // We have stashed the starting pointer in the ptr_data field. Use it.
2481    const char *Text = static_cast<const char *>(CXTok.ptr_data);
2482    return createCXString(llvm::StringRef(Text, CXTok.int_data[2]));
2483  }
2484
2485  case CXToken_Punctuation:
2486  case CXToken_Comment:
2487    break;
2488  }
2489
2490  // We have to find the starting buffer pointer the hard way, by
2491  // deconstructing the source location.
2492  ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2493  if (!CXXUnit)
2494    return createCXString("");
2495
2496  SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
2497  std::pair<FileID, unsigned> LocInfo
2498    = CXXUnit->getSourceManager().getDecomposedLoc(Loc);
2499  bool Invalid = false;
2500  llvm::StringRef Buffer
2501    = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
2502  if (Invalid)
2503    return createCXString("");
2504
2505  return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
2506}
2507
2508CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
2509  ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2510  if (!CXXUnit)
2511    return clang_getNullLocation();
2512
2513  return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
2514                        SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
2515}
2516
2517CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
2518  ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2519  if (!CXXUnit)
2520    return clang_getNullRange();
2521
2522  return cxloc::translateSourceRange(CXXUnit->getASTContext(),
2523                        SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
2524}
2525
2526void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
2527                    CXToken **Tokens, unsigned *NumTokens) {
2528  if (Tokens)
2529    *Tokens = 0;
2530  if (NumTokens)
2531    *NumTokens = 0;
2532
2533  ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2534  if (!CXXUnit || !Tokens || !NumTokens)
2535    return;
2536
2537  ASTUnit::ConcurrencyCheck Check(*CXXUnit);
2538
2539  SourceRange R = cxloc::translateCXSourceRange(Range);
2540  if (R.isInvalid())
2541    return;
2542
2543  SourceManager &SourceMgr = CXXUnit->getSourceManager();
2544  std::pair<FileID, unsigned> BeginLocInfo
2545    = SourceMgr.getDecomposedLoc(R.getBegin());
2546  std::pair<FileID, unsigned> EndLocInfo
2547    = SourceMgr.getDecomposedLoc(R.getEnd());
2548
2549  // Cannot tokenize across files.
2550  if (BeginLocInfo.first != EndLocInfo.first)
2551    return;
2552
2553  // Create a lexer
2554  bool Invalid = false;
2555  llvm::StringRef Buffer
2556    = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
2557  if (Invalid)
2558    return;
2559
2560  Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
2561            CXXUnit->getASTContext().getLangOptions(),
2562            Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
2563  Lex.SetCommentRetentionState(true);
2564
2565  // Lex tokens until we hit the end of the range.
2566  const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
2567  llvm::SmallVector<CXToken, 32> CXTokens;
2568  Token Tok;
2569  do {
2570    // Lex the next token
2571    Lex.LexFromRawLexer(Tok);
2572    if (Tok.is(tok::eof))
2573      break;
2574
2575    // Initialize the CXToken.
2576    CXToken CXTok;
2577
2578    //   - Common fields
2579    CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
2580    CXTok.int_data[2] = Tok.getLength();
2581    CXTok.int_data[3] = 0;
2582
2583    //   - Kind-specific fields
2584    if (Tok.isLiteral()) {
2585      CXTok.int_data[0] = CXToken_Literal;
2586      CXTok.ptr_data = (void *)Tok.getLiteralData();
2587    } else if (Tok.is(tok::identifier)) {
2588      // Lookup the identifier to determine whether we have a keyword.
2589      std::pair<FileID, unsigned> LocInfo
2590        = SourceMgr.getDecomposedLoc(Tok.getLocation());
2591      bool Invalid = false;
2592      llvm::StringRef Buf
2593        = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
2594      if (Invalid)
2595        return;
2596
2597      const char *StartPos = Buf.data() + LocInfo.second;
2598      IdentifierInfo *II
2599        = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok, StartPos);
2600
2601      if (II->getObjCKeywordID() != tok::objc_not_keyword) {
2602        CXTok.int_data[0] = CXToken_Keyword;
2603      }
2604      else {
2605        CXTok.int_data[0] = II->getTokenID() == tok::identifier?
2606                                CXToken_Identifier
2607                              : CXToken_Keyword;
2608      }
2609      CXTok.ptr_data = II;
2610    } else if (Tok.is(tok::comment)) {
2611      CXTok.int_data[0] = CXToken_Comment;
2612      CXTok.ptr_data = 0;
2613    } else {
2614      CXTok.int_data[0] = CXToken_Punctuation;
2615      CXTok.ptr_data = 0;
2616    }
2617    CXTokens.push_back(CXTok);
2618  } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
2619
2620  if (CXTokens.empty())
2621    return;
2622
2623  *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
2624  memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
2625  *NumTokens = CXTokens.size();
2626}
2627
2628void clang_disposeTokens(CXTranslationUnit TU,
2629                         CXToken *Tokens, unsigned NumTokens) {
2630  free(Tokens);
2631}
2632
2633} // end: extern "C"
2634
2635//===----------------------------------------------------------------------===//
2636// Token annotation APIs.
2637//===----------------------------------------------------------------------===//
2638
2639typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
2640static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
2641                                                     CXCursor parent,
2642                                                     CXClientData client_data);
2643namespace {
2644class AnnotateTokensWorker {
2645  AnnotateTokensData &Annotated;
2646  CXToken *Tokens;
2647  CXCursor *Cursors;
2648  unsigned NumTokens;
2649  unsigned TokIdx;
2650  CursorVisitor AnnotateVis;
2651  SourceManager &SrcMgr;
2652
2653  bool MoreTokens() const { return TokIdx < NumTokens; }
2654  unsigned NextToken() const { return TokIdx; }
2655  void AdvanceToken() { ++TokIdx; }
2656  SourceLocation GetTokenLoc(unsigned tokI) {
2657    return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
2658  }
2659
2660public:
2661  AnnotateTokensWorker(AnnotateTokensData &annotated,
2662                       CXToken *tokens, CXCursor *cursors, unsigned numTokens,
2663                       ASTUnit *CXXUnit, SourceRange RegionOfInterest)
2664    : Annotated(annotated), Tokens(tokens), Cursors(cursors),
2665      NumTokens(numTokens), TokIdx(0),
2666      AnnotateVis(CXXUnit, AnnotateTokensVisitor, this,
2667                  Decl::MaxPCHLevel, RegionOfInterest),
2668      SrcMgr(CXXUnit->getSourceManager()) {}
2669
2670  void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
2671  enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
2672  void AnnotateTokens(CXCursor parent);
2673};
2674}
2675
2676void AnnotateTokensWorker::AnnotateTokens(CXCursor parent) {
2677  // Walk the AST within the region of interest, annotating tokens
2678  // along the way.
2679  VisitChildren(parent);
2680
2681  for (unsigned I = 0 ; I < TokIdx ; ++I) {
2682    AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
2683    if (Pos != Annotated.end())
2684      Cursors[I] = Pos->second;
2685  }
2686
2687  // Finish up annotating any tokens left.
2688  if (!MoreTokens())
2689    return;
2690
2691  const CXCursor &C = clang_getNullCursor();
2692  for (unsigned I = TokIdx ; I < NumTokens ; ++I) {
2693    AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
2694    Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second;
2695  }
2696}
2697
2698enum CXChildVisitResult
2699AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
2700  CXSourceLocation Loc = clang_getCursorLocation(cursor);
2701  // We can always annotate a preprocessing directive/macro instantiation.
2702  if (clang_isPreprocessing(cursor.kind)) {
2703    Annotated[Loc.int_data] = cursor;
2704    return CXChildVisit_Recurse;
2705  }
2706
2707  SourceRange cursorRange = getRawCursorExtent(cursor);
2708
2709  if (cursorRange.isInvalid())
2710    return CXChildVisit_Continue;
2711
2712  SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data);
2713
2714  // Adjust the annotated range based specific declarations.
2715  const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
2716  if (cursorK >= CXCursor_FirstDecl && cursorK <= CXCursor_LastDecl) {
2717    Decl *D = cxcursor::getCursorDecl(cursor);
2718    // Don't visit synthesized ObjC methods, since they have no syntatic
2719    // representation in the source.
2720    if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
2721      if (MD->isSynthesized())
2722        return CXChildVisit_Continue;
2723    }
2724    if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
2725      if (TypeSourceInfo *TI = DD->getTypeSourceInfo()) {
2726        TypeLoc TL = TI->getTypeLoc();
2727        SourceLocation TLoc = TL.getSourceRange().getBegin();
2728        if (TLoc.isValid() &&
2729            SrcMgr.isBeforeInTranslationUnit(TLoc, L))
2730          cursorRange.setBegin(TLoc);
2731      }
2732    }
2733  }
2734
2735  // If the location of the cursor occurs within a macro instantiation, record
2736  // the spelling location of the cursor in our annotation map.  We can then
2737  // paper over the token labelings during a post-processing step to try and
2738  // get cursor mappings for tokens that are the *arguments* of a macro
2739  // instantiation.
2740  if (L.isMacroID()) {
2741    unsigned rawEncoding = SrcMgr.getSpellingLoc(L).getRawEncoding();
2742    // Only invalidate the old annotation if it isn't part of a preprocessing
2743    // directive.  Here we assume that the default construction of CXCursor
2744    // results in CXCursor.kind being an initialized value (i.e., 0).  If
2745    // this isn't the case, we can fix by doing lookup + insertion.
2746
2747    CXCursor &oldC = Annotated[rawEncoding];
2748    if (!clang_isPreprocessing(oldC.kind))
2749      oldC = cursor;
2750  }
2751
2752  const enum CXCursorKind K = clang_getCursorKind(parent);
2753  const CXCursor updateC =
2754    (clang_isInvalid(K) || K == CXCursor_TranslationUnit ||
2755     L.isMacroID())
2756    ? clang_getNullCursor() : parent;
2757
2758  while (MoreTokens()) {
2759    const unsigned I = NextToken();
2760    SourceLocation TokLoc = GetTokenLoc(I);
2761    switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
2762      case RangeBefore:
2763        Cursors[I] = updateC;
2764        AdvanceToken();
2765        continue;
2766      case RangeAfter:
2767      case RangeOverlap:
2768        break;
2769    }
2770    break;
2771  }
2772
2773  // Visit children to get their cursor information.
2774  const unsigned BeforeChildren = NextToken();
2775  VisitChildren(cursor);
2776  const unsigned AfterChildren = NextToken();
2777
2778  // Adjust 'Last' to the last token within the extent of the cursor.
2779  while (MoreTokens()) {
2780    const unsigned I = NextToken();
2781    SourceLocation TokLoc = GetTokenLoc(I);
2782    switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
2783      case RangeBefore:
2784        assert(0 && "Infeasible");
2785      case RangeAfter:
2786        break;
2787      case RangeOverlap:
2788        Cursors[I] = updateC;
2789        AdvanceToken();
2790        continue;
2791    }
2792    break;
2793  }
2794  const unsigned Last = NextToken();
2795
2796  // Scan the tokens that are at the beginning of the cursor, but are not
2797  // capture by the child cursors.
2798
2799  // For AST elements within macros, rely on a post-annotate pass to
2800  // to correctly annotate the tokens with cursors.  Otherwise we can
2801  // get confusing results of having tokens that map to cursors that really
2802  // are expanded by an instantiation.
2803  if (L.isMacroID())
2804    cursor = clang_getNullCursor();
2805
2806  for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
2807    if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
2808      break;
2809    Cursors[I] = cursor;
2810  }
2811  // Scan the tokens that are at the end of the cursor, but are not captured
2812  // but the child cursors.
2813  for (unsigned I = AfterChildren; I != Last; ++I)
2814    Cursors[I] = cursor;
2815
2816  TokIdx = Last;
2817  return CXChildVisit_Continue;
2818}
2819
2820static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
2821                                                     CXCursor parent,
2822                                                     CXClientData client_data) {
2823  return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
2824}
2825
2826extern "C" {
2827
2828void clang_annotateTokens(CXTranslationUnit TU,
2829                          CXToken *Tokens, unsigned NumTokens,
2830                          CXCursor *Cursors) {
2831
2832  if (NumTokens == 0 || !Tokens || !Cursors)
2833    return;
2834
2835  ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2836  if (!CXXUnit) {
2837    // Any token we don't specifically annotate will have a NULL cursor.
2838    const CXCursor &C = clang_getNullCursor();
2839    for (unsigned I = 0; I != NumTokens; ++I)
2840      Cursors[I] = C;
2841    return;
2842  }
2843
2844  ASTUnit::ConcurrencyCheck Check(*CXXUnit);
2845
2846  // Determine the region of interest, which contains all of the tokens.
2847  SourceRange RegionOfInterest;
2848  RegionOfInterest.setBegin(cxloc::translateSourceLocation(
2849                                        clang_getTokenLocation(TU, Tokens[0])));
2850  RegionOfInterest.setEnd(cxloc::translateSourceLocation(
2851                                clang_getTokenLocation(TU,
2852                                                       Tokens[NumTokens - 1])));
2853
2854  // A mapping from the source locations found when re-lexing or traversing the
2855  // region of interest to the corresponding cursors.
2856  AnnotateTokensData Annotated;
2857
2858  // Relex the tokens within the source range to look for preprocessing
2859  // directives.
2860  SourceManager &SourceMgr = CXXUnit->getSourceManager();
2861  std::pair<FileID, unsigned> BeginLocInfo
2862    = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
2863  std::pair<FileID, unsigned> EndLocInfo
2864    = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
2865
2866  llvm::StringRef Buffer;
2867  bool Invalid = false;
2868  if (BeginLocInfo.first == EndLocInfo.first &&
2869      ((Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid)),true) &&
2870      !Invalid) {
2871    Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
2872              CXXUnit->getASTContext().getLangOptions(),
2873              Buffer.begin(), Buffer.data() + BeginLocInfo.second,
2874              Buffer.end());
2875    Lex.SetCommentRetentionState(true);
2876
2877    // Lex tokens in raw mode until we hit the end of the range, to avoid
2878    // entering #includes or expanding macros.
2879    while (true) {
2880      Token Tok;
2881      Lex.LexFromRawLexer(Tok);
2882
2883    reprocess:
2884      if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
2885        // We have found a preprocessing directive. Gobble it up so that we
2886        // don't see it while preprocessing these tokens later, but keep track of
2887        // all of the token locations inside this preprocessing directive so that
2888        // we can annotate them appropriately.
2889        //
2890        // FIXME: Some simple tests here could identify macro definitions and
2891        // #undefs, to provide specific cursor kinds for those.
2892        std::vector<SourceLocation> Locations;
2893        do {
2894          Locations.push_back(Tok.getLocation());
2895          Lex.LexFromRawLexer(Tok);
2896        } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
2897
2898        using namespace cxcursor;
2899        CXCursor Cursor
2900          = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
2901                                                         Locations.back()),
2902                                           CXXUnit);
2903        for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
2904          Annotated[Locations[I].getRawEncoding()] = Cursor;
2905        }
2906
2907        if (Tok.isAtStartOfLine())
2908          goto reprocess;
2909
2910        continue;
2911      }
2912
2913      if (Tok.is(tok::eof))
2914        break;
2915    }
2916  }
2917
2918  // Annotate all of the source locations in the region of interest that map to
2919  // a specific cursor.
2920  AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens,
2921                         CXXUnit, RegionOfInterest);
2922  W.AnnotateTokens(clang_getTranslationUnitCursor(CXXUnit));
2923}
2924} // end: extern "C"
2925
2926//===----------------------------------------------------------------------===//
2927// Operations for querying linkage of a cursor.
2928//===----------------------------------------------------------------------===//
2929
2930extern "C" {
2931CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
2932  if (!clang_isDeclaration(cursor.kind))
2933    return CXLinkage_Invalid;
2934
2935  Decl *D = cxcursor::getCursorDecl(cursor);
2936  if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
2937    switch (ND->getLinkage()) {
2938      case NoLinkage: return CXLinkage_NoLinkage;
2939      case InternalLinkage: return CXLinkage_Internal;
2940      case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
2941      case ExternalLinkage: return CXLinkage_External;
2942    };
2943
2944  return CXLinkage_Invalid;
2945}
2946} // end: extern "C"
2947
2948//===----------------------------------------------------------------------===//
2949// Operations for querying language of a cursor.
2950//===----------------------------------------------------------------------===//
2951
2952static CXLanguageKind getDeclLanguage(const Decl *D) {
2953  switch (D->getKind()) {
2954    default:
2955      break;
2956    case Decl::ImplicitParam:
2957    case Decl::ObjCAtDefsField:
2958    case Decl::ObjCCategory:
2959    case Decl::ObjCCategoryImpl:
2960    case Decl::ObjCClass:
2961    case Decl::ObjCCompatibleAlias:
2962    case Decl::ObjCForwardProtocol:
2963    case Decl::ObjCImplementation:
2964    case Decl::ObjCInterface:
2965    case Decl::ObjCIvar:
2966    case Decl::ObjCMethod:
2967    case Decl::ObjCProperty:
2968    case Decl::ObjCPropertyImpl:
2969    case Decl::ObjCProtocol:
2970      return CXLanguage_ObjC;
2971    case Decl::CXXConstructor:
2972    case Decl::CXXConversion:
2973    case Decl::CXXDestructor:
2974    case Decl::CXXMethod:
2975    case Decl::CXXRecord:
2976    case Decl::ClassTemplate:
2977    case Decl::ClassTemplatePartialSpecialization:
2978    case Decl::ClassTemplateSpecialization:
2979    case Decl::Friend:
2980    case Decl::FriendTemplate:
2981    case Decl::FunctionTemplate:
2982    case Decl::LinkageSpec:
2983    case Decl::Namespace:
2984    case Decl::NamespaceAlias:
2985    case Decl::NonTypeTemplateParm:
2986    case Decl::StaticAssert:
2987    case Decl::TemplateTemplateParm:
2988    case Decl::TemplateTypeParm:
2989    case Decl::UnresolvedUsingTypename:
2990    case Decl::UnresolvedUsingValue:
2991    case Decl::Using:
2992    case Decl::UsingDirective:
2993    case Decl::UsingShadow:
2994      return CXLanguage_CPlusPlus;
2995  }
2996
2997  return CXLanguage_C;
2998}
2999
3000extern "C" {
3001CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
3002  if (clang_isDeclaration(cursor.kind))
3003    return getDeclLanguage(cxcursor::getCursorDecl(cursor));
3004
3005  return CXLanguage_Invalid;
3006}
3007} // end: extern "C"
3008
3009
3010//===----------------------------------------------------------------------===//
3011// C++ AST instrospection.
3012//===----------------------------------------------------------------------===//
3013
3014extern "C" {
3015unsigned clang_CXXMethod_isStatic(CXCursor C) {
3016  if (!clang_isDeclaration(C.kind))
3017    return 0;
3018  CXXMethodDecl *D = dyn_cast<CXXMethodDecl>(cxcursor::getCursorDecl(C));
3019  return (D && D->isStatic()) ? 1 : 0;
3020}
3021
3022} // end: extern "C"
3023
3024//===----------------------------------------------------------------------===//
3025// CXString Operations.
3026//===----------------------------------------------------------------------===//
3027
3028extern "C" {
3029const char *clang_getCString(CXString string) {
3030  return string.Spelling;
3031}
3032
3033void clang_disposeString(CXString string) {
3034  if (string.MustFreeString && string.Spelling)
3035    free((void*)string.Spelling);
3036}
3037
3038} // end: extern "C"
3039
3040namespace clang { namespace cxstring {
3041CXString createCXString(const char *String, bool DupString){
3042  CXString Str;
3043  if (DupString) {
3044    Str.Spelling = strdup(String);
3045    Str.MustFreeString = 1;
3046  } else {
3047    Str.Spelling = String;
3048    Str.MustFreeString = 0;
3049  }
3050  return Str;
3051}
3052
3053CXString createCXString(llvm::StringRef String, bool DupString) {
3054  CXString Result;
3055  if (DupString || (!String.empty() && String.data()[String.size()] != 0)) {
3056    char *Spelling = (char *)malloc(String.size() + 1);
3057    memmove(Spelling, String.data(), String.size());
3058    Spelling[String.size()] = 0;
3059    Result.Spelling = Spelling;
3060    Result.MustFreeString = 1;
3061  } else {
3062    Result.Spelling = String.data();
3063    Result.MustFreeString = 0;
3064  }
3065  return Result;
3066}
3067}}
3068
3069//===----------------------------------------------------------------------===//
3070// Misc. utility functions.
3071//===----------------------------------------------------------------------===//
3072
3073extern "C" {
3074
3075CXString clang_getClangVersion() {
3076  return createCXString(getClangFullVersion());
3077}
3078
3079} // end: extern "C"
3080