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