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