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