CIndex.cpp revision 58ddb60f409125eda5436c4a1f070f7fa4744295
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 (AttrVec::const_iterator i = D->attr_begin(), e = D->attr_end();
1148       i != e; ++i)
1149    if (Visit(MakeCXCursor(*i, D, TU)))
1150        return true;
1151
1152  return false;
1153}
1154
1155extern "C" {
1156CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
1157                          int displayDiagnostics) {
1158  // We use crash recovery to make some of our APIs more reliable, implicitly
1159  // enable it.
1160  llvm::CrashRecoveryContext::Enable();
1161
1162  CIndexer *CIdxr = new CIndexer();
1163  if (excludeDeclarationsFromPCH)
1164    CIdxr->setOnlyLocalDecls();
1165  if (displayDiagnostics)
1166    CIdxr->setDisplayDiagnostics();
1167  return CIdxr;
1168}
1169
1170void clang_disposeIndex(CXIndex CIdx) {
1171  if (CIdx)
1172    delete static_cast<CIndexer *>(CIdx);
1173  if (getenv("LIBCLANG_TIMING"))
1174    llvm::TimerGroup::printAll(llvm::errs());
1175}
1176
1177void clang_setUseExternalASTGeneration(CXIndex CIdx, int value) {
1178  if (CIdx) {
1179    CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
1180    CXXIdx->setUseExternalASTGeneration(value);
1181  }
1182}
1183
1184CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
1185                                              const char *ast_filename) {
1186  if (!CIdx)
1187    return 0;
1188
1189  CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
1190
1191  llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
1192  return ASTUnit::LoadFromASTFile(ast_filename, Diags,
1193                                  CXXIdx->getOnlyLocalDecls(),
1194                                  0, 0, true);
1195}
1196
1197unsigned clang_defaultEditingTranslationUnitOptions() {
1198  return CXTranslationUnit_PrecompiledPreamble;
1199}
1200
1201CXTranslationUnit
1202clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
1203                                          const char *source_filename,
1204                                          int num_command_line_args,
1205                                          const char **command_line_args,
1206                                          unsigned num_unsaved_files,
1207                                          struct CXUnsavedFile *unsaved_files) {
1208  return clang_parseTranslationUnit(CIdx, source_filename,
1209                                    command_line_args, num_command_line_args,
1210                                    unsaved_files, num_unsaved_files,
1211                                 CXTranslationUnit_DetailedPreprocessingRecord);
1212}
1213
1214struct ParseTranslationUnitInfo {
1215  CXIndex CIdx;
1216  const char *source_filename;
1217  const char **command_line_args;
1218  int num_command_line_args;
1219  struct CXUnsavedFile *unsaved_files;
1220  unsigned num_unsaved_files;
1221  unsigned options;
1222  CXTranslationUnit result;
1223};
1224static void clang_parseTranslationUnit_Impl(void *UserData) {
1225  ParseTranslationUnitInfo *PTUI =
1226    static_cast<ParseTranslationUnitInfo*>(UserData);
1227  CXIndex CIdx = PTUI->CIdx;
1228  const char *source_filename = PTUI->source_filename;
1229  const char **command_line_args = PTUI->command_line_args;
1230  int num_command_line_args = PTUI->num_command_line_args;
1231  struct CXUnsavedFile *unsaved_files = PTUI->unsaved_files;
1232  unsigned num_unsaved_files = PTUI->num_unsaved_files;
1233  unsigned options = PTUI->options;
1234  PTUI->result = 0;
1235
1236  if (!CIdx)
1237    return;
1238
1239  CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
1240
1241  bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
1242  bool CompleteTranslationUnit
1243    = ((options & CXTranslationUnit_Incomplete) == 0);
1244  bool CacheCodeCompetionResults
1245    = options & CXTranslationUnit_CacheCompletionResults;
1246
1247  // Configure the diagnostics.
1248  DiagnosticOptions DiagOpts;
1249  llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
1250  Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
1251
1252  llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
1253  for (unsigned I = 0; I != num_unsaved_files; ++I) {
1254    llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
1255    const llvm::MemoryBuffer *Buffer
1256      = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
1257    RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
1258                                           Buffer));
1259  }
1260
1261  if (!CXXIdx->getUseExternalASTGeneration()) {
1262    llvm::SmallVector<const char *, 16> Args;
1263
1264    // The 'source_filename' argument is optional.  If the caller does not
1265    // specify it then it is assumed that the source file is specified
1266    // in the actual argument list.
1267    if (source_filename)
1268      Args.push_back(source_filename);
1269
1270    // Since the Clang C library is primarily used by batch tools dealing with
1271    // (often very broken) source code, where spell-checking can have a
1272    // significant negative impact on performance (particularly when
1273    // precompiled headers are involved), we disable it by default.
1274    // Note that we place this argument early in the list, so that it can be
1275    // overridden by the caller with "-fspell-checking".
1276    Args.push_back("-fno-spell-checking");
1277
1278    Args.insert(Args.end(), command_line_args,
1279                command_line_args + num_command_line_args);
1280
1281    // Do we need the detailed preprocessing record?
1282    if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
1283      Args.push_back("-Xclang");
1284      Args.push_back("-detailed-preprocessing-record");
1285    }
1286
1287    unsigned NumErrors = Diags->getNumErrors();
1288
1289#ifdef USE_CRASHTRACER
1290    ArgsCrashTracerInfo ACTI(Args);
1291#endif
1292
1293    llvm::OwningPtr<ASTUnit> Unit(
1294      ASTUnit::LoadFromCommandLine(Args.data(), Args.data() + Args.size(),
1295                                   Diags,
1296                                   CXXIdx->getClangResourcesPath(),
1297                                   CXXIdx->getOnlyLocalDecls(),
1298                                   RemappedFiles.data(),
1299                                   RemappedFiles.size(),
1300                                   /*CaptureDiagnostics=*/true,
1301                                   PrecompilePreamble,
1302                                   CompleteTranslationUnit,
1303                                   CacheCodeCompetionResults));
1304
1305    if (NumErrors != Diags->getNumErrors()) {
1306      // Make sure to check that 'Unit' is non-NULL.
1307      if (CXXIdx->getDisplayDiagnostics() && Unit.get()) {
1308        for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
1309                                        DEnd = Unit->stored_diag_end();
1310             D != DEnd; ++D) {
1311          CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOptions());
1312          CXString Msg = clang_formatDiagnostic(&Diag,
1313                                      clang_defaultDiagnosticDisplayOptions());
1314          fprintf(stderr, "%s\n", clang_getCString(Msg));
1315          clang_disposeString(Msg);
1316        }
1317#ifdef LLVM_ON_WIN32
1318        // On Windows, force a flush, since there may be multiple copies of
1319        // stderr and stdout in the file system, all with different buffers
1320        // but writing to the same device.
1321        fflush(stderr);
1322#endif
1323      }
1324    }
1325
1326    PTUI->result = Unit.take();
1327    return;
1328  }
1329
1330  // Build up the arguments for invoking 'clang'.
1331  std::vector<const char *> argv;
1332
1333  // First add the complete path to the 'clang' executable.
1334  llvm::sys::Path ClangPath = static_cast<CIndexer *>(CIdx)->getClangPath();
1335  argv.push_back(ClangPath.c_str());
1336
1337  // Add the '-emit-ast' option as our execution mode for 'clang'.
1338  argv.push_back("-emit-ast");
1339
1340  // The 'source_filename' argument is optional.  If the caller does not
1341  // specify it then it is assumed that the source file is specified
1342  // in the actual argument list.
1343  if (source_filename)
1344    argv.push_back(source_filename);
1345
1346  // Generate a temporary name for the AST file.
1347  argv.push_back("-o");
1348  char astTmpFile[L_tmpnam];
1349  argv.push_back(tmpnam(astTmpFile));
1350
1351  // Since the Clang C library is primarily used by batch tools dealing with
1352  // (often very broken) source code, where spell-checking can have a
1353  // significant negative impact on performance (particularly when
1354  // precompiled headers are involved), we disable it by default.
1355  // Note that we place this argument early in the list, so that it can be
1356  // overridden by the caller with "-fspell-checking".
1357  argv.push_back("-fno-spell-checking");
1358
1359  // Remap any unsaved files to temporary files.
1360  std::vector<llvm::sys::Path> TemporaryFiles;
1361  std::vector<std::string> RemapArgs;
1362  if (RemapFiles(num_unsaved_files, unsaved_files, RemapArgs, TemporaryFiles))
1363    return;
1364
1365  // The pointers into the elements of RemapArgs are stable because we
1366  // won't be adding anything to RemapArgs after this point.
1367  for (unsigned i = 0, e = RemapArgs.size(); i != e; ++i)
1368    argv.push_back(RemapArgs[i].c_str());
1369
1370  // Process the compiler options, stripping off '-o', '-c', '-fsyntax-only'.
1371  for (int i = 0; i < num_command_line_args; ++i)
1372    if (const char *arg = command_line_args[i]) {
1373      if (strcmp(arg, "-o") == 0) {
1374        ++i; // Also skip the matching argument.
1375        continue;
1376      }
1377      if (strcmp(arg, "-emit-ast") == 0 ||
1378          strcmp(arg, "-c") == 0 ||
1379          strcmp(arg, "-fsyntax-only") == 0) {
1380        continue;
1381      }
1382
1383      // Keep the argument.
1384      argv.push_back(arg);
1385    }
1386
1387  // Generate a temporary name for the diagnostics file.
1388  char tmpFileResults[L_tmpnam];
1389  char *tmpResultsFileName = tmpnam(tmpFileResults);
1390  llvm::sys::Path DiagnosticsFile(tmpResultsFileName);
1391  TemporaryFiles.push_back(DiagnosticsFile);
1392  argv.push_back("-fdiagnostics-binary");
1393
1394  // Do we need the detailed preprocessing record?
1395  if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
1396    argv.push_back("-Xclang");
1397    argv.push_back("-detailed-preprocessing-record");
1398  }
1399
1400  // Add the null terminator.
1401  argv.push_back(NULL);
1402
1403  // Invoke 'clang'.
1404  llvm::sys::Path DevNull; // leave empty, causes redirection to /dev/null
1405                           // on Unix or NUL (Windows).
1406  std::string ErrMsg;
1407  const llvm::sys::Path *Redirects[] = { &DevNull, &DevNull, &DiagnosticsFile,
1408                                         NULL };
1409  llvm::sys::Program::ExecuteAndWait(ClangPath, &argv[0], /* env */ NULL,
1410      /* redirects */ &Redirects[0],
1411      /* secondsToWait */ 0, /* memoryLimits */ 0, &ErrMsg);
1412
1413  if (!ErrMsg.empty()) {
1414    std::string AllArgs;
1415    for (std::vector<const char*>::iterator I = argv.begin(), E = argv.end();
1416         I != E; ++I) {
1417      AllArgs += ' ';
1418      if (*I)
1419        AllArgs += *I;
1420    }
1421
1422    Diags->Report(diag::err_fe_invoking) << AllArgs << ErrMsg;
1423  }
1424
1425  ASTUnit *ATU = ASTUnit::LoadFromASTFile(astTmpFile, Diags,
1426                                          CXXIdx->getOnlyLocalDecls(),
1427                                          RemappedFiles.data(),
1428                                          RemappedFiles.size(),
1429                                          /*CaptureDiagnostics=*/true);
1430  if (ATU) {
1431    LoadSerializedDiagnostics(DiagnosticsFile,
1432                              num_unsaved_files, unsaved_files,
1433                              ATU->getFileManager(),
1434                              ATU->getSourceManager(),
1435                              ATU->getStoredDiagnostics());
1436  } else if (CXXIdx->getDisplayDiagnostics()) {
1437    // We failed to load the ASTUnit, but we can still deserialize the
1438    // diagnostics and emit them.
1439    FileManager FileMgr;
1440    Diagnostic Diag;
1441    SourceManager SourceMgr(Diag);
1442    // FIXME: Faked LangOpts!
1443    LangOptions LangOpts;
1444    llvm::SmallVector<StoredDiagnostic, 4> Diags;
1445    LoadSerializedDiagnostics(DiagnosticsFile,
1446                              num_unsaved_files, unsaved_files,
1447                              FileMgr, SourceMgr, Diags);
1448    for (llvm::SmallVector<StoredDiagnostic, 4>::iterator D = Diags.begin(),
1449                                                       DEnd = Diags.end();
1450         D != DEnd; ++D) {
1451      CXStoredDiagnostic Diag(*D, LangOpts);
1452      CXString Msg = clang_formatDiagnostic(&Diag,
1453                                      clang_defaultDiagnosticDisplayOptions());
1454      fprintf(stderr, "%s\n", clang_getCString(Msg));
1455      clang_disposeString(Msg);
1456    }
1457
1458#ifdef LLVM_ON_WIN32
1459    // On Windows, force a flush, since there may be multiple copies of
1460    // stderr and stdout in the file system, all with different buffers
1461    // but writing to the same device.
1462    fflush(stderr);
1463#endif
1464  }
1465
1466  if (ATU) {
1467    // Make the translation unit responsible for destroying all temporary files.
1468    for (unsigned i = 0, e = TemporaryFiles.size(); i != e; ++i)
1469      ATU->addTemporaryFile(TemporaryFiles[i]);
1470    ATU->addTemporaryFile(llvm::sys::Path(ATU->getASTFileName()));
1471  } else {
1472    // Destroy all of the temporary files now; they can't be referenced any
1473    // longer.
1474    llvm::sys::Path(astTmpFile).eraseFromDisk();
1475    for (unsigned i = 0, e = TemporaryFiles.size(); i != e; ++i)
1476      TemporaryFiles[i].eraseFromDisk();
1477  }
1478
1479  PTUI->result = ATU;
1480}
1481CXTranslationUnit clang_parseTranslationUnit(CXIndex CIdx,
1482                                             const char *source_filename,
1483                                             const char **command_line_args,
1484                                             int num_command_line_args,
1485                                             struct CXUnsavedFile *unsaved_files,
1486                                             unsigned num_unsaved_files,
1487                                             unsigned options) {
1488  ParseTranslationUnitInfo PTUI = { CIdx, source_filename, command_line_args,
1489                                    num_command_line_args, unsaved_files, num_unsaved_files,
1490                                    options, 0 };
1491  llvm::CrashRecoveryContext CRC;
1492
1493  if (!CRC.RunSafely(clang_parseTranslationUnit_Impl, &PTUI)) {
1494    fprintf(stderr, "libclang: crash detected during parsing: {\n");
1495    fprintf(stderr, "  'source_filename' : '%s'\n", source_filename);
1496    fprintf(stderr, "  'command_line_args' : [");
1497    for (int i = 0; i != num_command_line_args; ++i) {
1498      if (i)
1499        fprintf(stderr, ", ");
1500      fprintf(stderr, "'%s'", command_line_args[i]);
1501    }
1502    fprintf(stderr, "],\n");
1503    fprintf(stderr, "  'unsaved_files' : [");
1504    for (unsigned i = 0; i != num_unsaved_files; ++i) {
1505      if (i)
1506        fprintf(stderr, ", ");
1507      fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
1508              unsaved_files[i].Length);
1509    }
1510    fprintf(stderr, "],\n");
1511    fprintf(stderr, "  'options' : %d,\n", options);
1512    fprintf(stderr, "}\n");
1513
1514    return 0;
1515  }
1516
1517  return PTUI.result;
1518}
1519
1520unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
1521  return CXSaveTranslationUnit_None;
1522}
1523
1524int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
1525                              unsigned options) {
1526  if (!TU)
1527    return 1;
1528
1529  return static_cast<ASTUnit *>(TU)->Save(FileName);
1530}
1531
1532void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
1533  if (CTUnit) {
1534    // If the translation unit has been marked as unsafe to free, just discard
1535    // it.
1536    if (static_cast<ASTUnit *>(CTUnit)->isUnsafeToFree())
1537      return;
1538
1539    delete static_cast<ASTUnit *>(CTUnit);
1540  }
1541}
1542
1543unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
1544  return CXReparse_None;
1545}
1546
1547struct ReparseTranslationUnitInfo {
1548  CXTranslationUnit TU;
1549  unsigned num_unsaved_files;
1550  struct CXUnsavedFile *unsaved_files;
1551  unsigned options;
1552  int result;
1553};
1554static void clang_reparseTranslationUnit_Impl(void *UserData) {
1555  ReparseTranslationUnitInfo *RTUI =
1556    static_cast<ReparseTranslationUnitInfo*>(UserData);
1557  CXTranslationUnit TU = RTUI->TU;
1558  unsigned num_unsaved_files = RTUI->num_unsaved_files;
1559  struct CXUnsavedFile *unsaved_files = RTUI->unsaved_files;
1560  unsigned options = RTUI->options;
1561  (void) options;
1562  RTUI->result = 1;
1563
1564  if (!TU)
1565    return;
1566
1567  llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
1568  for (unsigned I = 0; I != num_unsaved_files; ++I) {
1569    llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
1570    const llvm::MemoryBuffer *Buffer
1571      = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
1572    RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
1573                                           Buffer));
1574  }
1575
1576  if (!static_cast<ASTUnit *>(TU)->Reparse(RemappedFiles.data(),
1577                                           RemappedFiles.size()))
1578      RTUI->result = 0;
1579}
1580int clang_reparseTranslationUnit(CXTranslationUnit TU,
1581                                 unsigned num_unsaved_files,
1582                                 struct CXUnsavedFile *unsaved_files,
1583                                 unsigned options) {
1584  ReparseTranslationUnitInfo RTUI = { TU, num_unsaved_files, unsaved_files,
1585                                      options, 0 };
1586  llvm::CrashRecoveryContext CRC;
1587
1588  if (!CRC.RunSafely(clang_reparseTranslationUnit_Impl, &RTUI)) {
1589    fprintf(stderr, "libclang: crash detected during reparsing\n");
1590    static_cast<ASTUnit *>(TU)->setUnsafeToFree(true);
1591    return 1;
1592  }
1593
1594  return RTUI.result;
1595}
1596
1597
1598CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
1599  if (!CTUnit)
1600    return createCXString("");
1601
1602  ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit);
1603  return createCXString(CXXUnit->getOriginalSourceFileName(), true);
1604}
1605
1606CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
1607  CXCursor Result = { CXCursor_TranslationUnit, { 0, 0, TU } };
1608  return Result;
1609}
1610
1611} // end: extern "C"
1612
1613//===----------------------------------------------------------------------===//
1614// CXSourceLocation and CXSourceRange Operations.
1615//===----------------------------------------------------------------------===//
1616
1617extern "C" {
1618CXSourceLocation clang_getNullLocation() {
1619  CXSourceLocation Result = { { 0, 0 }, 0 };
1620  return Result;
1621}
1622
1623unsigned clang_equalLocations(CXSourceLocation loc1, CXSourceLocation loc2) {
1624  return (loc1.ptr_data[0] == loc2.ptr_data[0] &&
1625          loc1.ptr_data[1] == loc2.ptr_data[1] &&
1626          loc1.int_data == loc2.int_data);
1627}
1628
1629CXSourceLocation clang_getLocation(CXTranslationUnit tu,
1630                                   CXFile file,
1631                                   unsigned line,
1632                                   unsigned column) {
1633  if (!tu || !file)
1634    return clang_getNullLocation();
1635
1636  ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
1637  SourceLocation SLoc
1638    = CXXUnit->getSourceManager().getLocation(
1639                                        static_cast<const FileEntry *>(file),
1640                                              line, column);
1641
1642  return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
1643}
1644
1645CXSourceRange clang_getNullRange() {
1646  CXSourceRange Result = { { 0, 0 }, 0, 0 };
1647  return Result;
1648}
1649
1650CXSourceRange clang_getRange(CXSourceLocation begin, CXSourceLocation end) {
1651  if (begin.ptr_data[0] != end.ptr_data[0] ||
1652      begin.ptr_data[1] != end.ptr_data[1])
1653    return clang_getNullRange();
1654
1655  CXSourceRange Result = { { begin.ptr_data[0], begin.ptr_data[1] },
1656                           begin.int_data, end.int_data };
1657  return Result;
1658}
1659
1660void clang_getInstantiationLocation(CXSourceLocation location,
1661                                    CXFile *file,
1662                                    unsigned *line,
1663                                    unsigned *column,
1664                                    unsigned *offset) {
1665  SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
1666
1667  if (!location.ptr_data[0] || Loc.isInvalid()) {
1668    if (file)
1669      *file = 0;
1670    if (line)
1671      *line = 0;
1672    if (column)
1673      *column = 0;
1674    if (offset)
1675      *offset = 0;
1676    return;
1677  }
1678
1679  const SourceManager &SM =
1680    *static_cast<const SourceManager*>(location.ptr_data[0]);
1681  SourceLocation InstLoc = SM.getInstantiationLoc(Loc);
1682
1683  if (file)
1684    *file = (void *)SM.getFileEntryForID(SM.getFileID(InstLoc));
1685  if (line)
1686    *line = SM.getInstantiationLineNumber(InstLoc);
1687  if (column)
1688    *column = SM.getInstantiationColumnNumber(InstLoc);
1689  if (offset)
1690    *offset = SM.getDecomposedLoc(InstLoc).second;
1691}
1692
1693CXSourceLocation clang_getRangeStart(CXSourceRange range) {
1694  CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
1695                              range.begin_int_data };
1696  return Result;
1697}
1698
1699CXSourceLocation clang_getRangeEnd(CXSourceRange range) {
1700  CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
1701                              range.end_int_data };
1702  return Result;
1703}
1704
1705} // end: extern "C"
1706
1707//===----------------------------------------------------------------------===//
1708// CXFile Operations.
1709//===----------------------------------------------------------------------===//
1710
1711extern "C" {
1712CXString clang_getFileName(CXFile SFile) {
1713  if (!SFile)
1714    return createCXString(NULL);
1715
1716  FileEntry *FEnt = static_cast<FileEntry *>(SFile);
1717  return createCXString(FEnt->getName());
1718}
1719
1720time_t clang_getFileTime(CXFile SFile) {
1721  if (!SFile)
1722    return 0;
1723
1724  FileEntry *FEnt = static_cast<FileEntry *>(SFile);
1725  return FEnt->getModificationTime();
1726}
1727
1728CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
1729  if (!tu)
1730    return 0;
1731
1732  ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
1733
1734  FileManager &FMgr = CXXUnit->getFileManager();
1735  const FileEntry *File = FMgr.getFile(file_name, file_name+strlen(file_name));
1736  return const_cast<FileEntry *>(File);
1737}
1738
1739} // end: extern "C"
1740
1741//===----------------------------------------------------------------------===//
1742// CXCursor Operations.
1743//===----------------------------------------------------------------------===//
1744
1745static Decl *getDeclFromExpr(Stmt *E) {
1746  if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
1747    return RefExpr->getDecl();
1748  if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
1749    return ME->getMemberDecl();
1750  if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
1751    return RE->getDecl();
1752
1753  if (CallExpr *CE = dyn_cast<CallExpr>(E))
1754    return getDeclFromExpr(CE->getCallee());
1755  if (CastExpr *CE = dyn_cast<CastExpr>(E))
1756    return getDeclFromExpr(CE->getSubExpr());
1757  if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
1758    return OME->getMethodDecl();
1759
1760  return 0;
1761}
1762
1763static SourceLocation getLocationFromExpr(Expr *E) {
1764  if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
1765    return /*FIXME:*/Msg->getLeftLoc();
1766  if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
1767    return DRE->getLocation();
1768  if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
1769    return Member->getMemberLoc();
1770  if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
1771    return Ivar->getLocation();
1772  return E->getLocStart();
1773}
1774
1775extern "C" {
1776
1777unsigned clang_visitChildren(CXCursor parent,
1778                             CXCursorVisitor visitor,
1779                             CXClientData client_data) {
1780  ASTUnit *CXXUnit = getCursorASTUnit(parent);
1781
1782  CursorVisitor CursorVis(CXXUnit, visitor, client_data,
1783                          CXXUnit->getMaxPCHLevel());
1784  return CursorVis.VisitChildren(parent);
1785}
1786
1787static CXString getDeclSpelling(Decl *D) {
1788  NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
1789  if (!ND)
1790    return createCXString("");
1791
1792  if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
1793    return createCXString(OMD->getSelector().getAsString());
1794
1795  if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
1796    // No, this isn't the same as the code below. getIdentifier() is non-virtual
1797    // and returns different names. NamedDecl returns the class name and
1798    // ObjCCategoryImplDecl returns the category name.
1799    return createCXString(CIMP->getIdentifier()->getNameStart());
1800
1801  llvm::SmallString<1024> S;
1802  llvm::raw_svector_ostream os(S);
1803  ND->printName(os);
1804
1805  return createCXString(os.str());
1806}
1807
1808CXString clang_getCursorSpelling(CXCursor C) {
1809  if (clang_isTranslationUnit(C.kind))
1810    return clang_getTranslationUnitSpelling(C.data[2]);
1811
1812  if (clang_isReference(C.kind)) {
1813    switch (C.kind) {
1814    case CXCursor_ObjCSuperClassRef: {
1815      ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
1816      return createCXString(Super->getIdentifier()->getNameStart());
1817    }
1818    case CXCursor_ObjCClassRef: {
1819      ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
1820      return createCXString(Class->getIdentifier()->getNameStart());
1821    }
1822    case CXCursor_ObjCProtocolRef: {
1823      ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
1824      assert(OID && "getCursorSpelling(): Missing protocol decl");
1825      return createCXString(OID->getIdentifier()->getNameStart());
1826    }
1827    case CXCursor_TypeRef: {
1828      TypeDecl *Type = getCursorTypeRef(C).first;
1829      assert(Type && "Missing type decl");
1830
1831      return createCXString(getCursorContext(C).getTypeDeclType(Type).
1832                              getAsString());
1833    }
1834
1835    default:
1836      return createCXString("<not implemented>");
1837    }
1838  }
1839
1840  if (clang_isExpression(C.kind)) {
1841    Decl *D = getDeclFromExpr(getCursorExpr(C));
1842    if (D)
1843      return getDeclSpelling(D);
1844    return createCXString("");
1845  }
1846
1847  if (C.kind == CXCursor_MacroInstantiation)
1848    return createCXString(getCursorMacroInstantiation(C)->getName()
1849                                                           ->getNameStart());
1850
1851  if (C.kind == CXCursor_MacroDefinition)
1852    return createCXString(getCursorMacroDefinition(C)->getName()
1853                                                           ->getNameStart());
1854
1855  if (clang_isDeclaration(C.kind))
1856    return getDeclSpelling(getCursorDecl(C));
1857
1858  return createCXString("");
1859}
1860
1861CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
1862  switch (Kind) {
1863  case CXCursor_FunctionDecl:
1864      return createCXString("FunctionDecl");
1865  case CXCursor_TypedefDecl:
1866      return createCXString("TypedefDecl");
1867  case CXCursor_EnumDecl:
1868      return createCXString("EnumDecl");
1869  case CXCursor_EnumConstantDecl:
1870      return createCXString("EnumConstantDecl");
1871  case CXCursor_StructDecl:
1872      return createCXString("StructDecl");
1873  case CXCursor_UnionDecl:
1874      return createCXString("UnionDecl");
1875  case CXCursor_ClassDecl:
1876      return createCXString("ClassDecl");
1877  case CXCursor_FieldDecl:
1878      return createCXString("FieldDecl");
1879  case CXCursor_VarDecl:
1880      return createCXString("VarDecl");
1881  case CXCursor_ParmDecl:
1882      return createCXString("ParmDecl");
1883  case CXCursor_ObjCInterfaceDecl:
1884      return createCXString("ObjCInterfaceDecl");
1885  case CXCursor_ObjCCategoryDecl:
1886      return createCXString("ObjCCategoryDecl");
1887  case CXCursor_ObjCProtocolDecl:
1888      return createCXString("ObjCProtocolDecl");
1889  case CXCursor_ObjCPropertyDecl:
1890      return createCXString("ObjCPropertyDecl");
1891  case CXCursor_ObjCIvarDecl:
1892      return createCXString("ObjCIvarDecl");
1893  case CXCursor_ObjCInstanceMethodDecl:
1894      return createCXString("ObjCInstanceMethodDecl");
1895  case CXCursor_ObjCClassMethodDecl:
1896      return createCXString("ObjCClassMethodDecl");
1897  case CXCursor_ObjCImplementationDecl:
1898      return createCXString("ObjCImplementationDecl");
1899  case CXCursor_ObjCCategoryImplDecl:
1900      return createCXString("ObjCCategoryImplDecl");
1901  case CXCursor_CXXMethod:
1902      return createCXString("CXXMethod");
1903  case CXCursor_UnexposedDecl:
1904      return createCXString("UnexposedDecl");
1905  case CXCursor_ObjCSuperClassRef:
1906      return createCXString("ObjCSuperClassRef");
1907  case CXCursor_ObjCProtocolRef:
1908      return createCXString("ObjCProtocolRef");
1909  case CXCursor_ObjCClassRef:
1910      return createCXString("ObjCClassRef");
1911  case CXCursor_TypeRef:
1912      return createCXString("TypeRef");
1913  case CXCursor_UnexposedExpr:
1914      return createCXString("UnexposedExpr");
1915  case CXCursor_BlockExpr:
1916      return createCXString("BlockExpr");
1917  case CXCursor_DeclRefExpr:
1918      return createCXString("DeclRefExpr");
1919  case CXCursor_MemberRefExpr:
1920      return createCXString("MemberRefExpr");
1921  case CXCursor_CallExpr:
1922      return createCXString("CallExpr");
1923  case CXCursor_ObjCMessageExpr:
1924      return createCXString("ObjCMessageExpr");
1925  case CXCursor_UnexposedStmt:
1926      return createCXString("UnexposedStmt");
1927  case CXCursor_InvalidFile:
1928      return createCXString("InvalidFile");
1929  case CXCursor_InvalidCode:
1930    return createCXString("InvalidCode");
1931  case CXCursor_NoDeclFound:
1932      return createCXString("NoDeclFound");
1933  case CXCursor_NotImplemented:
1934      return createCXString("NotImplemented");
1935  case CXCursor_TranslationUnit:
1936      return createCXString("TranslationUnit");
1937  case CXCursor_UnexposedAttr:
1938      return createCXString("UnexposedAttr");
1939  case CXCursor_IBActionAttr:
1940      return createCXString("attribute(ibaction)");
1941  case CXCursor_IBOutletAttr:
1942     return createCXString("attribute(iboutlet)");
1943  case CXCursor_IBOutletCollectionAttr:
1944      return createCXString("attribute(iboutletcollection)");
1945  case CXCursor_PreprocessingDirective:
1946    return createCXString("preprocessing directive");
1947  case CXCursor_MacroDefinition:
1948    return createCXString("macro definition");
1949  case CXCursor_MacroInstantiation:
1950    return createCXString("macro instantiation");
1951  case CXCursor_Namespace:
1952    return createCXString("Namespace");
1953  case CXCursor_LinkageSpec:
1954    return createCXString("LinkageSpec");
1955  }
1956
1957  llvm_unreachable("Unhandled CXCursorKind");
1958  return createCXString(NULL);
1959}
1960
1961enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
1962                                         CXCursor parent,
1963                                         CXClientData client_data) {
1964  CXCursor *BestCursor = static_cast<CXCursor *>(client_data);
1965  *BestCursor = cursor;
1966  return CXChildVisit_Recurse;
1967}
1968
1969CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
1970  if (!TU)
1971    return clang_getNullCursor();
1972
1973  ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
1974  ASTUnit::ConcurrencyCheck Check(*CXXUnit);
1975
1976  // Translate the given source location to make it point at the beginning of
1977  // the token under the cursor.
1978  SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
1979
1980  // Guard against an invalid SourceLocation, or we may assert in one
1981  // of the following calls.
1982  if (SLoc.isInvalid())
1983    return clang_getNullCursor();
1984
1985  SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
1986                                    CXXUnit->getASTContext().getLangOptions());
1987
1988  CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
1989  if (SLoc.isValid()) {
1990    // FIXME: Would be great to have a "hint" cursor, then walk from that
1991    // hint cursor upward until we find a cursor whose source range encloses
1992    // the region of interest, rather than starting from the translation unit.
1993    CXCursor Parent = clang_getTranslationUnitCursor(CXXUnit);
1994    CursorVisitor CursorVis(CXXUnit, GetCursorVisitor, &Result,
1995                            Decl::MaxPCHLevel, SourceLocation(SLoc));
1996    CursorVis.VisitChildren(Parent);
1997  }
1998  return Result;
1999}
2000
2001CXCursor clang_getNullCursor(void) {
2002  return MakeCXCursorInvalid(CXCursor_InvalidFile);
2003}
2004
2005unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
2006  return X == Y;
2007}
2008
2009unsigned clang_isInvalid(enum CXCursorKind K) {
2010  return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
2011}
2012
2013unsigned clang_isDeclaration(enum CXCursorKind K) {
2014  return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
2015}
2016
2017unsigned clang_isReference(enum CXCursorKind K) {
2018  return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
2019}
2020
2021unsigned clang_isExpression(enum CXCursorKind K) {
2022  return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
2023}
2024
2025unsigned clang_isStatement(enum CXCursorKind K) {
2026  return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
2027}
2028
2029unsigned clang_isTranslationUnit(enum CXCursorKind K) {
2030  return K == CXCursor_TranslationUnit;
2031}
2032
2033unsigned clang_isPreprocessing(enum CXCursorKind K) {
2034  return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
2035}
2036
2037unsigned clang_isUnexposed(enum CXCursorKind K) {
2038  switch (K) {
2039    case CXCursor_UnexposedDecl:
2040    case CXCursor_UnexposedExpr:
2041    case CXCursor_UnexposedStmt:
2042    case CXCursor_UnexposedAttr:
2043      return true;
2044    default:
2045      return false;
2046  }
2047}
2048
2049CXCursorKind clang_getCursorKind(CXCursor C) {
2050  return C.kind;
2051}
2052
2053CXSourceLocation clang_getCursorLocation(CXCursor C) {
2054  if (clang_isReference(C.kind)) {
2055    switch (C.kind) {
2056    case CXCursor_ObjCSuperClassRef: {
2057      std::pair<ObjCInterfaceDecl *, SourceLocation> P
2058        = getCursorObjCSuperClassRef(C);
2059      return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
2060    }
2061
2062    case CXCursor_ObjCProtocolRef: {
2063      std::pair<ObjCProtocolDecl *, SourceLocation> P
2064        = getCursorObjCProtocolRef(C);
2065      return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
2066    }
2067
2068    case CXCursor_ObjCClassRef: {
2069      std::pair<ObjCInterfaceDecl *, SourceLocation> P
2070        = getCursorObjCClassRef(C);
2071      return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
2072    }
2073
2074    case CXCursor_TypeRef: {
2075      std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
2076      return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
2077    }
2078
2079    default:
2080      // FIXME: Need a way to enumerate all non-reference cases.
2081      llvm_unreachable("Missed a reference kind");
2082    }
2083  }
2084
2085  if (clang_isExpression(C.kind))
2086    return cxloc::translateSourceLocation(getCursorContext(C),
2087                                   getLocationFromExpr(getCursorExpr(C)));
2088
2089  if (C.kind == CXCursor_PreprocessingDirective) {
2090    SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
2091    return cxloc::translateSourceLocation(getCursorContext(C), L);
2092  }
2093
2094  if (C.kind == CXCursor_MacroInstantiation) {
2095    SourceLocation L
2096      = cxcursor::getCursorMacroInstantiation(C)->getSourceRange().getBegin();
2097    return cxloc::translateSourceLocation(getCursorContext(C), L);
2098  }
2099
2100  if (C.kind == CXCursor_MacroDefinition) {
2101    SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
2102    return cxloc::translateSourceLocation(getCursorContext(C), L);
2103  }
2104
2105  if (C.kind < CXCursor_FirstDecl || C.kind > CXCursor_LastDecl)
2106    return clang_getNullLocation();
2107
2108  Decl *D = getCursorDecl(C);
2109  SourceLocation Loc = D->getLocation();
2110  if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
2111    Loc = Class->getClassLoc();
2112  return cxloc::translateSourceLocation(getCursorContext(C), Loc);
2113}
2114
2115} // end extern "C"
2116
2117static SourceRange getRawCursorExtent(CXCursor C) {
2118  if (clang_isReference(C.kind)) {
2119    switch (C.kind) {
2120    case CXCursor_ObjCSuperClassRef:
2121      return  getCursorObjCSuperClassRef(C).second;
2122
2123    case CXCursor_ObjCProtocolRef:
2124      return getCursorObjCProtocolRef(C).second;
2125
2126    case CXCursor_ObjCClassRef:
2127      return getCursorObjCClassRef(C).second;
2128
2129    case CXCursor_TypeRef:
2130      return getCursorTypeRef(C).second;
2131
2132    default:
2133      // FIXME: Need a way to enumerate all non-reference cases.
2134      llvm_unreachable("Missed a reference kind");
2135    }
2136  }
2137
2138  if (clang_isExpression(C.kind))
2139    return getCursorExpr(C)->getSourceRange();
2140
2141  if (clang_isStatement(C.kind))
2142    return getCursorStmt(C)->getSourceRange();
2143
2144  if (C.kind == CXCursor_PreprocessingDirective)
2145    return cxcursor::getCursorPreprocessingDirective(C);
2146
2147  if (C.kind == CXCursor_MacroInstantiation)
2148    return cxcursor::getCursorMacroInstantiation(C)->getSourceRange();
2149
2150  if (C.kind == CXCursor_MacroDefinition)
2151    return cxcursor::getCursorMacroDefinition(C)->getSourceRange();
2152
2153  if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl)
2154    return getCursorDecl(C)->getSourceRange();
2155
2156  return SourceRange();
2157}
2158
2159extern "C" {
2160
2161CXSourceRange clang_getCursorExtent(CXCursor C) {
2162  SourceRange R = getRawCursorExtent(C);
2163  if (R.isInvalid())
2164    return clang_getNullRange();
2165
2166  return cxloc::translateSourceRange(getCursorContext(C), R);
2167}
2168
2169CXCursor clang_getCursorReferenced(CXCursor C) {
2170  if (clang_isInvalid(C.kind))
2171    return clang_getNullCursor();
2172
2173  ASTUnit *CXXUnit = getCursorASTUnit(C);
2174  if (clang_isDeclaration(C.kind))
2175    return C;
2176
2177  if (clang_isExpression(C.kind)) {
2178    Decl *D = getDeclFromExpr(getCursorExpr(C));
2179    if (D)
2180      return MakeCXCursor(D, CXXUnit);
2181    return clang_getNullCursor();
2182  }
2183
2184  if (C.kind == CXCursor_MacroInstantiation) {
2185    if (MacroDefinition *Def = getCursorMacroInstantiation(C)->getDefinition())
2186      return MakeMacroDefinitionCursor(Def, CXXUnit);
2187  }
2188
2189  if (!clang_isReference(C.kind))
2190    return clang_getNullCursor();
2191
2192  switch (C.kind) {
2193    case CXCursor_ObjCSuperClassRef:
2194      return MakeCXCursor(getCursorObjCSuperClassRef(C).first, CXXUnit);
2195
2196    case CXCursor_ObjCProtocolRef: {
2197      return MakeCXCursor(getCursorObjCProtocolRef(C).first, CXXUnit);
2198
2199    case CXCursor_ObjCClassRef:
2200      return MakeCXCursor(getCursorObjCClassRef(C).first, CXXUnit);
2201
2202    case CXCursor_TypeRef:
2203      return MakeCXCursor(getCursorTypeRef(C).first, CXXUnit);
2204
2205    default:
2206      // We would prefer to enumerate all non-reference cursor kinds here.
2207      llvm_unreachable("Unhandled reference cursor kind");
2208      break;
2209    }
2210  }
2211
2212  return clang_getNullCursor();
2213}
2214
2215CXCursor clang_getCursorDefinition(CXCursor C) {
2216  if (clang_isInvalid(C.kind))
2217    return clang_getNullCursor();
2218
2219  ASTUnit *CXXUnit = getCursorASTUnit(C);
2220
2221  bool WasReference = false;
2222  if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
2223    C = clang_getCursorReferenced(C);
2224    WasReference = true;
2225  }
2226
2227  if (C.kind == CXCursor_MacroInstantiation)
2228    return clang_getCursorReferenced(C);
2229
2230  if (!clang_isDeclaration(C.kind))
2231    return clang_getNullCursor();
2232
2233  Decl *D = getCursorDecl(C);
2234  if (!D)
2235    return clang_getNullCursor();
2236
2237  switch (D->getKind()) {
2238  // Declaration kinds that don't really separate the notions of
2239  // declaration and definition.
2240  case Decl::Namespace:
2241  case Decl::Typedef:
2242  case Decl::TemplateTypeParm:
2243  case Decl::EnumConstant:
2244  case Decl::Field:
2245  case Decl::ObjCIvar:
2246  case Decl::ObjCAtDefsField:
2247  case Decl::ImplicitParam:
2248  case Decl::ParmVar:
2249  case Decl::NonTypeTemplateParm:
2250  case Decl::TemplateTemplateParm:
2251  case Decl::ObjCCategoryImpl:
2252  case Decl::ObjCImplementation:
2253  case Decl::AccessSpec:
2254  case Decl::LinkageSpec:
2255  case Decl::ObjCPropertyImpl:
2256  case Decl::FileScopeAsm:
2257  case Decl::StaticAssert:
2258  case Decl::Block:
2259    return C;
2260
2261  // Declaration kinds that don't make any sense here, but are
2262  // nonetheless harmless.
2263  case Decl::TranslationUnit:
2264    break;
2265
2266  // Declaration kinds for which the definition is not resolvable.
2267  case Decl::UnresolvedUsingTypename:
2268  case Decl::UnresolvedUsingValue:
2269    break;
2270
2271  case Decl::UsingDirective:
2272    return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
2273                        CXXUnit);
2274
2275  case Decl::NamespaceAlias:
2276    return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), CXXUnit);
2277
2278  case Decl::Enum:
2279  case Decl::Record:
2280  case Decl::CXXRecord:
2281  case Decl::ClassTemplateSpecialization:
2282  case Decl::ClassTemplatePartialSpecialization:
2283    if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
2284      return MakeCXCursor(Def, CXXUnit);
2285    return clang_getNullCursor();
2286
2287  case Decl::Function:
2288  case Decl::CXXMethod:
2289  case Decl::CXXConstructor:
2290  case Decl::CXXDestructor:
2291  case Decl::CXXConversion: {
2292    const FunctionDecl *Def = 0;
2293    if (cast<FunctionDecl>(D)->getBody(Def))
2294      return MakeCXCursor(const_cast<FunctionDecl *>(Def), CXXUnit);
2295    return clang_getNullCursor();
2296  }
2297
2298  case Decl::Var: {
2299    // Ask the variable if it has a definition.
2300    if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
2301      return MakeCXCursor(Def, CXXUnit);
2302    return clang_getNullCursor();
2303  }
2304
2305  case Decl::FunctionTemplate: {
2306    const FunctionDecl *Def = 0;
2307    if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
2308      return MakeCXCursor(Def->getDescribedFunctionTemplate(), CXXUnit);
2309    return clang_getNullCursor();
2310  }
2311
2312  case Decl::ClassTemplate: {
2313    if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
2314                                                            ->getDefinition())
2315      return MakeCXCursor(
2316                         cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
2317                          CXXUnit);
2318    return clang_getNullCursor();
2319  }
2320
2321  case Decl::Using: {
2322    UsingDecl *Using = cast<UsingDecl>(D);
2323    CXCursor Def = clang_getNullCursor();
2324    for (UsingDecl::shadow_iterator S = Using->shadow_begin(),
2325                                 SEnd = Using->shadow_end();
2326         S != SEnd; ++S) {
2327      if (Def != clang_getNullCursor()) {
2328        // FIXME: We have no way to return multiple results.
2329        return clang_getNullCursor();
2330      }
2331
2332      Def = clang_getCursorDefinition(MakeCXCursor((*S)->getTargetDecl(),
2333                                                   CXXUnit));
2334    }
2335
2336    return Def;
2337  }
2338
2339  case Decl::UsingShadow:
2340    return clang_getCursorDefinition(
2341                       MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
2342                                    CXXUnit));
2343
2344  case Decl::ObjCMethod: {
2345    ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
2346    if (Method->isThisDeclarationADefinition())
2347      return C;
2348
2349    // Dig out the method definition in the associated
2350    // @implementation, if we have it.
2351    // FIXME: The ASTs should make finding the definition easier.
2352    if (ObjCInterfaceDecl *Class
2353                       = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
2354      if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
2355        if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
2356                                                  Method->isInstanceMethod()))
2357          if (Def->isThisDeclarationADefinition())
2358            return MakeCXCursor(Def, CXXUnit);
2359
2360    return clang_getNullCursor();
2361  }
2362
2363  case Decl::ObjCCategory:
2364    if (ObjCCategoryImplDecl *Impl
2365                               = cast<ObjCCategoryDecl>(D)->getImplementation())
2366      return MakeCXCursor(Impl, CXXUnit);
2367    return clang_getNullCursor();
2368
2369  case Decl::ObjCProtocol:
2370    if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
2371      return C;
2372    return clang_getNullCursor();
2373
2374  case Decl::ObjCInterface:
2375    // There are two notions of a "definition" for an Objective-C
2376    // class: the interface and its implementation. When we resolved a
2377    // reference to an Objective-C class, produce the @interface as
2378    // the definition; when we were provided with the interface,
2379    // produce the @implementation as the definition.
2380    if (WasReference) {
2381      if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
2382        return C;
2383    } else if (ObjCImplementationDecl *Impl
2384                              = cast<ObjCInterfaceDecl>(D)->getImplementation())
2385      return MakeCXCursor(Impl, CXXUnit);
2386    return clang_getNullCursor();
2387
2388  case Decl::ObjCProperty:
2389    // FIXME: We don't really know where to find the
2390    // ObjCPropertyImplDecls that implement this property.
2391    return clang_getNullCursor();
2392
2393  case Decl::ObjCCompatibleAlias:
2394    if (ObjCInterfaceDecl *Class
2395          = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
2396      if (!Class->isForwardDecl())
2397        return MakeCXCursor(Class, CXXUnit);
2398
2399    return clang_getNullCursor();
2400
2401  case Decl::ObjCForwardProtocol: {
2402    ObjCForwardProtocolDecl *Forward = cast<ObjCForwardProtocolDecl>(D);
2403    if (Forward->protocol_size() == 1)
2404      return clang_getCursorDefinition(
2405                                     MakeCXCursor(*Forward->protocol_begin(),
2406                                                  CXXUnit));
2407
2408    // FIXME: Cannot return multiple definitions.
2409    return clang_getNullCursor();
2410  }
2411
2412  case Decl::ObjCClass: {
2413    ObjCClassDecl *Class = cast<ObjCClassDecl>(D);
2414    if (Class->size() == 1) {
2415      ObjCInterfaceDecl *IFace = Class->begin()->getInterface();
2416      if (!IFace->isForwardDecl())
2417        return MakeCXCursor(IFace, CXXUnit);
2418      return clang_getNullCursor();
2419    }
2420
2421    // FIXME: Cannot return multiple definitions.
2422    return clang_getNullCursor();
2423  }
2424
2425  case Decl::Friend:
2426    if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
2427      return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
2428    return clang_getNullCursor();
2429
2430  case Decl::FriendTemplate:
2431    if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
2432      return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
2433    return clang_getNullCursor();
2434  }
2435
2436  return clang_getNullCursor();
2437}
2438
2439unsigned clang_isCursorDefinition(CXCursor C) {
2440  if (!clang_isDeclaration(C.kind))
2441    return 0;
2442
2443  return clang_getCursorDefinition(C) == C;
2444}
2445
2446void clang_getDefinitionSpellingAndExtent(CXCursor C,
2447                                          const char **startBuf,
2448                                          const char **endBuf,
2449                                          unsigned *startLine,
2450                                          unsigned *startColumn,
2451                                          unsigned *endLine,
2452                                          unsigned *endColumn) {
2453  assert(getCursorDecl(C) && "CXCursor has null decl");
2454  NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
2455  FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
2456  CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
2457
2458  SourceManager &SM = FD->getASTContext().getSourceManager();
2459  *startBuf = SM.getCharacterData(Body->getLBracLoc());
2460  *endBuf = SM.getCharacterData(Body->getRBracLoc());
2461  *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
2462  *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
2463  *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
2464  *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
2465}
2466
2467void clang_enableStackTraces(void) {
2468  llvm::sys::PrintStackTraceOnErrorSignal();
2469}
2470
2471} // end: extern "C"
2472
2473//===----------------------------------------------------------------------===//
2474// Token-based Operations.
2475//===----------------------------------------------------------------------===//
2476
2477/* CXToken layout:
2478 *   int_data[0]: a CXTokenKind
2479 *   int_data[1]: starting token location
2480 *   int_data[2]: token length
2481 *   int_data[3]: reserved
2482 *   ptr_data: for identifiers and keywords, an IdentifierInfo*.
2483 *   otherwise unused.
2484 */
2485extern "C" {
2486
2487CXTokenKind clang_getTokenKind(CXToken CXTok) {
2488  return static_cast<CXTokenKind>(CXTok.int_data[0]);
2489}
2490
2491CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
2492  switch (clang_getTokenKind(CXTok)) {
2493  case CXToken_Identifier:
2494  case CXToken_Keyword:
2495    // We know we have an IdentifierInfo*, so use that.
2496    return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
2497                            ->getNameStart());
2498
2499  case CXToken_Literal: {
2500    // We have stashed the starting pointer in the ptr_data field. Use it.
2501    const char *Text = static_cast<const char *>(CXTok.ptr_data);
2502    return createCXString(llvm::StringRef(Text, CXTok.int_data[2]));
2503  }
2504
2505  case CXToken_Punctuation:
2506  case CXToken_Comment:
2507    break;
2508  }
2509
2510  // We have to find the starting buffer pointer the hard way, by
2511  // deconstructing the source location.
2512  ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2513  if (!CXXUnit)
2514    return createCXString("");
2515
2516  SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
2517  std::pair<FileID, unsigned> LocInfo
2518    = CXXUnit->getSourceManager().getDecomposedLoc(Loc);
2519  bool Invalid = false;
2520  llvm::StringRef Buffer
2521    = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
2522  if (Invalid)
2523    return createCXString("");
2524
2525  return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
2526}
2527
2528CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
2529  ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2530  if (!CXXUnit)
2531    return clang_getNullLocation();
2532
2533  return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
2534                        SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
2535}
2536
2537CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
2538  ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2539  if (!CXXUnit)
2540    return clang_getNullRange();
2541
2542  return cxloc::translateSourceRange(CXXUnit->getASTContext(),
2543                        SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
2544}
2545
2546void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
2547                    CXToken **Tokens, unsigned *NumTokens) {
2548  if (Tokens)
2549    *Tokens = 0;
2550  if (NumTokens)
2551    *NumTokens = 0;
2552
2553  ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2554  if (!CXXUnit || !Tokens || !NumTokens)
2555    return;
2556
2557  ASTUnit::ConcurrencyCheck Check(*CXXUnit);
2558
2559  SourceRange R = cxloc::translateCXSourceRange(Range);
2560  if (R.isInvalid())
2561    return;
2562
2563  SourceManager &SourceMgr = CXXUnit->getSourceManager();
2564  std::pair<FileID, unsigned> BeginLocInfo
2565    = SourceMgr.getDecomposedLoc(R.getBegin());
2566  std::pair<FileID, unsigned> EndLocInfo
2567    = SourceMgr.getDecomposedLoc(R.getEnd());
2568
2569  // Cannot tokenize across files.
2570  if (BeginLocInfo.first != EndLocInfo.first)
2571    return;
2572
2573  // Create a lexer
2574  bool Invalid = false;
2575  llvm::StringRef Buffer
2576    = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
2577  if (Invalid)
2578    return;
2579
2580  Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
2581            CXXUnit->getASTContext().getLangOptions(),
2582            Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
2583  Lex.SetCommentRetentionState(true);
2584
2585  // Lex tokens until we hit the end of the range.
2586  const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
2587  llvm::SmallVector<CXToken, 32> CXTokens;
2588  Token Tok;
2589  do {
2590    // Lex the next token
2591    Lex.LexFromRawLexer(Tok);
2592    if (Tok.is(tok::eof))
2593      break;
2594
2595    // Initialize the CXToken.
2596    CXToken CXTok;
2597
2598    //   - Common fields
2599    CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
2600    CXTok.int_data[2] = Tok.getLength();
2601    CXTok.int_data[3] = 0;
2602
2603    //   - Kind-specific fields
2604    if (Tok.isLiteral()) {
2605      CXTok.int_data[0] = CXToken_Literal;
2606      CXTok.ptr_data = (void *)Tok.getLiteralData();
2607    } else if (Tok.is(tok::identifier)) {
2608      // Lookup the identifier to determine whether we have a keyword.
2609      std::pair<FileID, unsigned> LocInfo
2610        = SourceMgr.getDecomposedLoc(Tok.getLocation());
2611      bool Invalid = false;
2612      llvm::StringRef Buf
2613        = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
2614      if (Invalid)
2615        return;
2616
2617      const char *StartPos = Buf.data() + LocInfo.second;
2618      IdentifierInfo *II
2619        = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok, StartPos);
2620
2621      if (II->getObjCKeywordID() != tok::objc_not_keyword) {
2622        CXTok.int_data[0] = CXToken_Keyword;
2623      }
2624      else {
2625        CXTok.int_data[0] = II->getTokenID() == tok::identifier?
2626                                CXToken_Identifier
2627                              : CXToken_Keyword;
2628      }
2629      CXTok.ptr_data = II;
2630    } else if (Tok.is(tok::comment)) {
2631      CXTok.int_data[0] = CXToken_Comment;
2632      CXTok.ptr_data = 0;
2633    } else {
2634      CXTok.int_data[0] = CXToken_Punctuation;
2635      CXTok.ptr_data = 0;
2636    }
2637    CXTokens.push_back(CXTok);
2638  } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
2639
2640  if (CXTokens.empty())
2641    return;
2642
2643  *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
2644  memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
2645  *NumTokens = CXTokens.size();
2646}
2647
2648void clang_disposeTokens(CXTranslationUnit TU,
2649                         CXToken *Tokens, unsigned NumTokens) {
2650  free(Tokens);
2651}
2652
2653} // end: extern "C"
2654
2655//===----------------------------------------------------------------------===//
2656// Token annotation APIs.
2657//===----------------------------------------------------------------------===//
2658
2659typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
2660static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
2661                                                     CXCursor parent,
2662                                                     CXClientData client_data);
2663namespace {
2664class AnnotateTokensWorker {
2665  AnnotateTokensData &Annotated;
2666  CXToken *Tokens;
2667  CXCursor *Cursors;
2668  unsigned NumTokens;
2669  unsigned TokIdx;
2670  CursorVisitor AnnotateVis;
2671  SourceManager &SrcMgr;
2672
2673  bool MoreTokens() const { return TokIdx < NumTokens; }
2674  unsigned NextToken() const { return TokIdx; }
2675  void AdvanceToken() { ++TokIdx; }
2676  SourceLocation GetTokenLoc(unsigned tokI) {
2677    return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
2678  }
2679
2680public:
2681  AnnotateTokensWorker(AnnotateTokensData &annotated,
2682                       CXToken *tokens, CXCursor *cursors, unsigned numTokens,
2683                       ASTUnit *CXXUnit, SourceRange RegionOfInterest)
2684    : Annotated(annotated), Tokens(tokens), Cursors(cursors),
2685      NumTokens(numTokens), TokIdx(0),
2686      AnnotateVis(CXXUnit, AnnotateTokensVisitor, this,
2687                  Decl::MaxPCHLevel, RegionOfInterest),
2688      SrcMgr(CXXUnit->getSourceManager()) {}
2689
2690  void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
2691  enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
2692  void AnnotateTokens(CXCursor parent);
2693};
2694}
2695
2696void AnnotateTokensWorker::AnnotateTokens(CXCursor parent) {
2697  // Walk the AST within the region of interest, annotating tokens
2698  // along the way.
2699  VisitChildren(parent);
2700
2701  for (unsigned I = 0 ; I < TokIdx ; ++I) {
2702    AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
2703    if (Pos != Annotated.end())
2704      Cursors[I] = Pos->second;
2705  }
2706
2707  // Finish up annotating any tokens left.
2708  if (!MoreTokens())
2709    return;
2710
2711  const CXCursor &C = clang_getNullCursor();
2712  for (unsigned I = TokIdx ; I < NumTokens ; ++I) {
2713    AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
2714    Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second;
2715  }
2716}
2717
2718enum CXChildVisitResult
2719AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
2720  CXSourceLocation Loc = clang_getCursorLocation(cursor);
2721  // We can always annotate a preprocessing directive/macro instantiation.
2722  if (clang_isPreprocessing(cursor.kind)) {
2723    Annotated[Loc.int_data] = cursor;
2724    return CXChildVisit_Recurse;
2725  }
2726
2727  SourceRange cursorRange = getRawCursorExtent(cursor);
2728
2729  if (cursorRange.isInvalid())
2730    return CXChildVisit_Continue;
2731
2732  SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data);
2733
2734  // Adjust the annotated range based specific declarations.
2735  const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
2736  if (cursorK >= CXCursor_FirstDecl && cursorK <= CXCursor_LastDecl) {
2737    Decl *D = cxcursor::getCursorDecl(cursor);
2738    // Don't visit synthesized ObjC methods, since they have no syntatic
2739    // representation in the source.
2740    if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
2741      if (MD->isSynthesized())
2742        return CXChildVisit_Continue;
2743    }
2744    if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
2745      if (TypeSourceInfo *TI = DD->getTypeSourceInfo()) {
2746        TypeLoc TL = TI->getTypeLoc();
2747        SourceLocation TLoc = TL.getSourceRange().getBegin();
2748        if (TLoc.isValid() &&
2749            SrcMgr.isBeforeInTranslationUnit(TLoc, L))
2750          cursorRange.setBegin(TLoc);
2751      }
2752    }
2753  }
2754
2755  // If the location of the cursor occurs within a macro instantiation, record
2756  // the spelling location of the cursor in our annotation map.  We can then
2757  // paper over the token labelings during a post-processing step to try and
2758  // get cursor mappings for tokens that are the *arguments* of a macro
2759  // instantiation.
2760  if (L.isMacroID()) {
2761    unsigned rawEncoding = SrcMgr.getSpellingLoc(L).getRawEncoding();
2762    // Only invalidate the old annotation if it isn't part of a preprocessing
2763    // directive.  Here we assume that the default construction of CXCursor
2764    // results in CXCursor.kind being an initialized value (i.e., 0).  If
2765    // this isn't the case, we can fix by doing lookup + insertion.
2766
2767    CXCursor &oldC = Annotated[rawEncoding];
2768    if (!clang_isPreprocessing(oldC.kind))
2769      oldC = cursor;
2770  }
2771
2772  const enum CXCursorKind K = clang_getCursorKind(parent);
2773  const CXCursor updateC =
2774    (clang_isInvalid(K) || K == CXCursor_TranslationUnit ||
2775     L.isMacroID())
2776    ? clang_getNullCursor() : parent;
2777
2778  while (MoreTokens()) {
2779    const unsigned I = NextToken();
2780    SourceLocation TokLoc = GetTokenLoc(I);
2781    switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
2782      case RangeBefore:
2783        Cursors[I] = updateC;
2784        AdvanceToken();
2785        continue;
2786      case RangeAfter:
2787      case RangeOverlap:
2788        break;
2789    }
2790    break;
2791  }
2792
2793  // Visit children to get their cursor information.
2794  const unsigned BeforeChildren = NextToken();
2795  VisitChildren(cursor);
2796  const unsigned AfterChildren = NextToken();
2797
2798  // Adjust 'Last' to the last token within the extent of the cursor.
2799  while (MoreTokens()) {
2800    const unsigned I = NextToken();
2801    SourceLocation TokLoc = GetTokenLoc(I);
2802    switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
2803      case RangeBefore:
2804        assert(0 && "Infeasible");
2805      case RangeAfter:
2806        break;
2807      case RangeOverlap:
2808        Cursors[I] = updateC;
2809        AdvanceToken();
2810        continue;
2811    }
2812    break;
2813  }
2814  const unsigned Last = NextToken();
2815
2816  // Scan the tokens that are at the beginning of the cursor, but are not
2817  // capture by the child cursors.
2818
2819  // For AST elements within macros, rely on a post-annotate pass to
2820  // to correctly annotate the tokens with cursors.  Otherwise we can
2821  // get confusing results of having tokens that map to cursors that really
2822  // are expanded by an instantiation.
2823  if (L.isMacroID())
2824    cursor = clang_getNullCursor();
2825
2826  for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
2827    if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
2828      break;
2829    Cursors[I] = cursor;
2830  }
2831  // Scan the tokens that are at the end of the cursor, but are not captured
2832  // but the child cursors.
2833  for (unsigned I = AfterChildren; I != Last; ++I)
2834    Cursors[I] = cursor;
2835
2836  TokIdx = Last;
2837  return CXChildVisit_Continue;
2838}
2839
2840static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
2841                                                     CXCursor parent,
2842                                                     CXClientData client_data) {
2843  return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
2844}
2845
2846extern "C" {
2847
2848void clang_annotateTokens(CXTranslationUnit TU,
2849                          CXToken *Tokens, unsigned NumTokens,
2850                          CXCursor *Cursors) {
2851
2852  if (NumTokens == 0 || !Tokens || !Cursors)
2853    return;
2854
2855  ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2856  if (!CXXUnit) {
2857    // Any token we don't specifically annotate will have a NULL cursor.
2858    const CXCursor &C = clang_getNullCursor();
2859    for (unsigned I = 0; I != NumTokens; ++I)
2860      Cursors[I] = C;
2861    return;
2862  }
2863
2864  ASTUnit::ConcurrencyCheck Check(*CXXUnit);
2865
2866  // Determine the region of interest, which contains all of the tokens.
2867  SourceRange RegionOfInterest;
2868  RegionOfInterest.setBegin(cxloc::translateSourceLocation(
2869                                        clang_getTokenLocation(TU, Tokens[0])));
2870  RegionOfInterest.setEnd(cxloc::translateSourceLocation(
2871                                clang_getTokenLocation(TU,
2872                                                       Tokens[NumTokens - 1])));
2873
2874  // A mapping from the source locations found when re-lexing or traversing the
2875  // region of interest to the corresponding cursors.
2876  AnnotateTokensData Annotated;
2877
2878  // Relex the tokens within the source range to look for preprocessing
2879  // directives.
2880  SourceManager &SourceMgr = CXXUnit->getSourceManager();
2881  std::pair<FileID, unsigned> BeginLocInfo
2882    = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
2883  std::pair<FileID, unsigned> EndLocInfo
2884    = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
2885
2886  llvm::StringRef Buffer;
2887  bool Invalid = false;
2888  if (BeginLocInfo.first == EndLocInfo.first &&
2889      ((Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid)),true) &&
2890      !Invalid) {
2891    Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
2892              CXXUnit->getASTContext().getLangOptions(),
2893              Buffer.begin(), Buffer.data() + BeginLocInfo.second,
2894              Buffer.end());
2895    Lex.SetCommentRetentionState(true);
2896
2897    // Lex tokens in raw mode until we hit the end of the range, to avoid
2898    // entering #includes or expanding macros.
2899    while (true) {
2900      Token Tok;
2901      Lex.LexFromRawLexer(Tok);
2902
2903    reprocess:
2904      if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
2905        // We have found a preprocessing directive. Gobble it up so that we
2906        // don't see it while preprocessing these tokens later, but keep track of
2907        // all of the token locations inside this preprocessing directive so that
2908        // we can annotate them appropriately.
2909        //
2910        // FIXME: Some simple tests here could identify macro definitions and
2911        // #undefs, to provide specific cursor kinds for those.
2912        std::vector<SourceLocation> Locations;
2913        do {
2914          Locations.push_back(Tok.getLocation());
2915          Lex.LexFromRawLexer(Tok);
2916        } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
2917
2918        using namespace cxcursor;
2919        CXCursor Cursor
2920          = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
2921                                                         Locations.back()),
2922                                           CXXUnit);
2923        for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
2924          Annotated[Locations[I].getRawEncoding()] = Cursor;
2925        }
2926
2927        if (Tok.isAtStartOfLine())
2928          goto reprocess;
2929
2930        continue;
2931      }
2932
2933      if (Tok.is(tok::eof))
2934        break;
2935    }
2936  }
2937
2938  // Annotate all of the source locations in the region of interest that map to
2939  // a specific cursor.
2940  AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens,
2941                         CXXUnit, RegionOfInterest);
2942  W.AnnotateTokens(clang_getTranslationUnitCursor(CXXUnit));
2943}
2944} // end: extern "C"
2945
2946//===----------------------------------------------------------------------===//
2947// Operations for querying linkage of a cursor.
2948//===----------------------------------------------------------------------===//
2949
2950extern "C" {
2951CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
2952  if (!clang_isDeclaration(cursor.kind))
2953    return CXLinkage_Invalid;
2954
2955  Decl *D = cxcursor::getCursorDecl(cursor);
2956  if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
2957    switch (ND->getLinkage()) {
2958      case NoLinkage: return CXLinkage_NoLinkage;
2959      case InternalLinkage: return CXLinkage_Internal;
2960      case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
2961      case ExternalLinkage: return CXLinkage_External;
2962    };
2963
2964  return CXLinkage_Invalid;
2965}
2966} // end: extern "C"
2967
2968//===----------------------------------------------------------------------===//
2969// Operations for querying language of a cursor.
2970//===----------------------------------------------------------------------===//
2971
2972static CXLanguageKind getDeclLanguage(const Decl *D) {
2973  switch (D->getKind()) {
2974    default:
2975      break;
2976    case Decl::ImplicitParam:
2977    case Decl::ObjCAtDefsField:
2978    case Decl::ObjCCategory:
2979    case Decl::ObjCCategoryImpl:
2980    case Decl::ObjCClass:
2981    case Decl::ObjCCompatibleAlias:
2982    case Decl::ObjCForwardProtocol:
2983    case Decl::ObjCImplementation:
2984    case Decl::ObjCInterface:
2985    case Decl::ObjCIvar:
2986    case Decl::ObjCMethod:
2987    case Decl::ObjCProperty:
2988    case Decl::ObjCPropertyImpl:
2989    case Decl::ObjCProtocol:
2990      return CXLanguage_ObjC;
2991    case Decl::CXXConstructor:
2992    case Decl::CXXConversion:
2993    case Decl::CXXDestructor:
2994    case Decl::CXXMethod:
2995    case Decl::CXXRecord:
2996    case Decl::ClassTemplate:
2997    case Decl::ClassTemplatePartialSpecialization:
2998    case Decl::ClassTemplateSpecialization:
2999    case Decl::Friend:
3000    case Decl::FriendTemplate:
3001    case Decl::FunctionTemplate:
3002    case Decl::LinkageSpec:
3003    case Decl::Namespace:
3004    case Decl::NamespaceAlias:
3005    case Decl::NonTypeTemplateParm:
3006    case Decl::StaticAssert:
3007    case Decl::TemplateTemplateParm:
3008    case Decl::TemplateTypeParm:
3009    case Decl::UnresolvedUsingTypename:
3010    case Decl::UnresolvedUsingValue:
3011    case Decl::Using:
3012    case Decl::UsingDirective:
3013    case Decl::UsingShadow:
3014      return CXLanguage_CPlusPlus;
3015  }
3016
3017  return CXLanguage_C;
3018}
3019
3020extern "C" {
3021
3022enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
3023  if (clang_isDeclaration(cursor.kind))
3024    if (Decl *D = cxcursor::getCursorDecl(cursor)) {
3025      if (D->hasAttr<UnavailableAttr>() ||
3026          (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted()))
3027        return CXAvailability_Available;
3028
3029      if (D->hasAttr<DeprecatedAttr>())
3030        return CXAvailability_Deprecated;
3031    }
3032
3033  return CXAvailability_Available;
3034}
3035
3036CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
3037  if (clang_isDeclaration(cursor.kind))
3038    return getDeclLanguage(cxcursor::getCursorDecl(cursor));
3039
3040  return CXLanguage_Invalid;
3041}
3042} // end: extern "C"
3043
3044
3045//===----------------------------------------------------------------------===//
3046// C++ AST instrospection.
3047//===----------------------------------------------------------------------===//
3048
3049extern "C" {
3050unsigned clang_CXXMethod_isStatic(CXCursor C) {
3051  if (!clang_isDeclaration(C.kind))
3052    return 0;
3053  CXXMethodDecl *D = dyn_cast<CXXMethodDecl>(cxcursor::getCursorDecl(C));
3054  return (D && D->isStatic()) ? 1 : 0;
3055}
3056
3057} // end: extern "C"
3058
3059//===----------------------------------------------------------------------===//
3060// CXString Operations.
3061//===----------------------------------------------------------------------===//
3062
3063extern "C" {
3064const char *clang_getCString(CXString string) {
3065  return string.Spelling;
3066}
3067
3068void clang_disposeString(CXString string) {
3069  if (string.MustFreeString && string.Spelling)
3070    free((void*)string.Spelling);
3071}
3072
3073} // end: extern "C"
3074
3075namespace clang { namespace cxstring {
3076CXString createCXString(const char *String, bool DupString){
3077  CXString Str;
3078  if (DupString) {
3079    Str.Spelling = strdup(String);
3080    Str.MustFreeString = 1;
3081  } else {
3082    Str.Spelling = String;
3083    Str.MustFreeString = 0;
3084  }
3085  return Str;
3086}
3087
3088CXString createCXString(llvm::StringRef String, bool DupString) {
3089  CXString Result;
3090  if (DupString || (!String.empty() && String.data()[String.size()] != 0)) {
3091    char *Spelling = (char *)malloc(String.size() + 1);
3092    memmove(Spelling, String.data(), String.size());
3093    Spelling[String.size()] = 0;
3094    Result.Spelling = Spelling;
3095    Result.MustFreeString = 1;
3096  } else {
3097    Result.Spelling = String.data();
3098    Result.MustFreeString = 0;
3099  }
3100  return Result;
3101}
3102}}
3103
3104//===----------------------------------------------------------------------===//
3105// Misc. utility functions.
3106//===----------------------------------------------------------------------===//
3107
3108extern "C" {
3109
3110CXString clang_getClangVersion() {
3111  return createCXString(getClangFullVersion());
3112}
3113
3114} // end: extern "C"
3115