CIndex.cpp revision 91fc0259d29be805191ccf2ab91d5e6b2e774070
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/ADT/STLExtras.h"
34#include "llvm/ADT/Optional.h"
35#include "clang/Analysis/Support/SaveAndRestore.h"
36#include "llvm/Support/CrashRecoveryContext.h"
37#include "llvm/Support/PrettyStackTrace.h"
38#include "llvm/Support/MemoryBuffer.h"
39#include "llvm/Support/raw_ostream.h"
40#include "llvm/Support/Timer.h"
41#include "llvm/System/Mutex.h"
42#include "llvm/System/Program.h"
43#include "llvm/System/Signals.h"
44#include "llvm/System/Threading.h"
45
46using namespace clang;
47using namespace clang::cxcursor;
48using namespace clang::cxstring;
49
50/// \brief The result of comparing two source ranges.
51enum RangeComparisonResult {
52  /// \brief Either the ranges overlap or one of the ranges is invalid.
53  RangeOverlap,
54
55  /// \brief The first range ends before the second range starts.
56  RangeBefore,
57
58  /// \brief The first range starts after the second range ends.
59  RangeAfter
60};
61
62/// \brief Compare two source ranges to determine their relative position in
63/// the translation unit.
64static RangeComparisonResult RangeCompare(SourceManager &SM,
65                                          SourceRange R1,
66                                          SourceRange R2) {
67  assert(R1.isValid() && "First range is invalid?");
68  assert(R2.isValid() && "Second range is invalid?");
69  if (R1.getEnd() != R2.getBegin() &&
70      SM.isBeforeInTranslationUnit(R1.getEnd(), R2.getBegin()))
71    return RangeBefore;
72  if (R2.getEnd() != R1.getBegin() &&
73      SM.isBeforeInTranslationUnit(R2.getEnd(), R1.getBegin()))
74    return RangeAfter;
75  return RangeOverlap;
76}
77
78/// \brief Determine if a source location falls within, before, or after a
79///   a given source range.
80static RangeComparisonResult LocationCompare(SourceManager &SM,
81                                             SourceLocation L, SourceRange R) {
82  assert(R.isValid() && "First range is invalid?");
83  assert(L.isValid() && "Second range is invalid?");
84  if (L == R.getBegin() || L == R.getEnd())
85    return RangeOverlap;
86  if (SM.isBeforeInTranslationUnit(L, R.getBegin()))
87    return RangeBefore;
88  if (SM.isBeforeInTranslationUnit(R.getEnd(), L))
89    return RangeAfter;
90  return RangeOverlap;
91}
92
93/// \brief Translate a Clang source range into a CIndex source range.
94///
95/// Clang internally represents ranges where the end location points to the
96/// start of the token at the end. However, for external clients it is more
97/// useful to have a CXSourceRange be a proper half-open interval. This routine
98/// does the appropriate translation.
99CXSourceRange cxloc::translateSourceRange(const SourceManager &SM,
100                                          const LangOptions &LangOpts,
101                                          const CharSourceRange &R) {
102  // We want the last character in this location, so we will adjust the
103  // location accordingly.
104  SourceLocation EndLoc = R.getEnd();
105  if (EndLoc.isValid() && EndLoc.isMacroID())
106    EndLoc = SM.getSpellingLoc(EndLoc);
107  if (R.isTokenRange() && !EndLoc.isInvalid() && EndLoc.isFileID()) {
108    unsigned Length = Lexer::MeasureTokenLength(EndLoc, SM, LangOpts);
109    EndLoc = EndLoc.getFileLocWithOffset(Length);
110  }
111
112  CXSourceRange Result = { { (void *)&SM, (void *)&LangOpts },
113                           R.getBegin().getRawEncoding(),
114                           EndLoc.getRawEncoding() };
115  return Result;
116}
117
118//===----------------------------------------------------------------------===//
119// Cursor visitor.
120//===----------------------------------------------------------------------===//
121
122namespace {
123
124class VisitorJob {
125public:
126  enum Kind { DeclVisitKind, StmtVisitKind, MemberExprPartsKind,
127              TypeLocVisitKind, OverloadExprPartsKind,
128              DeclRefExprPartsKind };
129protected:
130  void *dataA;
131  void *dataB;
132  CXCursor parent;
133  Kind K;
134  VisitorJob(CXCursor C, Kind k, void *d1, void *d2 = 0)
135    : dataA(d1), dataB(d2), parent(C), K(k) {}
136public:
137  Kind getKind() const { return K; }
138  const CXCursor &getParent() const { return parent; }
139  static bool classof(VisitorJob *VJ) { return true; }
140};
141
142typedef llvm::SmallVector<VisitorJob, 10> VisitorWorkList;
143
144// Cursor visitor.
145class CursorVisitor : public DeclVisitor<CursorVisitor, bool>,
146                      public TypeLocVisitor<CursorVisitor, bool>,
147                      public StmtVisitor<CursorVisitor, bool>
148{
149  /// \brief The translation unit we are traversing.
150  ASTUnit *TU;
151
152  /// \brief The parent cursor whose children we are traversing.
153  CXCursor Parent;
154
155  /// \brief The declaration that serves at the parent of any statement or
156  /// expression nodes.
157  Decl *StmtParent;
158
159  /// \brief The visitor function.
160  CXCursorVisitor Visitor;
161
162  /// \brief The opaque client data, to be passed along to the visitor.
163  CXClientData ClientData;
164
165  // MaxPCHLevel - the maximum PCH level of declarations that we will pass on
166  // to the visitor. Declarations with a PCH level greater than this value will
167  // be suppressed.
168  unsigned MaxPCHLevel;
169
170  /// \brief When valid, a source range to which the cursor should restrict
171  /// its search.
172  SourceRange RegionOfInterest;
173
174  // FIXME: Eventually remove.  This part of a hack to support proper
175  // iteration over all Decls contained lexically within an ObjC container.
176  DeclContext::decl_iterator *DI_current;
177  DeclContext::decl_iterator DE_current;
178
179  using DeclVisitor<CursorVisitor, bool>::Visit;
180  using TypeLocVisitor<CursorVisitor, bool>::Visit;
181  using StmtVisitor<CursorVisitor, bool>::Visit;
182
183  /// \brief Determine whether this particular source range comes before, comes
184  /// after, or overlaps the region of interest.
185  ///
186  /// \param R a half-open source range retrieved from the abstract syntax tree.
187  RangeComparisonResult CompareRegionOfInterest(SourceRange R);
188
189  class SetParentRAII {
190    CXCursor &Parent;
191    Decl *&StmtParent;
192    CXCursor OldParent;
193
194  public:
195    SetParentRAII(CXCursor &Parent, Decl *&StmtParent, CXCursor NewParent)
196      : Parent(Parent), StmtParent(StmtParent), OldParent(Parent)
197    {
198      Parent = NewParent;
199      if (clang_isDeclaration(Parent.kind))
200        StmtParent = getCursorDecl(Parent);
201    }
202
203    ~SetParentRAII() {
204      Parent = OldParent;
205      if (clang_isDeclaration(Parent.kind))
206        StmtParent = getCursorDecl(Parent);
207    }
208  };
209
210public:
211  CursorVisitor(ASTUnit *TU, CXCursorVisitor Visitor, CXClientData ClientData,
212                unsigned MaxPCHLevel,
213                SourceRange RegionOfInterest = SourceRange())
214    : TU(TU), Visitor(Visitor), ClientData(ClientData),
215      MaxPCHLevel(MaxPCHLevel), RegionOfInterest(RegionOfInterest),
216      DI_current(0)
217  {
218    Parent.kind = CXCursor_NoDeclFound;
219    Parent.data[0] = 0;
220    Parent.data[1] = 0;
221    Parent.data[2] = 0;
222    StmtParent = 0;
223  }
224
225  ASTUnit *getASTUnit() const { return TU; }
226
227  bool Visit(CXCursor Cursor, bool CheckedRegionOfInterest = false);
228
229  std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
230    getPreprocessedEntities();
231
232  bool VisitChildren(CXCursor Parent);
233
234  // Declaration visitors
235  bool VisitAttributes(Decl *D);
236  bool VisitBlockDecl(BlockDecl *B);
237  bool VisitCXXRecordDecl(CXXRecordDecl *D);
238  llvm::Optional<bool> shouldVisitCursor(CXCursor C);
239  bool VisitDeclContext(DeclContext *DC);
240  bool VisitTranslationUnitDecl(TranslationUnitDecl *D);
241  bool VisitTypedefDecl(TypedefDecl *D);
242  bool VisitTagDecl(TagDecl *D);
243  bool VisitClassTemplateSpecializationDecl(ClassTemplateSpecializationDecl *D);
244  bool VisitClassTemplatePartialSpecializationDecl(
245                                     ClassTemplatePartialSpecializationDecl *D);
246  bool VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
247  bool VisitEnumConstantDecl(EnumConstantDecl *D);
248  bool VisitDeclaratorDecl(DeclaratorDecl *DD);
249  bool VisitFunctionDecl(FunctionDecl *ND);
250  bool VisitFieldDecl(FieldDecl *D);
251  bool VisitVarDecl(VarDecl *);
252  bool VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D);
253  bool VisitFunctionTemplateDecl(FunctionTemplateDecl *D);
254  bool VisitClassTemplateDecl(ClassTemplateDecl *D);
255  bool VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D);
256  bool VisitObjCMethodDecl(ObjCMethodDecl *ND);
257  bool VisitObjCContainerDecl(ObjCContainerDecl *D);
258  bool VisitObjCCategoryDecl(ObjCCategoryDecl *ND);
259  bool VisitObjCProtocolDecl(ObjCProtocolDecl *PID);
260  bool VisitObjCPropertyDecl(ObjCPropertyDecl *PD);
261  bool VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
262  bool VisitObjCImplDecl(ObjCImplDecl *D);
263  bool VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
264  bool VisitObjCImplementationDecl(ObjCImplementationDecl *D);
265  // FIXME: ObjCCompatibleAliasDecl requires aliased-class locations.
266  bool VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D);
267  bool VisitObjCClassDecl(ObjCClassDecl *D);
268  bool VisitLinkageSpecDecl(LinkageSpecDecl *D);
269  bool VisitNamespaceDecl(NamespaceDecl *D);
270  bool VisitNamespaceAliasDecl(NamespaceAliasDecl *D);
271  bool VisitUsingDirectiveDecl(UsingDirectiveDecl *D);
272  bool VisitUsingDecl(UsingDecl *D);
273  bool VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D);
274  bool VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D);
275
276  // Name visitor
277  bool VisitDeclarationNameInfo(DeclarationNameInfo Name);
278  bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS, SourceRange Range);
279
280  // Template visitors
281  bool VisitTemplateParameters(const TemplateParameterList *Params);
282  bool VisitTemplateName(TemplateName Name, SourceLocation Loc);
283  bool VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL);
284
285  // Type visitors
286  bool VisitQualifiedTypeLoc(QualifiedTypeLoc TL);
287  bool VisitBuiltinTypeLoc(BuiltinTypeLoc TL);
288  bool VisitTypedefTypeLoc(TypedefTypeLoc TL);
289  bool VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL);
290  bool VisitTagTypeLoc(TagTypeLoc TL);
291  bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL);
292  bool VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL);
293  bool VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL);
294  bool VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL);
295  bool VisitPointerTypeLoc(PointerTypeLoc TL);
296  bool VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL);
297  bool VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL);
298  bool VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL);
299  bool VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL);
300  bool VisitFunctionTypeLoc(FunctionTypeLoc TL, bool SkipResultType = false);
301  bool VisitArrayTypeLoc(ArrayTypeLoc TL);
302  bool VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL);
303  // FIXME: Implement visitors here when the unimplemented TypeLocs get
304  // implemented
305  bool VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL);
306  bool VisitTypeOfTypeLoc(TypeOfTypeLoc TL);
307
308  // Statement visitors
309  bool VisitStmt(Stmt *S);
310
311  // Expression visitors
312  bool VisitOffsetOfExpr(OffsetOfExpr *E);
313  bool VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E);
314  bool VisitAddrLabelExpr(AddrLabelExpr *E);
315  bool VisitTypesCompatibleExpr(TypesCompatibleExpr *E);
316  bool VisitVAArgExpr(VAArgExpr *E);
317  bool VisitDesignatedInitExpr(DesignatedInitExpr *E);
318  bool VisitCXXTypeidExpr(CXXTypeidExpr *E);
319  bool VisitCXXUuidofExpr(CXXUuidofExpr *E);
320  bool VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
321  bool VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E);
322  bool VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E);
323  bool VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E);
324  bool VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr *E);
325  bool VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E);
326
327#define DATA_RECURSIVE_VISIT(NAME)\
328bool Visit##NAME(NAME *S) { return VisitDataRecursive(S); }
329  DATA_RECURSIVE_VISIT(BinaryOperator)
330  DATA_RECURSIVE_VISIT(BlockExpr)
331  DATA_RECURSIVE_VISIT(CompoundLiteralExpr)
332  DATA_RECURSIVE_VISIT(CXXDefaultArgExpr)
333  DATA_RECURSIVE_VISIT(CXXMemberCallExpr)
334  DATA_RECURSIVE_VISIT(CXXNewExpr)
335  DATA_RECURSIVE_VISIT(CXXOperatorCallExpr)
336  DATA_RECURSIVE_VISIT(CXXTemporaryObjectExpr)
337  DATA_RECURSIVE_VISIT(DeclRefExpr)
338  DATA_RECURSIVE_VISIT(DeclStmt)
339  DATA_RECURSIVE_VISIT(ExplicitCastExpr)
340  DATA_RECURSIVE_VISIT(DoStmt)
341  DATA_RECURSIVE_VISIT(IfStmt)
342  DATA_RECURSIVE_VISIT(InitListExpr)
343  DATA_RECURSIVE_VISIT(ForStmt)
344  DATA_RECURSIVE_VISIT(GotoStmt)
345  DATA_RECURSIVE_VISIT(MemberExpr)
346  DATA_RECURSIVE_VISIT(ObjCEncodeExpr)
347  DATA_RECURSIVE_VISIT(ObjCMessageExpr)
348  DATA_RECURSIVE_VISIT(OverloadExpr)
349  DATA_RECURSIVE_VISIT(SwitchStmt)
350  DATA_RECURSIVE_VISIT(WhileStmt)
351  DATA_RECURSIVE_VISIT(UnresolvedMemberExpr)
352
353  // Data-recursive visitor functions.
354  bool IsInRegionOfInterest(CXCursor C);
355  bool RunVisitorWorkList(VisitorWorkList &WL);
356  void EnqueueWorkList(VisitorWorkList &WL, Stmt *S);
357  bool VisitDataRecursive(Stmt *S);
358};
359
360} // end anonymous namespace
361
362static SourceRange getRawCursorExtent(CXCursor C);
363
364RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
365  return RangeCompare(TU->getSourceManager(), R, RegionOfInterest);
366}
367
368/// \brief Visit the given cursor and, if requested by the visitor,
369/// its children.
370///
371/// \param Cursor the cursor to visit.
372///
373/// \param CheckRegionOfInterest if true, then the caller already checked that
374/// this cursor is within the region of interest.
375///
376/// \returns true if the visitation should be aborted, false if it
377/// should continue.
378bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
379  if (clang_isInvalid(Cursor.kind))
380    return false;
381
382  if (clang_isDeclaration(Cursor.kind)) {
383    Decl *D = getCursorDecl(Cursor);
384    assert(D && "Invalid declaration cursor");
385    if (D->getPCHLevel() > MaxPCHLevel)
386      return false;
387
388    if (D->isImplicit())
389      return false;
390  }
391
392  // If we have a range of interest, and this cursor doesn't intersect with it,
393  // we're done.
394  if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
395    SourceRange Range = getRawCursorExtent(Cursor);
396    if (Range.isInvalid() || CompareRegionOfInterest(Range))
397      return false;
398  }
399
400  switch (Visitor(Cursor, Parent, ClientData)) {
401  case CXChildVisit_Break:
402    return true;
403
404  case CXChildVisit_Continue:
405    return false;
406
407  case CXChildVisit_Recurse:
408    return VisitChildren(Cursor);
409  }
410
411  return false;
412}
413
414std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
415CursorVisitor::getPreprocessedEntities() {
416  PreprocessingRecord &PPRec
417    = *TU->getPreprocessor().getPreprocessingRecord();
418
419  bool OnlyLocalDecls
420    = !TU->isMainFileAST() && TU->getOnlyLocalDecls();
421
422  // There is no region of interest; we have to walk everything.
423  if (RegionOfInterest.isInvalid())
424    return std::make_pair(PPRec.begin(OnlyLocalDecls),
425                          PPRec.end(OnlyLocalDecls));
426
427  // Find the file in which the region of interest lands.
428  SourceManager &SM = TU->getSourceManager();
429  std::pair<FileID, unsigned> Begin
430    = SM.getDecomposedInstantiationLoc(RegionOfInterest.getBegin());
431  std::pair<FileID, unsigned> End
432    = SM.getDecomposedInstantiationLoc(RegionOfInterest.getEnd());
433
434  // The region of interest spans files; we have to walk everything.
435  if (Begin.first != End.first)
436    return std::make_pair(PPRec.begin(OnlyLocalDecls),
437                          PPRec.end(OnlyLocalDecls));
438
439  ASTUnit::PreprocessedEntitiesByFileMap &ByFileMap
440    = TU->getPreprocessedEntitiesByFile();
441  if (ByFileMap.empty()) {
442    // Build the mapping from files to sets of preprocessed entities.
443    for (PreprocessingRecord::iterator E = PPRec.begin(OnlyLocalDecls),
444                                    EEnd = PPRec.end(OnlyLocalDecls);
445         E != EEnd; ++E) {
446      std::pair<FileID, unsigned> P
447        = SM.getDecomposedInstantiationLoc((*E)->getSourceRange().getBegin());
448      ByFileMap[P.first].push_back(*E);
449    }
450  }
451
452  return std::make_pair(ByFileMap[Begin.first].begin(),
453                        ByFileMap[Begin.first].end());
454}
455
456/// \brief Visit the children of the given cursor.
457///
458/// \returns true if the visitation should be aborted, false if it
459/// should continue.
460bool CursorVisitor::VisitChildren(CXCursor Cursor) {
461  if (clang_isReference(Cursor.kind)) {
462    // By definition, references have no children.
463    return false;
464  }
465
466  // Set the Parent field to Cursor, then back to its old value once we're
467  // done.
468  SetParentRAII SetParent(Parent, StmtParent, Cursor);
469
470  if (clang_isDeclaration(Cursor.kind)) {
471    Decl *D = getCursorDecl(Cursor);
472    assert(D && "Invalid declaration cursor");
473    return VisitAttributes(D) || Visit(D);
474  }
475
476  if (clang_isStatement(Cursor.kind))
477    return Visit(getCursorStmt(Cursor));
478  if (clang_isExpression(Cursor.kind))
479    return Visit(getCursorExpr(Cursor));
480
481  if (clang_isTranslationUnit(Cursor.kind)) {
482    ASTUnit *CXXUnit = getCursorASTUnit(Cursor);
483    if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
484        RegionOfInterest.isInvalid()) {
485      for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(),
486                                    TLEnd = CXXUnit->top_level_end();
487           TL != TLEnd; ++TL) {
488        if (Visit(MakeCXCursor(*TL, CXXUnit), true))
489          return true;
490      }
491    } else if (VisitDeclContext(
492                            CXXUnit->getASTContext().getTranslationUnitDecl()))
493      return true;
494
495    // Walk the preprocessing record.
496    if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
497      // FIXME: Once we have the ability to deserialize a preprocessing record,
498      // do so.
499      PreprocessingRecord::iterator E, EEnd;
500      for (llvm::tie(E, EEnd) = getPreprocessedEntities(); E != EEnd; ++E) {
501        if (MacroInstantiation *MI = dyn_cast<MacroInstantiation>(*E)) {
502          if (Visit(MakeMacroInstantiationCursor(MI, CXXUnit)))
503            return true;
504
505          continue;
506        }
507
508        if (MacroDefinition *MD = dyn_cast<MacroDefinition>(*E)) {
509          if (Visit(MakeMacroDefinitionCursor(MD, CXXUnit)))
510            return true;
511
512          continue;
513        }
514
515        if (InclusionDirective *ID = dyn_cast<InclusionDirective>(*E)) {
516          if (Visit(MakeInclusionDirectiveCursor(ID, CXXUnit)))
517            return true;
518
519          continue;
520        }
521      }
522    }
523    return false;
524  }
525
526  // Nothing to visit at the moment.
527  return false;
528}
529
530bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
531  if (Visit(B->getSignatureAsWritten()->getTypeLoc()))
532    return true;
533
534  if (Stmt *Body = B->getBody())
535    return Visit(MakeCXCursor(Body, StmtParent, TU));
536
537  return false;
538}
539
540llvm::Optional<bool> CursorVisitor::shouldVisitCursor(CXCursor Cursor) {
541  if (RegionOfInterest.isValid()) {
542    SourceRange Range = getRawCursorExtent(Cursor);
543    if (Range.isInvalid())
544      return llvm::Optional<bool>();
545
546    switch (CompareRegionOfInterest(Range)) {
547    case RangeBefore:
548      // This declaration comes before the region of interest; skip it.
549      return llvm::Optional<bool>();
550
551    case RangeAfter:
552      // This declaration comes after the region of interest; we're done.
553      return false;
554
555    case RangeOverlap:
556      // This declaration overlaps the region of interest; visit it.
557      break;
558    }
559  }
560  return true;
561}
562
563bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
564  DeclContext::decl_iterator I = DC->decls_begin(), E = DC->decls_end();
565
566  // FIXME: Eventually remove.  This part of a hack to support proper
567  // iteration over all Decls contained lexically within an ObjC container.
568  SaveAndRestore<DeclContext::decl_iterator*> DI_saved(DI_current, &I);
569  SaveAndRestore<DeclContext::decl_iterator> DE_saved(DE_current, E);
570
571  for ( ; I != E; ++I) {
572    Decl *D = *I;
573    if (D->getLexicalDeclContext() != DC)
574      continue;
575    CXCursor Cursor = MakeCXCursor(D, TU);
576    const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
577    if (!V.hasValue())
578      continue;
579    if (!V.getValue())
580      return false;
581    if (Visit(Cursor, true))
582      return true;
583  }
584  return false;
585}
586
587bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
588  llvm_unreachable("Translation units are visited directly by Visit()");
589  return false;
590}
591
592bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
593  if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
594    return Visit(TSInfo->getTypeLoc());
595
596  return false;
597}
598
599bool CursorVisitor::VisitTagDecl(TagDecl *D) {
600  return VisitDeclContext(D);
601}
602
603bool CursorVisitor::VisitClassTemplateSpecializationDecl(
604                                          ClassTemplateSpecializationDecl *D) {
605  bool ShouldVisitBody = false;
606  switch (D->getSpecializationKind()) {
607  case TSK_Undeclared:
608  case TSK_ImplicitInstantiation:
609    // Nothing to visit
610    return false;
611
612  case TSK_ExplicitInstantiationDeclaration:
613  case TSK_ExplicitInstantiationDefinition:
614    break;
615
616  case TSK_ExplicitSpecialization:
617    ShouldVisitBody = true;
618    break;
619  }
620
621  // Visit the template arguments used in the specialization.
622  if (TypeSourceInfo *SpecType = D->getTypeAsWritten()) {
623    TypeLoc TL = SpecType->getTypeLoc();
624    if (TemplateSpecializationTypeLoc *TSTLoc
625          = dyn_cast<TemplateSpecializationTypeLoc>(&TL)) {
626      for (unsigned I = 0, N = TSTLoc->getNumArgs(); I != N; ++I)
627        if (VisitTemplateArgumentLoc(TSTLoc->getArgLoc(I)))
628          return true;
629    }
630  }
631
632  if (ShouldVisitBody && VisitCXXRecordDecl(D))
633    return true;
634
635  return false;
636}
637
638bool CursorVisitor::VisitClassTemplatePartialSpecializationDecl(
639                                   ClassTemplatePartialSpecializationDecl *D) {
640  // FIXME: Visit the "outer" template parameter lists on the TagDecl
641  // before visiting these template parameters.
642  if (VisitTemplateParameters(D->getTemplateParameters()))
643    return true;
644
645  // Visit the partial specialization arguments.
646  const TemplateArgumentLoc *TemplateArgs = D->getTemplateArgsAsWritten();
647  for (unsigned I = 0, N = D->getNumTemplateArgsAsWritten(); I != N; ++I)
648    if (VisitTemplateArgumentLoc(TemplateArgs[I]))
649      return true;
650
651  return VisitCXXRecordDecl(D);
652}
653
654bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
655  // Visit the default argument.
656  if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
657    if (TypeSourceInfo *DefArg = D->getDefaultArgumentInfo())
658      if (Visit(DefArg->getTypeLoc()))
659        return true;
660
661  return false;
662}
663
664bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
665  if (Expr *Init = D->getInitExpr())
666    return Visit(MakeCXCursor(Init, StmtParent, TU));
667  return false;
668}
669
670bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
671  if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
672    if (Visit(TSInfo->getTypeLoc()))
673      return true;
674
675  return false;
676}
677
678/// \brief Compare two base or member initializers based on their source order.
679static int CompareCXXBaseOrMemberInitializers(const void* Xp, const void *Yp) {
680  CXXBaseOrMemberInitializer const * const *X
681    = static_cast<CXXBaseOrMemberInitializer const * const *>(Xp);
682  CXXBaseOrMemberInitializer const * const *Y
683    = static_cast<CXXBaseOrMemberInitializer const * const *>(Yp);
684
685  if ((*X)->getSourceOrder() < (*Y)->getSourceOrder())
686    return -1;
687  else if ((*X)->getSourceOrder() > (*Y)->getSourceOrder())
688    return 1;
689  else
690    return 0;
691}
692
693bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
694  if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) {
695    // Visit the function declaration's syntactic components in the order
696    // written. This requires a bit of work.
697    TypeLoc TL = TSInfo->getTypeLoc();
698    FunctionTypeLoc *FTL = dyn_cast<FunctionTypeLoc>(&TL);
699
700    // If we have a function declared directly (without the use of a typedef),
701    // visit just the return type. Otherwise, just visit the function's type
702    // now.
703    if ((FTL && !isa<CXXConversionDecl>(ND) && Visit(FTL->getResultLoc())) ||
704        (!FTL && Visit(TL)))
705      return true;
706
707    // Visit the nested-name-specifier, if present.
708    if (NestedNameSpecifier *Qualifier = ND->getQualifier())
709      if (VisitNestedNameSpecifier(Qualifier, ND->getQualifierRange()))
710        return true;
711
712    // Visit the declaration name.
713    if (VisitDeclarationNameInfo(ND->getNameInfo()))
714      return true;
715
716    // FIXME: Visit explicitly-specified template arguments!
717
718    // Visit the function parameters, if we have a function type.
719    if (FTL && VisitFunctionTypeLoc(*FTL, true))
720      return true;
721
722    // FIXME: Attributes?
723  }
724
725  if (ND->isThisDeclarationADefinition()) {
726    if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ND)) {
727      // Find the initializers that were written in the source.
728      llvm::SmallVector<CXXBaseOrMemberInitializer *, 4> WrittenInits;
729      for (CXXConstructorDecl::init_iterator I = Constructor->init_begin(),
730                                          IEnd = Constructor->init_end();
731           I != IEnd; ++I) {
732        if (!(*I)->isWritten())
733          continue;
734
735        WrittenInits.push_back(*I);
736      }
737
738      // Sort the initializers in source order
739      llvm::array_pod_sort(WrittenInits.begin(), WrittenInits.end(),
740                           &CompareCXXBaseOrMemberInitializers);
741
742      // Visit the initializers in source order
743      for (unsigned I = 0, N = WrittenInits.size(); I != N; ++I) {
744        CXXBaseOrMemberInitializer *Init = WrittenInits[I];
745        if (Init->isMemberInitializer()) {
746          if (Visit(MakeCursorMemberRef(Init->getMember(),
747                                        Init->getMemberLocation(), TU)))
748            return true;
749        } else if (TypeSourceInfo *BaseInfo = Init->getBaseClassInfo()) {
750          if (Visit(BaseInfo->getTypeLoc()))
751            return true;
752        }
753
754        // Visit the initializer value.
755        if (Expr *Initializer = Init->getInit())
756          if (Visit(MakeCXCursor(Initializer, ND, TU)))
757            return true;
758      }
759    }
760
761    if (Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
762      return true;
763  }
764
765  return false;
766}
767
768bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
769  if (VisitDeclaratorDecl(D))
770    return true;
771
772  if (Expr *BitWidth = D->getBitWidth())
773    return Visit(MakeCXCursor(BitWidth, StmtParent, TU));
774
775  return false;
776}
777
778bool CursorVisitor::VisitVarDecl(VarDecl *D) {
779  if (VisitDeclaratorDecl(D))
780    return true;
781
782  if (Expr *Init = D->getInit())
783    return Visit(MakeCXCursor(Init, StmtParent, TU));
784
785  return false;
786}
787
788bool CursorVisitor::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
789  if (VisitDeclaratorDecl(D))
790    return true;
791
792  if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
793    if (Expr *DefArg = D->getDefaultArgument())
794      return Visit(MakeCXCursor(DefArg, StmtParent, TU));
795
796  return false;
797}
798
799bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
800  // FIXME: Visit the "outer" template parameter lists on the FunctionDecl
801  // before visiting these template parameters.
802  if (VisitTemplateParameters(D->getTemplateParameters()))
803    return true;
804
805  return VisitFunctionDecl(D->getTemplatedDecl());
806}
807
808bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) {
809  // FIXME: Visit the "outer" template parameter lists on the TagDecl
810  // before visiting these template parameters.
811  if (VisitTemplateParameters(D->getTemplateParameters()))
812    return true;
813
814  return VisitCXXRecordDecl(D->getTemplatedDecl());
815}
816
817bool CursorVisitor::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
818  if (VisitTemplateParameters(D->getTemplateParameters()))
819    return true;
820
821  if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited() &&
822      VisitTemplateArgumentLoc(D->getDefaultArgument()))
823    return true;
824
825  return false;
826}
827
828bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
829  if (TypeSourceInfo *TSInfo = ND->getResultTypeSourceInfo())
830    if (Visit(TSInfo->getTypeLoc()))
831      return true;
832
833  for (ObjCMethodDecl::param_iterator P = ND->param_begin(),
834       PEnd = ND->param_end();
835       P != PEnd; ++P) {
836    if (Visit(MakeCXCursor(*P, TU)))
837      return true;
838  }
839
840  if (ND->isThisDeclarationADefinition() &&
841      Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
842    return true;
843
844  return false;
845}
846
847namespace {
848  struct ContainerDeclsSort {
849    SourceManager &SM;
850    ContainerDeclsSort(SourceManager &sm) : SM(sm) {}
851    bool operator()(Decl *A, Decl *B) {
852      SourceLocation L_A = A->getLocStart();
853      SourceLocation L_B = B->getLocStart();
854      assert(L_A.isValid() && L_B.isValid());
855      return SM.isBeforeInTranslationUnit(L_A, L_B);
856    }
857  };
858}
859
860bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
861  // FIXME: Eventually convert back to just 'VisitDeclContext()'.  Essentially
862  // an @implementation can lexically contain Decls that are not properly
863  // nested in the AST.  When we identify such cases, we need to retrofit
864  // this nesting here.
865  if (!DI_current)
866    return VisitDeclContext(D);
867
868  // Scan the Decls that immediately come after the container
869  // in the current DeclContext.  If any fall within the
870  // container's lexical region, stash them into a vector
871  // for later processing.
872  llvm::SmallVector<Decl *, 24> DeclsInContainer;
873  SourceLocation EndLoc = D->getSourceRange().getEnd();
874  SourceManager &SM = TU->getSourceManager();
875  if (EndLoc.isValid()) {
876    DeclContext::decl_iterator next = *DI_current;
877    while (++next != DE_current) {
878      Decl *D_next = *next;
879      if (!D_next)
880        break;
881      SourceLocation L = D_next->getLocStart();
882      if (!L.isValid())
883        break;
884      if (SM.isBeforeInTranslationUnit(L, EndLoc)) {
885        *DI_current = next;
886        DeclsInContainer.push_back(D_next);
887        continue;
888      }
889      break;
890    }
891  }
892
893  // The common case.
894  if (DeclsInContainer.empty())
895    return VisitDeclContext(D);
896
897  // Get all the Decls in the DeclContext, and sort them with the
898  // additional ones we've collected.  Then visit them.
899  for (DeclContext::decl_iterator I = D->decls_begin(), E = D->decls_end();
900       I!=E; ++I) {
901    Decl *subDecl = *I;
902    if (!subDecl || subDecl->getLexicalDeclContext() != D ||
903        subDecl->getLocStart().isInvalid())
904      continue;
905    DeclsInContainer.push_back(subDecl);
906  }
907
908  // Now sort the Decls so that they appear in lexical order.
909  std::sort(DeclsInContainer.begin(), DeclsInContainer.end(),
910            ContainerDeclsSort(SM));
911
912  // Now visit the decls.
913  for (llvm::SmallVectorImpl<Decl*>::iterator I = DeclsInContainer.begin(),
914         E = DeclsInContainer.end(); I != E; ++I) {
915    CXCursor Cursor = MakeCXCursor(*I, TU);
916    const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
917    if (!V.hasValue())
918      continue;
919    if (!V.getValue())
920      return false;
921    if (Visit(Cursor, true))
922      return true;
923  }
924  return false;
925}
926
927bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
928  if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
929                                   TU)))
930    return true;
931
932  ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
933  for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
934         E = ND->protocol_end(); I != E; ++I, ++PL)
935    if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
936      return true;
937
938  return VisitObjCContainerDecl(ND);
939}
940
941bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
942  ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
943  for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
944       E = PID->protocol_end(); I != E; ++I, ++PL)
945    if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
946      return true;
947
948  return VisitObjCContainerDecl(PID);
949}
950
951bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
952  if (PD->getTypeSourceInfo() && Visit(PD->getTypeSourceInfo()->getTypeLoc()))
953    return true;
954
955  // FIXME: This implements a workaround with @property declarations also being
956  // installed in the DeclContext for the @interface.  Eventually this code
957  // should be removed.
958  ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
959  if (!CDecl || !CDecl->IsClassExtension())
960    return false;
961
962  ObjCInterfaceDecl *ID = CDecl->getClassInterface();
963  if (!ID)
964    return false;
965
966  IdentifierInfo *PropertyId = PD->getIdentifier();
967  ObjCPropertyDecl *prevDecl =
968    ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId);
969
970  if (!prevDecl)
971    return false;
972
973  // Visit synthesized methods since they will be skipped when visiting
974  // the @interface.
975  if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
976    if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
977      if (Visit(MakeCXCursor(MD, TU)))
978        return true;
979
980  if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
981    if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
982      if (Visit(MakeCXCursor(MD, TU)))
983        return true;
984
985  return false;
986}
987
988bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
989  // Issue callbacks for super class.
990  if (D->getSuperClass() &&
991      Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
992                                        D->getSuperClassLoc(),
993                                        TU)))
994    return true;
995
996  ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
997  for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
998         E = D->protocol_end(); I != E; ++I, ++PL)
999    if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
1000      return true;
1001
1002  return VisitObjCContainerDecl(D);
1003}
1004
1005bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
1006  return VisitObjCContainerDecl(D);
1007}
1008
1009bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
1010  // 'ID' could be null when dealing with invalid code.
1011  if (ObjCInterfaceDecl *ID = D->getClassInterface())
1012    if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
1013      return true;
1014
1015  return VisitObjCImplDecl(D);
1016}
1017
1018bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
1019#if 0
1020  // Issue callbacks for super class.
1021  // FIXME: No source location information!
1022  if (D->getSuperClass() &&
1023      Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
1024                                        D->getSuperClassLoc(),
1025                                        TU)))
1026    return true;
1027#endif
1028
1029  return VisitObjCImplDecl(D);
1030}
1031
1032bool CursorVisitor::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D) {
1033  ObjCForwardProtocolDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1034  for (ObjCForwardProtocolDecl::protocol_iterator I = D->protocol_begin(),
1035                                                  E = D->protocol_end();
1036       I != E; ++I, ++PL)
1037    if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
1038      return true;
1039
1040  return false;
1041}
1042
1043bool CursorVisitor::VisitObjCClassDecl(ObjCClassDecl *D) {
1044  for (ObjCClassDecl::iterator C = D->begin(), CEnd = D->end(); C != CEnd; ++C)
1045    if (Visit(MakeCursorObjCClassRef(C->getInterface(), C->getLocation(), TU)))
1046      return true;
1047
1048  return false;
1049}
1050
1051bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
1052  return VisitDeclContext(D);
1053}
1054
1055bool CursorVisitor::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
1056  // Visit nested-name-specifier.
1057  if (NestedNameSpecifier *Qualifier = D->getQualifier())
1058    if (VisitNestedNameSpecifier(Qualifier, D->getQualifierRange()))
1059      return true;
1060
1061  return Visit(MakeCursorNamespaceRef(D->getAliasedNamespace(),
1062                                      D->getTargetNameLoc(), TU));
1063}
1064
1065bool CursorVisitor::VisitUsingDecl(UsingDecl *D) {
1066  // Visit nested-name-specifier.
1067  if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameDecl())
1068    if (VisitNestedNameSpecifier(Qualifier, D->getNestedNameRange()))
1069      return true;
1070
1071  if (Visit(MakeCursorOverloadedDeclRef(D, D->getLocation(), TU)))
1072    return true;
1073
1074  return VisitDeclarationNameInfo(D->getNameInfo());
1075}
1076
1077bool CursorVisitor::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
1078  // Visit nested-name-specifier.
1079  if (NestedNameSpecifier *Qualifier = D->getQualifier())
1080    if (VisitNestedNameSpecifier(Qualifier, D->getQualifierRange()))
1081      return true;
1082
1083  return Visit(MakeCursorNamespaceRef(D->getNominatedNamespaceAsWritten(),
1084                                      D->getIdentLocation(), TU));
1085}
1086
1087bool CursorVisitor::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
1088  // Visit nested-name-specifier.
1089  if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameSpecifier())
1090    if (VisitNestedNameSpecifier(Qualifier, D->getTargetNestedNameRange()))
1091      return true;
1092
1093  return VisitDeclarationNameInfo(D->getNameInfo());
1094}
1095
1096bool CursorVisitor::VisitUnresolvedUsingTypenameDecl(
1097                                               UnresolvedUsingTypenameDecl *D) {
1098  // Visit nested-name-specifier.
1099  if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameSpecifier())
1100    if (VisitNestedNameSpecifier(Qualifier, D->getTargetNestedNameRange()))
1101      return true;
1102
1103  return false;
1104}
1105
1106bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) {
1107  switch (Name.getName().getNameKind()) {
1108  case clang::DeclarationName::Identifier:
1109  case clang::DeclarationName::CXXLiteralOperatorName:
1110  case clang::DeclarationName::CXXOperatorName:
1111  case clang::DeclarationName::CXXUsingDirective:
1112    return false;
1113
1114  case clang::DeclarationName::CXXConstructorName:
1115  case clang::DeclarationName::CXXDestructorName:
1116  case clang::DeclarationName::CXXConversionFunctionName:
1117    if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo())
1118      return Visit(TSInfo->getTypeLoc());
1119    return false;
1120
1121  case clang::DeclarationName::ObjCZeroArgSelector:
1122  case clang::DeclarationName::ObjCOneArgSelector:
1123  case clang::DeclarationName::ObjCMultiArgSelector:
1124    // FIXME: Per-identifier location info?
1125    return false;
1126  }
1127
1128  return false;
1129}
1130
1131bool CursorVisitor::VisitNestedNameSpecifier(NestedNameSpecifier *NNS,
1132                                             SourceRange Range) {
1133  // FIXME: This whole routine is a hack to work around the lack of proper
1134  // source information in nested-name-specifiers (PR5791). Since we do have
1135  // a beginning source location, we can visit the first component of the
1136  // nested-name-specifier, if it's a single-token component.
1137  if (!NNS)
1138    return false;
1139
1140  // Get the first component in the nested-name-specifier.
1141  while (NestedNameSpecifier *Prefix = NNS->getPrefix())
1142    NNS = Prefix;
1143
1144  switch (NNS->getKind()) {
1145  case NestedNameSpecifier::Namespace:
1146    // FIXME: The token at this source location might actually have been a
1147    // namespace alias, but we don't model that. Lame!
1148    return Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(), Range.getBegin(),
1149                                        TU));
1150
1151  case NestedNameSpecifier::TypeSpec: {
1152    // If the type has a form where we know that the beginning of the source
1153    // range matches up with a reference cursor. Visit the appropriate reference
1154    // cursor.
1155    Type *T = NNS->getAsType();
1156    if (const TypedefType *Typedef = dyn_cast<TypedefType>(T))
1157      return Visit(MakeCursorTypeRef(Typedef->getDecl(), Range.getBegin(), TU));
1158    if (const TagType *Tag = dyn_cast<TagType>(T))
1159      return Visit(MakeCursorTypeRef(Tag->getDecl(), Range.getBegin(), TU));
1160    if (const TemplateSpecializationType *TST
1161                                      = dyn_cast<TemplateSpecializationType>(T))
1162      return VisitTemplateName(TST->getTemplateName(), Range.getBegin());
1163    break;
1164  }
1165
1166  case NestedNameSpecifier::TypeSpecWithTemplate:
1167  case NestedNameSpecifier::Global:
1168  case NestedNameSpecifier::Identifier:
1169    break;
1170  }
1171
1172  return false;
1173}
1174
1175bool CursorVisitor::VisitTemplateParameters(
1176                                          const TemplateParameterList *Params) {
1177  if (!Params)
1178    return false;
1179
1180  for (TemplateParameterList::const_iterator P = Params->begin(),
1181                                          PEnd = Params->end();
1182       P != PEnd; ++P) {
1183    if (Visit(MakeCXCursor(*P, TU)))
1184      return true;
1185  }
1186
1187  return false;
1188}
1189
1190bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) {
1191  switch (Name.getKind()) {
1192  case TemplateName::Template:
1193    return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU));
1194
1195  case TemplateName::OverloadedTemplate:
1196    // Visit the overloaded template set.
1197    if (Visit(MakeCursorOverloadedDeclRef(Name, Loc, TU)))
1198      return true;
1199
1200    return false;
1201
1202  case TemplateName::DependentTemplate:
1203    // FIXME: Visit nested-name-specifier.
1204    return false;
1205
1206  case TemplateName::QualifiedTemplate:
1207    // FIXME: Visit nested-name-specifier.
1208    return Visit(MakeCursorTemplateRef(
1209                                  Name.getAsQualifiedTemplateName()->getDecl(),
1210                                       Loc, TU));
1211  }
1212
1213  return false;
1214}
1215
1216bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) {
1217  switch (TAL.getArgument().getKind()) {
1218  case TemplateArgument::Null:
1219  case TemplateArgument::Integral:
1220    return false;
1221
1222  case TemplateArgument::Pack:
1223    // FIXME: Implement when variadic templates come along.
1224    return false;
1225
1226  case TemplateArgument::Type:
1227    if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo())
1228      return Visit(TSInfo->getTypeLoc());
1229    return false;
1230
1231  case TemplateArgument::Declaration:
1232    if (Expr *E = TAL.getSourceDeclExpression())
1233      return Visit(MakeCXCursor(E, StmtParent, TU));
1234    return false;
1235
1236  case TemplateArgument::Expression:
1237    if (Expr *E = TAL.getSourceExpression())
1238      return Visit(MakeCXCursor(E, StmtParent, TU));
1239    return false;
1240
1241  case TemplateArgument::Template:
1242    return VisitTemplateName(TAL.getArgument().getAsTemplate(),
1243                             TAL.getTemplateNameLoc());
1244  }
1245
1246  return false;
1247}
1248
1249bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1250  return VisitDeclContext(D);
1251}
1252
1253bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1254  return Visit(TL.getUnqualifiedLoc());
1255}
1256
1257bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
1258  ASTContext &Context = TU->getASTContext();
1259
1260  // Some builtin types (such as Objective-C's "id", "sel", and
1261  // "Class") have associated declarations. Create cursors for those.
1262  QualType VisitType;
1263  switch (TL.getType()->getAs<BuiltinType>()->getKind()) {
1264  case BuiltinType::Void:
1265  case BuiltinType::Bool:
1266  case BuiltinType::Char_U:
1267  case BuiltinType::UChar:
1268  case BuiltinType::Char16:
1269  case BuiltinType::Char32:
1270  case BuiltinType::UShort:
1271  case BuiltinType::UInt:
1272  case BuiltinType::ULong:
1273  case BuiltinType::ULongLong:
1274  case BuiltinType::UInt128:
1275  case BuiltinType::Char_S:
1276  case BuiltinType::SChar:
1277  case BuiltinType::WChar:
1278  case BuiltinType::Short:
1279  case BuiltinType::Int:
1280  case BuiltinType::Long:
1281  case BuiltinType::LongLong:
1282  case BuiltinType::Int128:
1283  case BuiltinType::Float:
1284  case BuiltinType::Double:
1285  case BuiltinType::LongDouble:
1286  case BuiltinType::NullPtr:
1287  case BuiltinType::Overload:
1288  case BuiltinType::Dependent:
1289    break;
1290
1291  case BuiltinType::UndeducedAuto: // FIXME: Deserves a cursor?
1292    break;
1293
1294  case BuiltinType::ObjCId:
1295    VisitType = Context.getObjCIdType();
1296    break;
1297
1298  case BuiltinType::ObjCClass:
1299    VisitType = Context.getObjCClassType();
1300    break;
1301
1302  case BuiltinType::ObjCSel:
1303    VisitType = Context.getObjCSelType();
1304    break;
1305  }
1306
1307  if (!VisitType.isNull()) {
1308    if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
1309      return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
1310                                     TU));
1311  }
1312
1313  return false;
1314}
1315
1316bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
1317  return Visit(MakeCursorTypeRef(TL.getTypedefDecl(), TL.getNameLoc(), TU));
1318}
1319
1320bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
1321  return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1322}
1323
1324bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
1325  return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1326}
1327
1328bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
1329  // FIXME: We can't visit the template type parameter, because there's
1330  // no context information with which we can match up the depth/index in the
1331  // type to the appropriate
1332  return false;
1333}
1334
1335bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
1336  if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
1337    return true;
1338
1339  return false;
1340}
1341
1342bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
1343  if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
1344    return true;
1345
1346  for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1347    if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1348                                        TU)))
1349      return true;
1350  }
1351
1352  return false;
1353}
1354
1355bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
1356  return Visit(TL.getPointeeLoc());
1357}
1358
1359bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
1360  return Visit(TL.getPointeeLoc());
1361}
1362
1363bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1364  return Visit(TL.getPointeeLoc());
1365}
1366
1367bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1368  return Visit(TL.getPointeeLoc());
1369}
1370
1371bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
1372  return Visit(TL.getPointeeLoc());
1373}
1374
1375bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
1376  return Visit(TL.getPointeeLoc());
1377}
1378
1379bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL,
1380                                         bool SkipResultType) {
1381  if (!SkipResultType && Visit(TL.getResultLoc()))
1382    return true;
1383
1384  for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1385    if (Decl *D = TL.getArg(I))
1386      if (Visit(MakeCXCursor(D, TU)))
1387        return true;
1388
1389  return false;
1390}
1391
1392bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
1393  if (Visit(TL.getElementLoc()))
1394    return true;
1395
1396  if (Expr *Size = TL.getSizeExpr())
1397    return Visit(MakeCXCursor(Size, StmtParent, TU));
1398
1399  return false;
1400}
1401
1402bool CursorVisitor::VisitTemplateSpecializationTypeLoc(
1403                                             TemplateSpecializationTypeLoc TL) {
1404  // Visit the template name.
1405  if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1406                        TL.getTemplateNameLoc()))
1407    return true;
1408
1409  // Visit the template arguments.
1410  for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1411    if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1412      return true;
1413
1414  return false;
1415}
1416
1417bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
1418  return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
1419}
1420
1421bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
1422  if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1423    return Visit(TSInfo->getTypeLoc());
1424
1425  return false;
1426}
1427
1428bool CursorVisitor::VisitStmt(Stmt *S) {
1429  for (Stmt::child_iterator Child = S->child_begin(), ChildEnd = S->child_end();
1430       Child != ChildEnd; ++Child) {
1431    if (Stmt *C = *Child)
1432      if (Visit(MakeCXCursor(C, StmtParent, TU)))
1433        return true;
1434  }
1435
1436  return false;
1437}
1438
1439bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
1440  if (D->isDefinition()) {
1441    for (CXXRecordDecl::base_class_iterator I = D->bases_begin(),
1442         E = D->bases_end(); I != E; ++I) {
1443      if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(I, TU)))
1444        return true;
1445    }
1446  }
1447
1448  return VisitTagDecl(D);
1449}
1450
1451bool CursorVisitor::VisitOffsetOfExpr(OffsetOfExpr *E) {
1452  // Visit the type into which we're computing an offset.
1453  if (Visit(E->getTypeSourceInfo()->getTypeLoc()))
1454    return true;
1455
1456  // Visit the components of the offsetof expression.
1457  for (unsigned I = 0, N = E->getNumComponents(); I != N; ++I) {
1458    typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
1459    const OffsetOfNode &Node = E->getComponent(I);
1460    switch (Node.getKind()) {
1461    case OffsetOfNode::Array:
1462      if (Visit(MakeCXCursor(E->getIndexExpr(Node.getArrayExprIndex()),
1463                             StmtParent, TU)))
1464        return true;
1465      break;
1466
1467    case OffsetOfNode::Field:
1468      if (Visit(MakeCursorMemberRef(Node.getField(), Node.getRange().getEnd(),
1469                                    TU)))
1470        return true;
1471      break;
1472
1473    case OffsetOfNode::Identifier:
1474    case OffsetOfNode::Base:
1475      continue;
1476    }
1477  }
1478
1479  return false;
1480}
1481
1482bool CursorVisitor::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E) {
1483  if (E->isArgumentType()) {
1484    if (TypeSourceInfo *TSInfo = E->getArgumentTypeInfo())
1485      return Visit(TSInfo->getTypeLoc());
1486
1487    return false;
1488  }
1489
1490  return VisitExpr(E);
1491}
1492
1493bool CursorVisitor::VisitAddrLabelExpr(AddrLabelExpr *E) {
1494  return Visit(MakeCursorLabelRef(E->getLabel(), E->getLabelLoc(), TU));
1495}
1496
1497bool CursorVisitor::VisitTypesCompatibleExpr(TypesCompatibleExpr *E) {
1498  return Visit(E->getArgTInfo1()->getTypeLoc()) ||
1499         Visit(E->getArgTInfo2()->getTypeLoc());
1500}
1501
1502bool CursorVisitor::VisitVAArgExpr(VAArgExpr *E) {
1503  if (Visit(E->getWrittenTypeInfo()->getTypeLoc()))
1504    return true;
1505
1506  return Visit(MakeCXCursor(E->getSubExpr(), StmtParent, TU));
1507}
1508
1509bool CursorVisitor::VisitDesignatedInitExpr(DesignatedInitExpr *E) {
1510  // Visit the designators.
1511  typedef DesignatedInitExpr::Designator Designator;
1512  for (DesignatedInitExpr::designators_iterator D = E->designators_begin(),
1513                                             DEnd = E->designators_end();
1514       D != DEnd; ++D) {
1515    if (D->isFieldDesignator()) {
1516      if (FieldDecl *Field = D->getField())
1517        if (Visit(MakeCursorMemberRef(Field, D->getFieldLoc(), TU)))
1518          return true;
1519
1520      continue;
1521    }
1522
1523    if (D->isArrayDesignator()) {
1524      if (Visit(MakeCXCursor(E->getArrayIndex(*D), StmtParent, TU)))
1525        return true;
1526
1527      continue;
1528    }
1529
1530    assert(D->isArrayRangeDesignator() && "Unknown designator kind");
1531    if (Visit(MakeCXCursor(E->getArrayRangeStart(*D), StmtParent, TU)) ||
1532        Visit(MakeCXCursor(E->getArrayRangeEnd(*D), StmtParent, TU)))
1533      return true;
1534  }
1535
1536  // Visit the initializer value itself.
1537  return Visit(MakeCXCursor(E->getInit(), StmtParent, TU));
1538}
1539
1540bool CursorVisitor::VisitCXXTypeidExpr(CXXTypeidExpr *E) {
1541  if (E->isTypeOperand()) {
1542    if (TypeSourceInfo *TSInfo = E->getTypeOperandSourceInfo())
1543      return Visit(TSInfo->getTypeLoc());
1544
1545    return false;
1546  }
1547
1548  return VisitExpr(E);
1549}
1550
1551bool CursorVisitor::VisitCXXUuidofExpr(CXXUuidofExpr *E) {
1552  if (E->isTypeOperand()) {
1553    if (TypeSourceInfo *TSInfo = E->getTypeOperandSourceInfo())
1554      return Visit(TSInfo->getTypeLoc());
1555
1556    return false;
1557  }
1558
1559  return VisitExpr(E);
1560}
1561
1562bool CursorVisitor::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
1563  if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
1564    return Visit(TSInfo->getTypeLoc());
1565
1566  return false;
1567}
1568
1569bool CursorVisitor::VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E) {
1570  // Visit base expression.
1571  if (Visit(MakeCXCursor(E->getBase(), StmtParent, TU)))
1572    return true;
1573
1574  // Visit the nested-name-specifier.
1575  if (NestedNameSpecifier *Qualifier = E->getQualifier())
1576    if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1577      return true;
1578
1579  // Visit the scope type that looks disturbingly like the nested-name-specifier
1580  // but isn't.
1581  if (TypeSourceInfo *TSInfo = E->getScopeTypeInfo())
1582    if (Visit(TSInfo->getTypeLoc()))
1583      return true;
1584
1585  // Visit the name of the type being destroyed.
1586  if (TypeSourceInfo *TSInfo = E->getDestroyedTypeInfo())
1587    if (Visit(TSInfo->getTypeLoc()))
1588      return true;
1589
1590  return false;
1591}
1592
1593bool CursorVisitor::VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E) {
1594  return Visit(E->getQueriedTypeSourceInfo()->getTypeLoc());
1595}
1596
1597bool CursorVisitor::VisitDependentScopeDeclRefExpr(
1598                                                DependentScopeDeclRefExpr *E) {
1599  // Visit the nested-name-specifier.
1600  if (NestedNameSpecifier *Qualifier = E->getQualifier())
1601    if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1602      return true;
1603
1604  // Visit the declaration name.
1605  if (VisitDeclarationNameInfo(E->getNameInfo()))
1606    return true;
1607
1608  // Visit the explicitly-specified template arguments.
1609  if (const ExplicitTemplateArgumentList *ArgList
1610      = E->getOptionalExplicitTemplateArgs()) {
1611    for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
1612         *ArgEnd = Arg + ArgList->NumTemplateArgs;
1613         Arg != ArgEnd; ++Arg) {
1614      if (VisitTemplateArgumentLoc(*Arg))
1615        return true;
1616    }
1617  }
1618
1619  return false;
1620}
1621
1622bool CursorVisitor::VisitCXXUnresolvedConstructExpr(
1623                                                CXXUnresolvedConstructExpr *E) {
1624  if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
1625    if (Visit(TSInfo->getTypeLoc()))
1626      return true;
1627
1628  return VisitExpr(E);
1629}
1630
1631bool CursorVisitor::VisitCXXDependentScopeMemberExpr(
1632                                              CXXDependentScopeMemberExpr *E) {
1633  // Visit the base expression, if there is one.
1634  if (!E->isImplicitAccess() &&
1635      Visit(MakeCXCursor(E->getBase(), StmtParent, TU)))
1636    return true;
1637
1638  // Visit the nested-name-specifier.
1639  if (NestedNameSpecifier *Qualifier = E->getQualifier())
1640    if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1641      return true;
1642
1643  // Visit the declaration name.
1644  if (VisitDeclarationNameInfo(E->getMemberNameInfo()))
1645    return true;
1646
1647  // Visit the explicitly-specified template arguments.
1648  if (const ExplicitTemplateArgumentList *ArgList
1649      = E->getOptionalExplicitTemplateArgs()) {
1650    for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
1651         *ArgEnd = Arg + ArgList->NumTemplateArgs;
1652         Arg != ArgEnd; ++Arg) {
1653      if (VisitTemplateArgumentLoc(*Arg))
1654        return true;
1655    }
1656  }
1657
1658  return false;
1659}
1660
1661bool CursorVisitor::VisitAttributes(Decl *D) {
1662  for (AttrVec::const_iterator i = D->attr_begin(), e = D->attr_end();
1663       i != e; ++i)
1664    if (Visit(MakeCXCursor(*i, D, TU)))
1665        return true;
1666
1667  return false;
1668}
1669
1670//===----------------------------------------------------------------------===//
1671// Data-recursive visitor methods.
1672//===----------------------------------------------------------------------===//
1673
1674namespace {
1675#define DEF_JOB(NAME, DATA, KIND)\
1676class NAME : public VisitorJob {\
1677public:\
1678  NAME(DATA *d, CXCursor parent) : VisitorJob(parent, VisitorJob::KIND, d) {} \
1679  static bool classof(const VisitorJob *VJ) { return VJ->getKind() == KIND; }\
1680  DATA *get() const { return static_cast<DATA*>(dataA); }\
1681};
1682
1683DEF_JOB(StmtVisit, Stmt, StmtVisitKind)
1684DEF_JOB(MemberExprParts, MemberExpr, MemberExprPartsKind)
1685DEF_JOB(DeclRefExprParts, DeclRefExpr, DeclRefExprPartsKind)
1686DEF_JOB(OverloadExprParts, OverloadExpr, OverloadExprPartsKind)
1687#undef DEF_JOB
1688
1689class DeclVisit : public VisitorJob {
1690public:
1691  DeclVisit(Decl *d, CXCursor parent, bool isFirst) :
1692    VisitorJob(parent, VisitorJob::DeclVisitKind,
1693               d, isFirst ? (void*) 1 : (void*) 0) {}
1694  static bool classof(const VisitorJob *VJ) {
1695    return VJ->getKind () == DeclVisitKind;
1696  }
1697  Decl *get() { return static_cast<Decl*>(dataA);}
1698  bool isFirst() const { return dataB ? true : false; }
1699};
1700
1701class TypeLocVisit : public VisitorJob {
1702public:
1703  TypeLocVisit(TypeLoc tl, CXCursor parent) :
1704    VisitorJob(parent, VisitorJob::TypeLocVisitKind,
1705               tl.getType().getAsOpaquePtr(), tl.getOpaqueData()) {}
1706
1707  static bool classof(const VisitorJob *VJ) {
1708    return VJ->getKind() == TypeLocVisitKind;
1709  }
1710
1711  TypeLoc get() {
1712    QualType T = QualType::getFromOpaquePtr(dataA);
1713    return TypeLoc(T, dataB);
1714  }
1715};
1716
1717class EnqueueVisitor : public StmtVisitor<EnqueueVisitor, void> {
1718  VisitorWorkList &WL;
1719  CXCursor Parent;
1720public:
1721  EnqueueVisitor(VisitorWorkList &wl, CXCursor parent)
1722    : WL(wl), Parent(parent) {}
1723
1724  void VisitBlockExpr(BlockExpr *B);
1725  void VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
1726  void VisitCompoundStmt(CompoundStmt *S);
1727  void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { /* Do nothing. */ }
1728  void VisitCXXNewExpr(CXXNewExpr *E);
1729  void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E);
1730  void VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E);
1731  void VisitDeclRefExpr(DeclRefExpr *D);
1732  void VisitDeclStmt(DeclStmt *S);
1733  void VisitExplicitCastExpr(ExplicitCastExpr *E);
1734  void VisitForStmt(ForStmt *FS);
1735  void VisitIfStmt(IfStmt *If);
1736  void VisitInitListExpr(InitListExpr *IE);
1737  void VisitMemberExpr(MemberExpr *M);
1738  void VisitObjCEncodeExpr(ObjCEncodeExpr *E);
1739  void VisitObjCMessageExpr(ObjCMessageExpr *M);
1740  void VisitOverloadExpr(OverloadExpr *E);
1741  void VisitStmt(Stmt *S);
1742  void VisitSwitchStmt(SwitchStmt *S);
1743  void VisitWhileStmt(WhileStmt *W);
1744  void VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U);
1745
1746private:
1747  void AddStmt(Stmt *S);
1748  void AddDecl(Decl *D, bool isFirst = true);
1749  void AddTypeLoc(TypeSourceInfo *TI);
1750  void EnqueueChildren(Stmt *S);
1751};
1752} // end anonyous namespace
1753
1754void EnqueueVisitor::AddStmt(Stmt *S) {
1755  if (S)
1756    WL.push_back(StmtVisit(S, Parent));
1757}
1758void EnqueueVisitor::AddDecl(Decl *D, bool isFirst) {
1759  if (D)
1760    WL.push_back(DeclVisit(D, Parent, isFirst));
1761}
1762void EnqueueVisitor::AddTypeLoc(TypeSourceInfo *TI) {
1763  if (TI)
1764    WL.push_back(TypeLocVisit(TI->getTypeLoc(), Parent));
1765 }
1766void EnqueueVisitor::EnqueueChildren(Stmt *S) {
1767  unsigned size = WL.size();
1768  for (Stmt::child_iterator Child = S->child_begin(), ChildEnd = S->child_end();
1769       Child != ChildEnd; ++Child) {
1770    AddStmt(*Child);
1771  }
1772  if (size == WL.size())
1773    return;
1774  // Now reverse the entries we just added.  This will match the DFS
1775  // ordering performed by the worklist.
1776  VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1777  std::reverse(I, E);
1778}
1779void EnqueueVisitor::VisitBlockExpr(BlockExpr *B) {
1780  AddDecl(B->getBlockDecl());
1781}
1782void EnqueueVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
1783  EnqueueChildren(E);
1784  AddTypeLoc(E->getTypeSourceInfo());
1785}
1786void EnqueueVisitor::VisitCompoundStmt(CompoundStmt *S) {
1787  for (CompoundStmt::reverse_body_iterator I = S->body_rbegin(),
1788        E = S->body_rend(); I != E; ++I) {
1789    AddStmt(*I);
1790  }
1791}
1792void EnqueueVisitor::VisitCXXNewExpr(CXXNewExpr *E) {
1793  // Enqueue the initializer or constructor arguments.
1794  for (unsigned I = E->getNumConstructorArgs(); I > 0; --I)
1795    AddStmt(E->getConstructorArg(I-1));
1796  // Enqueue the array size, if any.
1797  AddStmt(E->getArraySize());
1798  // Enqueue the allocated type.
1799  AddTypeLoc(E->getAllocatedTypeSourceInfo());
1800  // Enqueue the placement arguments.
1801  for (unsigned I = E->getNumPlacementArgs(); I > 0; --I)
1802    AddStmt(E->getPlacementArg(I-1));
1803}
1804void EnqueueVisitor::VisitCXXOperatorCallExpr(CXXOperatorCallExpr *CE) {
1805  for (unsigned I = CE->getNumArgs(); I > 1 /* Yes, this is 1 */; --I)
1806    AddStmt(CE->getArg(I-1));
1807  AddStmt(CE->getCallee());
1808  AddStmt(CE->getArg(0));
1809}
1810void EnqueueVisitor::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E) {
1811  EnqueueChildren(E);
1812  AddTypeLoc(E->getTypeSourceInfo());
1813}
1814void EnqueueVisitor::VisitDeclRefExpr(DeclRefExpr *DR) {
1815  WL.push_back(DeclRefExprParts(DR, Parent));
1816}
1817void EnqueueVisitor::VisitDeclStmt(DeclStmt *S) {
1818  unsigned size = WL.size();
1819  bool isFirst = true;
1820  for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
1821       D != DEnd; ++D) {
1822    AddDecl(*D, isFirst);
1823    isFirst = false;
1824  }
1825  if (size == WL.size())
1826    return;
1827  // Now reverse the entries we just added.  This will match the DFS
1828  // ordering performed by the worklist.
1829  VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1830  std::reverse(I, E);
1831}
1832void EnqueueVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
1833  EnqueueChildren(E);
1834  AddTypeLoc(E->getTypeInfoAsWritten());
1835}
1836void EnqueueVisitor::VisitForStmt(ForStmt *FS) {
1837  AddStmt(FS->getBody());
1838  AddStmt(FS->getInc());
1839  AddStmt(FS->getCond());
1840  AddDecl(FS->getConditionVariable());
1841  AddStmt(FS->getInit());
1842}
1843void EnqueueVisitor::VisitIfStmt(IfStmt *If) {
1844  AddStmt(If->getElse());
1845  AddStmt(If->getThen());
1846  AddStmt(If->getCond());
1847  AddDecl(If->getConditionVariable());
1848}
1849void EnqueueVisitor::VisitInitListExpr(InitListExpr *IE) {
1850  // We care about the syntactic form of the initializer list, only.
1851  if (InitListExpr *Syntactic = IE->getSyntacticForm())
1852    IE = Syntactic;
1853  EnqueueChildren(IE);
1854}
1855void EnqueueVisitor::VisitMemberExpr(MemberExpr *M) {
1856  WL.push_back(MemberExprParts(M, Parent));
1857  AddStmt(M->getBase());
1858}
1859void EnqueueVisitor::VisitObjCEncodeExpr(ObjCEncodeExpr *E) {
1860  AddTypeLoc(E->getEncodedTypeSourceInfo());
1861}
1862void EnqueueVisitor::VisitObjCMessageExpr(ObjCMessageExpr *M) {
1863  EnqueueChildren(M);
1864  AddTypeLoc(M->getClassReceiverTypeInfo());
1865}
1866void EnqueueVisitor::VisitOverloadExpr(OverloadExpr *E) {
1867  WL.push_back(OverloadExprParts(E, Parent));
1868}
1869void EnqueueVisitor::VisitStmt(Stmt *S) {
1870  EnqueueChildren(S);
1871}
1872void EnqueueVisitor::VisitSwitchStmt(SwitchStmt *S) {
1873  AddStmt(S->getBody());
1874  AddStmt(S->getCond());
1875  AddDecl(S->getConditionVariable());
1876}
1877void EnqueueVisitor::VisitWhileStmt(WhileStmt *W) {
1878  AddStmt(W->getBody());
1879  AddStmt(W->getCond());
1880  AddDecl(W->getConditionVariable());
1881}
1882void EnqueueVisitor::VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U) {
1883  VisitOverloadExpr(U);
1884  if (!U->isImplicitAccess())
1885    AddStmt(U->getBase());
1886}
1887
1888void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, Stmt *S) {
1889  EnqueueVisitor(WL, MakeCXCursor(S, StmtParent, TU)).Visit(S);
1890}
1891
1892bool CursorVisitor::IsInRegionOfInterest(CXCursor C) {
1893  if (RegionOfInterest.isValid()) {
1894    SourceRange Range = getRawCursorExtent(C);
1895    if (Range.isInvalid() || CompareRegionOfInterest(Range))
1896      return false;
1897  }
1898  return true;
1899}
1900
1901bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) {
1902  while (!WL.empty()) {
1903    // Dequeue the worklist item.
1904    VisitorJob LI = WL.back(); WL.pop_back();
1905
1906    // Set the Parent field, then back to its old value once we're done.
1907    SetParentRAII SetParent(Parent, StmtParent, LI.getParent());
1908
1909    switch (LI.getKind()) {
1910      case VisitorJob::DeclVisitKind: {
1911        Decl *D = cast<DeclVisit>(LI).get();
1912        if (!D)
1913          continue;
1914
1915        // For now, perform default visitation for Decls.
1916        if (Visit(MakeCXCursor(D, TU, cast<DeclVisit>(LI).isFirst())))
1917            return true;
1918
1919        continue;
1920      }
1921      case VisitorJob::TypeLocVisitKind: {
1922        // Perform default visitation for TypeLocs.
1923        if (Visit(cast<TypeLocVisit>(LI).get()))
1924          return true;
1925        continue;
1926      }
1927      case VisitorJob::StmtVisitKind: {
1928        Stmt *S = cast<StmtVisit>(LI).get();
1929        if (!S)
1930          continue;
1931
1932        // Update the current cursor.
1933        CXCursor Cursor = MakeCXCursor(S, StmtParent, TU);
1934
1935        switch (S->getStmtClass()) {
1936          case Stmt::GotoStmtClass: {
1937            GotoStmt *GS = cast<GotoStmt>(S);
1938            if (Visit(MakeCursorLabelRef(GS->getLabel(),
1939                                         GS->getLabelLoc(), TU))) {
1940              return true;
1941            }
1942            continue;
1943          }
1944          default: {
1945            // FIXME: this entire switch stmt will eventually
1946            // go away.
1947            if (!isa<ExplicitCastExpr>(S)) {
1948              // Perform default visitation for other cases.
1949              if (Visit(Cursor))
1950                return true;
1951              continue;
1952            }
1953            // Fall-through.
1954          }
1955          case Stmt::BinaryOperatorClass:
1956          case Stmt::BlockExprClass:
1957          case Stmt::CallExprClass:
1958          case Stmt::CaseStmtClass:
1959          case Stmt::CompoundLiteralExprClass:
1960          case Stmt::CompoundStmtClass:
1961          case Stmt::CXXDefaultArgExprClass:
1962          case Stmt::CXXMemberCallExprClass:
1963          case Stmt::CXXNewExprClass:
1964          case Stmt::CXXOperatorCallExprClass:
1965          case Stmt::CXXTemporaryObjectExprClass:
1966          case Stmt::DefaultStmtClass:
1967          case Stmt::DoStmtClass:
1968          case Stmt::ForStmtClass:
1969          case Stmt::IfStmtClass:
1970          case Stmt::InitListExprClass:
1971          case Stmt::MemberExprClass:
1972          case Stmt::ObjCEncodeExprClass:
1973          case Stmt::ObjCMessageExprClass:
1974          case Stmt::ParenExprClass:
1975          case Stmt::SwitchStmtClass:
1976          case Stmt::UnaryOperatorClass:
1977          case Stmt::UnresolvedLookupExprClass:
1978          case Stmt::UnresolvedMemberExprClass:
1979          case Stmt::WhileStmtClass:
1980          {
1981            if (!IsInRegionOfInterest(Cursor))
1982              continue;
1983            switch (Visitor(Cursor, Parent, ClientData)) {
1984              case CXChildVisit_Break:
1985                return true;
1986              case CXChildVisit_Continue:
1987                break;
1988              case CXChildVisit_Recurse:
1989                EnqueueWorkList(WL, S);
1990                break;
1991            }
1992          }
1993        }
1994        continue;
1995      }
1996      case VisitorJob::MemberExprPartsKind: {
1997        // Handle the other pieces in the MemberExpr besides the base.
1998        MemberExpr *M = cast<MemberExprParts>(LI).get();
1999
2000        // Visit the nested-name-specifier
2001        if (NestedNameSpecifier *Qualifier = M->getQualifier())
2002          if (VisitNestedNameSpecifier(Qualifier, M->getQualifierRange()))
2003            return true;
2004
2005        // Visit the declaration name.
2006        if (VisitDeclarationNameInfo(M->getMemberNameInfo()))
2007          return true;
2008
2009        // Visit the explicitly-specified template arguments, if any.
2010        if (M->hasExplicitTemplateArgs()) {
2011          for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(),
2012               *ArgEnd = Arg + M->getNumTemplateArgs();
2013               Arg != ArgEnd; ++Arg) {
2014            if (VisitTemplateArgumentLoc(*Arg))
2015              return true;
2016          }
2017        }
2018        continue;
2019      }
2020      case VisitorJob::DeclRefExprPartsKind: {
2021        DeclRefExpr *DR = cast<DeclRefExprParts>(LI).get();
2022        // Visit nested-name-specifier, if present.
2023        if (NestedNameSpecifier *Qualifier = DR->getQualifier())
2024          if (VisitNestedNameSpecifier(Qualifier, DR->getQualifierRange()))
2025            return true;
2026        // Visit declaration name.
2027        if (VisitDeclarationNameInfo(DR->getNameInfo()))
2028          return true;
2029        // Visit explicitly-specified template arguments.
2030        if (DR->hasExplicitTemplateArgs()) {
2031          ExplicitTemplateArgumentList &Args = DR->getExplicitTemplateArgs();
2032          for (TemplateArgumentLoc *Arg = Args.getTemplateArgs(),
2033                 *ArgEnd = Arg + Args.NumTemplateArgs;
2034               Arg != ArgEnd; ++Arg)
2035            if (VisitTemplateArgumentLoc(*Arg))
2036              return true;
2037        }
2038        continue;
2039      }
2040      case VisitorJob::OverloadExprPartsKind: {
2041        OverloadExpr *O = cast<OverloadExprParts>(LI).get();
2042        // Visit the nested-name-specifier.
2043        if (NestedNameSpecifier *Qualifier = O->getQualifier())
2044          if (VisitNestedNameSpecifier(Qualifier, O->getQualifierRange()))
2045            return true;
2046        // Visit the declaration name.
2047        if (VisitDeclarationNameInfo(O->getNameInfo()))
2048          return true;
2049        // Visit the overloaded declaration reference.
2050        if (Visit(MakeCursorOverloadedDeclRef(O, TU)))
2051          return true;
2052        // Visit the explicitly-specified template arguments.
2053        if (const ExplicitTemplateArgumentList *ArgList
2054                                      = O->getOptionalExplicitTemplateArgs()) {
2055          for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
2056                 *ArgEnd = Arg + ArgList->NumTemplateArgs;
2057               Arg != ArgEnd; ++Arg) {
2058            if (VisitTemplateArgumentLoc(*Arg))
2059              return true;
2060          }
2061        }
2062        continue;
2063      }
2064    }
2065  }
2066  return false;
2067}
2068
2069bool CursorVisitor::VisitDataRecursive(Stmt *S) {
2070  VisitorWorkList WL;
2071  EnqueueWorkList(WL, S);
2072  return RunVisitorWorkList(WL);
2073}
2074
2075//===----------------------------------------------------------------------===//
2076// Misc. API hooks.
2077//===----------------------------------------------------------------------===//
2078
2079static llvm::sys::Mutex EnableMultithreadingMutex;
2080static bool EnabledMultithreading;
2081
2082extern "C" {
2083CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
2084                          int displayDiagnostics) {
2085  // Disable pretty stack trace functionality, which will otherwise be a very
2086  // poor citizen of the world and set up all sorts of signal handlers.
2087  llvm::DisablePrettyStackTrace = true;
2088
2089  // We use crash recovery to make some of our APIs more reliable, implicitly
2090  // enable it.
2091  llvm::CrashRecoveryContext::Enable();
2092
2093  // Enable support for multithreading in LLVM.
2094  {
2095    llvm::sys::ScopedLock L(EnableMultithreadingMutex);
2096    if (!EnabledMultithreading) {
2097      llvm::llvm_start_multithreaded();
2098      EnabledMultithreading = true;
2099    }
2100  }
2101
2102  CIndexer *CIdxr = new CIndexer();
2103  if (excludeDeclarationsFromPCH)
2104    CIdxr->setOnlyLocalDecls();
2105  if (displayDiagnostics)
2106    CIdxr->setDisplayDiagnostics();
2107  return CIdxr;
2108}
2109
2110void clang_disposeIndex(CXIndex CIdx) {
2111  if (CIdx)
2112    delete static_cast<CIndexer *>(CIdx);
2113}
2114
2115CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
2116                                              const char *ast_filename) {
2117  if (!CIdx)
2118    return 0;
2119
2120  CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
2121  FileSystemOptions FileSystemOpts;
2122  FileSystemOpts.WorkingDir = CXXIdx->getWorkingDirectory();
2123
2124  llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
2125  return ASTUnit::LoadFromASTFile(ast_filename, Diags, FileSystemOpts,
2126                                  CXXIdx->getOnlyLocalDecls(),
2127                                  0, 0, true);
2128}
2129
2130unsigned clang_defaultEditingTranslationUnitOptions() {
2131  return CXTranslationUnit_PrecompiledPreamble |
2132         CXTranslationUnit_CacheCompletionResults |
2133         CXTranslationUnit_CXXPrecompiledPreamble;
2134}
2135
2136CXTranslationUnit
2137clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
2138                                          const char *source_filename,
2139                                          int num_command_line_args,
2140                                          const char * const *command_line_args,
2141                                          unsigned num_unsaved_files,
2142                                          struct CXUnsavedFile *unsaved_files) {
2143  return clang_parseTranslationUnit(CIdx, source_filename,
2144                                    command_line_args, num_command_line_args,
2145                                    unsaved_files, num_unsaved_files,
2146                                 CXTranslationUnit_DetailedPreprocessingRecord);
2147}
2148
2149struct ParseTranslationUnitInfo {
2150  CXIndex CIdx;
2151  const char *source_filename;
2152  const char *const *command_line_args;
2153  int num_command_line_args;
2154  struct CXUnsavedFile *unsaved_files;
2155  unsigned num_unsaved_files;
2156  unsigned options;
2157  CXTranslationUnit result;
2158};
2159static void clang_parseTranslationUnit_Impl(void *UserData) {
2160  ParseTranslationUnitInfo *PTUI =
2161    static_cast<ParseTranslationUnitInfo*>(UserData);
2162  CXIndex CIdx = PTUI->CIdx;
2163  const char *source_filename = PTUI->source_filename;
2164  const char * const *command_line_args = PTUI->command_line_args;
2165  int num_command_line_args = PTUI->num_command_line_args;
2166  struct CXUnsavedFile *unsaved_files = PTUI->unsaved_files;
2167  unsigned num_unsaved_files = PTUI->num_unsaved_files;
2168  unsigned options = PTUI->options;
2169  PTUI->result = 0;
2170
2171  if (!CIdx)
2172    return;
2173
2174  CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
2175
2176  bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
2177  bool CompleteTranslationUnit
2178    = ((options & CXTranslationUnit_Incomplete) == 0);
2179  bool CacheCodeCompetionResults
2180    = options & CXTranslationUnit_CacheCompletionResults;
2181  bool CXXPrecompilePreamble
2182    = options & CXTranslationUnit_CXXPrecompiledPreamble;
2183  bool CXXChainedPCH
2184    = options & CXTranslationUnit_CXXChainedPCH;
2185
2186  // Configure the diagnostics.
2187  DiagnosticOptions DiagOpts;
2188  llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
2189  Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
2190
2191  llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
2192  for (unsigned I = 0; I != num_unsaved_files; ++I) {
2193    llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
2194    const llvm::MemoryBuffer *Buffer
2195      = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
2196    RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
2197                                           Buffer));
2198  }
2199
2200  llvm::SmallVector<const char *, 16> Args;
2201
2202  // The 'source_filename' argument is optional.  If the caller does not
2203  // specify it then it is assumed that the source file is specified
2204  // in the actual argument list.
2205  if (source_filename)
2206    Args.push_back(source_filename);
2207
2208  // Since the Clang C library is primarily used by batch tools dealing with
2209  // (often very broken) source code, where spell-checking can have a
2210  // significant negative impact on performance (particularly when
2211  // precompiled headers are involved), we disable it by default.
2212  // Only do this if we haven't found a spell-checking-related argument.
2213  bool FoundSpellCheckingArgument = false;
2214  for (int I = 0; I != num_command_line_args; ++I) {
2215    if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
2216        strcmp(command_line_args[I], "-fspell-checking") == 0) {
2217      FoundSpellCheckingArgument = true;
2218      break;
2219    }
2220  }
2221  if (!FoundSpellCheckingArgument)
2222    Args.push_back("-fno-spell-checking");
2223
2224  Args.insert(Args.end(), command_line_args,
2225              command_line_args + num_command_line_args);
2226
2227  // Do we need the detailed preprocessing record?
2228  if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
2229    Args.push_back("-Xclang");
2230    Args.push_back("-detailed-preprocessing-record");
2231  }
2232
2233  unsigned NumErrors = Diags->getNumErrors();
2234  llvm::OwningPtr<ASTUnit> Unit(
2235    ASTUnit::LoadFromCommandLine(Args.data(), Args.data() + Args.size(),
2236                                 Diags,
2237                                 CXXIdx->getClangResourcesPath(),
2238                                 CXXIdx->getOnlyLocalDecls(),
2239                                 /*CaptureDiagnostics=*/true,
2240                                 RemappedFiles.data(),
2241                                 RemappedFiles.size(),
2242                                 PrecompilePreamble,
2243                                 CompleteTranslationUnit,
2244                                 CacheCodeCompetionResults,
2245                                 CXXPrecompilePreamble,
2246                                 CXXChainedPCH));
2247
2248  if (NumErrors != Diags->getNumErrors()) {
2249    // Make sure to check that 'Unit' is non-NULL.
2250    if (CXXIdx->getDisplayDiagnostics() && Unit.get()) {
2251      for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
2252                                      DEnd = Unit->stored_diag_end();
2253           D != DEnd; ++D) {
2254        CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOptions());
2255        CXString Msg = clang_formatDiagnostic(&Diag,
2256                                    clang_defaultDiagnosticDisplayOptions());
2257        fprintf(stderr, "%s\n", clang_getCString(Msg));
2258        clang_disposeString(Msg);
2259      }
2260#ifdef LLVM_ON_WIN32
2261      // On Windows, force a flush, since there may be multiple copies of
2262      // stderr and stdout in the file system, all with different buffers
2263      // but writing to the same device.
2264      fflush(stderr);
2265#endif
2266    }
2267  }
2268
2269  PTUI->result = Unit.take();
2270}
2271CXTranslationUnit clang_parseTranslationUnit(CXIndex CIdx,
2272                                             const char *source_filename,
2273                                         const char * const *command_line_args,
2274                                             int num_command_line_args,
2275                                            struct CXUnsavedFile *unsaved_files,
2276                                             unsigned num_unsaved_files,
2277                                             unsigned options) {
2278  ParseTranslationUnitInfo PTUI = { CIdx, source_filename, command_line_args,
2279                                    num_command_line_args, unsaved_files,
2280                                    num_unsaved_files, options, 0 };
2281  llvm::CrashRecoveryContext CRC;
2282
2283  if (!RunSafely(CRC, clang_parseTranslationUnit_Impl, &PTUI)) {
2284    fprintf(stderr, "libclang: crash detected during parsing: {\n");
2285    fprintf(stderr, "  'source_filename' : '%s'\n", source_filename);
2286    fprintf(stderr, "  'command_line_args' : [");
2287    for (int i = 0; i != num_command_line_args; ++i) {
2288      if (i)
2289        fprintf(stderr, ", ");
2290      fprintf(stderr, "'%s'", command_line_args[i]);
2291    }
2292    fprintf(stderr, "],\n");
2293    fprintf(stderr, "  'unsaved_files' : [");
2294    for (unsigned i = 0; i != num_unsaved_files; ++i) {
2295      if (i)
2296        fprintf(stderr, ", ");
2297      fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
2298              unsaved_files[i].Length);
2299    }
2300    fprintf(stderr, "],\n");
2301    fprintf(stderr, "  'options' : %d,\n", options);
2302    fprintf(stderr, "}\n");
2303
2304    return 0;
2305  }
2306
2307  return PTUI.result;
2308}
2309
2310unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
2311  return CXSaveTranslationUnit_None;
2312}
2313
2314int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
2315                              unsigned options) {
2316  if (!TU)
2317    return 1;
2318
2319  return static_cast<ASTUnit *>(TU)->Save(FileName);
2320}
2321
2322void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
2323  if (CTUnit) {
2324    // If the translation unit has been marked as unsafe to free, just discard
2325    // it.
2326    if (static_cast<ASTUnit *>(CTUnit)->isUnsafeToFree())
2327      return;
2328
2329    delete static_cast<ASTUnit *>(CTUnit);
2330  }
2331}
2332
2333unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
2334  return CXReparse_None;
2335}
2336
2337struct ReparseTranslationUnitInfo {
2338  CXTranslationUnit TU;
2339  unsigned num_unsaved_files;
2340  struct CXUnsavedFile *unsaved_files;
2341  unsigned options;
2342  int result;
2343};
2344
2345static void clang_reparseTranslationUnit_Impl(void *UserData) {
2346  ReparseTranslationUnitInfo *RTUI =
2347    static_cast<ReparseTranslationUnitInfo*>(UserData);
2348  CXTranslationUnit TU = RTUI->TU;
2349  unsigned num_unsaved_files = RTUI->num_unsaved_files;
2350  struct CXUnsavedFile *unsaved_files = RTUI->unsaved_files;
2351  unsigned options = RTUI->options;
2352  (void) options;
2353  RTUI->result = 1;
2354
2355  if (!TU)
2356    return;
2357
2358  ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2359  ASTUnit::ConcurrencyCheck Check(*CXXUnit);
2360
2361  llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
2362  for (unsigned I = 0; I != num_unsaved_files; ++I) {
2363    llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
2364    const llvm::MemoryBuffer *Buffer
2365      = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
2366    RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
2367                                           Buffer));
2368  }
2369
2370  if (!CXXUnit->Reparse(RemappedFiles.data(), RemappedFiles.size()))
2371    RTUI->result = 0;
2372}
2373
2374int clang_reparseTranslationUnit(CXTranslationUnit TU,
2375                                 unsigned num_unsaved_files,
2376                                 struct CXUnsavedFile *unsaved_files,
2377                                 unsigned options) {
2378  ReparseTranslationUnitInfo RTUI = { TU, num_unsaved_files, unsaved_files,
2379                                      options, 0 };
2380  llvm::CrashRecoveryContext CRC;
2381
2382  if (!RunSafely(CRC, clang_reparseTranslationUnit_Impl, &RTUI)) {
2383    fprintf(stderr, "libclang: crash detected during reparsing\n");
2384    static_cast<ASTUnit *>(TU)->setUnsafeToFree(true);
2385    return 1;
2386  }
2387
2388
2389  return RTUI.result;
2390}
2391
2392
2393CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
2394  if (!CTUnit)
2395    return createCXString("");
2396
2397  ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit);
2398  return createCXString(CXXUnit->getOriginalSourceFileName(), true);
2399}
2400
2401CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
2402  CXCursor Result = { CXCursor_TranslationUnit, { 0, 0, TU } };
2403  return Result;
2404}
2405
2406} // end: extern "C"
2407
2408//===----------------------------------------------------------------------===//
2409// CXSourceLocation and CXSourceRange Operations.
2410//===----------------------------------------------------------------------===//
2411
2412extern "C" {
2413CXSourceLocation clang_getNullLocation() {
2414  CXSourceLocation Result = { { 0, 0 }, 0 };
2415  return Result;
2416}
2417
2418unsigned clang_equalLocations(CXSourceLocation loc1, CXSourceLocation loc2) {
2419  return (loc1.ptr_data[0] == loc2.ptr_data[0] &&
2420          loc1.ptr_data[1] == loc2.ptr_data[1] &&
2421          loc1.int_data == loc2.int_data);
2422}
2423
2424CXSourceLocation clang_getLocation(CXTranslationUnit tu,
2425                                   CXFile file,
2426                                   unsigned line,
2427                                   unsigned column) {
2428  if (!tu || !file)
2429    return clang_getNullLocation();
2430
2431  ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
2432  SourceLocation SLoc
2433    = CXXUnit->getSourceManager().getLocation(
2434                                        static_cast<const FileEntry *>(file),
2435                                              line, column);
2436  if (SLoc.isInvalid()) return clang_getNullLocation();
2437
2438  return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
2439}
2440
2441CXSourceLocation clang_getLocationForOffset(CXTranslationUnit tu,
2442                                            CXFile file,
2443                                            unsigned offset) {
2444  if (!tu || !file)
2445    return clang_getNullLocation();
2446
2447  ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
2448  SourceLocation Start
2449    = CXXUnit->getSourceManager().getLocation(
2450                                        static_cast<const FileEntry *>(file),
2451                                              1, 1);
2452  if (Start.isInvalid()) return clang_getNullLocation();
2453
2454  SourceLocation SLoc = Start.getFileLocWithOffset(offset);
2455
2456  if (SLoc.isInvalid()) return clang_getNullLocation();
2457
2458  return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
2459}
2460
2461CXSourceRange clang_getNullRange() {
2462  CXSourceRange Result = { { 0, 0 }, 0, 0 };
2463  return Result;
2464}
2465
2466CXSourceRange clang_getRange(CXSourceLocation begin, CXSourceLocation end) {
2467  if (begin.ptr_data[0] != end.ptr_data[0] ||
2468      begin.ptr_data[1] != end.ptr_data[1])
2469    return clang_getNullRange();
2470
2471  CXSourceRange Result = { { begin.ptr_data[0], begin.ptr_data[1] },
2472                           begin.int_data, end.int_data };
2473  return Result;
2474}
2475
2476void clang_getInstantiationLocation(CXSourceLocation location,
2477                                    CXFile *file,
2478                                    unsigned *line,
2479                                    unsigned *column,
2480                                    unsigned *offset) {
2481  SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2482
2483  if (!location.ptr_data[0] || Loc.isInvalid()) {
2484    if (file)
2485      *file = 0;
2486    if (line)
2487      *line = 0;
2488    if (column)
2489      *column = 0;
2490    if (offset)
2491      *offset = 0;
2492    return;
2493  }
2494
2495  const SourceManager &SM =
2496    *static_cast<const SourceManager*>(location.ptr_data[0]);
2497  SourceLocation InstLoc = SM.getInstantiationLoc(Loc);
2498
2499  if (file)
2500    *file = (void *)SM.getFileEntryForID(SM.getFileID(InstLoc));
2501  if (line)
2502    *line = SM.getInstantiationLineNumber(InstLoc);
2503  if (column)
2504    *column = SM.getInstantiationColumnNumber(InstLoc);
2505  if (offset)
2506    *offset = SM.getDecomposedLoc(InstLoc).second;
2507}
2508
2509void clang_getSpellingLocation(CXSourceLocation location,
2510                               CXFile *file,
2511                               unsigned *line,
2512                               unsigned *column,
2513                               unsigned *offset) {
2514  SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2515
2516  if (!location.ptr_data[0] || Loc.isInvalid()) {
2517    if (file)
2518      *file = 0;
2519    if (line)
2520      *line = 0;
2521    if (column)
2522      *column = 0;
2523    if (offset)
2524      *offset = 0;
2525    return;
2526  }
2527
2528  const SourceManager &SM =
2529    *static_cast<const SourceManager*>(location.ptr_data[0]);
2530  SourceLocation SpellLoc = Loc;
2531  if (SpellLoc.isMacroID()) {
2532    SourceLocation SimpleSpellingLoc = SM.getImmediateSpellingLoc(SpellLoc);
2533    if (SimpleSpellingLoc.isFileID() &&
2534        SM.getFileEntryForID(SM.getDecomposedLoc(SimpleSpellingLoc).first))
2535      SpellLoc = SimpleSpellingLoc;
2536    else
2537      SpellLoc = SM.getInstantiationLoc(SpellLoc);
2538  }
2539
2540  std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(SpellLoc);
2541  FileID FID = LocInfo.first;
2542  unsigned FileOffset = LocInfo.second;
2543
2544  if (file)
2545    *file = (void *)SM.getFileEntryForID(FID);
2546  if (line)
2547    *line = SM.getLineNumber(FID, FileOffset);
2548  if (column)
2549    *column = SM.getColumnNumber(FID, FileOffset);
2550  if (offset)
2551    *offset = FileOffset;
2552}
2553
2554CXSourceLocation clang_getRangeStart(CXSourceRange range) {
2555  CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
2556                              range.begin_int_data };
2557  return Result;
2558}
2559
2560CXSourceLocation clang_getRangeEnd(CXSourceRange range) {
2561  CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
2562                              range.end_int_data };
2563  return Result;
2564}
2565
2566} // end: extern "C"
2567
2568//===----------------------------------------------------------------------===//
2569// CXFile Operations.
2570//===----------------------------------------------------------------------===//
2571
2572extern "C" {
2573CXString clang_getFileName(CXFile SFile) {
2574  if (!SFile)
2575    return createCXString(NULL);
2576
2577  FileEntry *FEnt = static_cast<FileEntry *>(SFile);
2578  return createCXString(FEnt->getName());
2579}
2580
2581time_t clang_getFileTime(CXFile SFile) {
2582  if (!SFile)
2583    return 0;
2584
2585  FileEntry *FEnt = static_cast<FileEntry *>(SFile);
2586  return FEnt->getModificationTime();
2587}
2588
2589CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
2590  if (!tu)
2591    return 0;
2592
2593  ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
2594
2595  FileManager &FMgr = CXXUnit->getFileManager();
2596  const FileEntry *File = FMgr.getFile(file_name, file_name+strlen(file_name),
2597                                       CXXUnit->getFileSystemOpts());
2598  return const_cast<FileEntry *>(File);
2599}
2600
2601} // end: extern "C"
2602
2603//===----------------------------------------------------------------------===//
2604// CXCursor Operations.
2605//===----------------------------------------------------------------------===//
2606
2607static Decl *getDeclFromExpr(Stmt *E) {
2608  if (CastExpr *CE = dyn_cast<CastExpr>(E))
2609    return getDeclFromExpr(CE->getSubExpr());
2610
2611  if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
2612    return RefExpr->getDecl();
2613  if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2614    return RefExpr->getDecl();
2615  if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
2616    return ME->getMemberDecl();
2617  if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
2618    return RE->getDecl();
2619  if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E))
2620    return PRE->getProperty();
2621
2622  if (CallExpr *CE = dyn_cast<CallExpr>(E))
2623    return getDeclFromExpr(CE->getCallee());
2624  if (CXXConstructExpr *CE = llvm::dyn_cast<CXXConstructExpr>(E))
2625    if (!CE->isElidable())
2626    return CE->getConstructor();
2627  if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
2628    return OME->getMethodDecl();
2629
2630  if (ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
2631    return PE->getProtocol();
2632
2633  return 0;
2634}
2635
2636static SourceLocation getLocationFromExpr(Expr *E) {
2637  if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
2638    return /*FIXME:*/Msg->getLeftLoc();
2639  if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
2640    return DRE->getLocation();
2641  if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2642    return RefExpr->getLocation();
2643  if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
2644    return Member->getMemberLoc();
2645  if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
2646    return Ivar->getLocation();
2647  return E->getLocStart();
2648}
2649
2650extern "C" {
2651
2652unsigned clang_visitChildren(CXCursor parent,
2653                             CXCursorVisitor visitor,
2654                             CXClientData client_data) {
2655  ASTUnit *CXXUnit = getCursorASTUnit(parent);
2656
2657  CursorVisitor CursorVis(CXXUnit, visitor, client_data,
2658                          CXXUnit->getMaxPCHLevel());
2659  return CursorVis.VisitChildren(parent);
2660}
2661
2662#ifndef __has_feature
2663#define __has_feature(x) 0
2664#endif
2665#if __has_feature(blocks)
2666typedef enum CXChildVisitResult
2667     (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent);
2668
2669static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
2670    CXClientData client_data) {
2671  CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
2672  return block(cursor, parent);
2673}
2674#else
2675// If we are compiled with a compiler that doesn't have native blocks support,
2676// define and call the block manually, so the
2677typedef struct _CXChildVisitResult
2678{
2679	void *isa;
2680	int flags;
2681	int reserved;
2682	enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor,
2683                                         CXCursor);
2684} *CXCursorVisitorBlock;
2685
2686static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
2687    CXClientData client_data) {
2688  CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
2689  return block->invoke(block, cursor, parent);
2690}
2691#endif
2692
2693
2694unsigned clang_visitChildrenWithBlock(CXCursor parent,
2695                                      CXCursorVisitorBlock block) {
2696  return clang_visitChildren(parent, visitWithBlock, block);
2697}
2698
2699static CXString getDeclSpelling(Decl *D) {
2700  NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
2701  if (!ND)
2702    return createCXString("");
2703
2704  if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
2705    return createCXString(OMD->getSelector().getAsString());
2706
2707  if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
2708    // No, this isn't the same as the code below. getIdentifier() is non-virtual
2709    // and returns different names. NamedDecl returns the class name and
2710    // ObjCCategoryImplDecl returns the category name.
2711    return createCXString(CIMP->getIdentifier()->getNameStart());
2712
2713  if (isa<UsingDirectiveDecl>(D))
2714    return createCXString("");
2715
2716  llvm::SmallString<1024> S;
2717  llvm::raw_svector_ostream os(S);
2718  ND->printName(os);
2719
2720  return createCXString(os.str());
2721}
2722
2723CXString clang_getCursorSpelling(CXCursor C) {
2724  if (clang_isTranslationUnit(C.kind))
2725    return clang_getTranslationUnitSpelling(C.data[2]);
2726
2727  if (clang_isReference(C.kind)) {
2728    switch (C.kind) {
2729    case CXCursor_ObjCSuperClassRef: {
2730      ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
2731      return createCXString(Super->getIdentifier()->getNameStart());
2732    }
2733    case CXCursor_ObjCClassRef: {
2734      ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
2735      return createCXString(Class->getIdentifier()->getNameStart());
2736    }
2737    case CXCursor_ObjCProtocolRef: {
2738      ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
2739      assert(OID && "getCursorSpelling(): Missing protocol decl");
2740      return createCXString(OID->getIdentifier()->getNameStart());
2741    }
2742    case CXCursor_CXXBaseSpecifier: {
2743      CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
2744      return createCXString(B->getType().getAsString());
2745    }
2746    case CXCursor_TypeRef: {
2747      TypeDecl *Type = getCursorTypeRef(C).first;
2748      assert(Type && "Missing type decl");
2749
2750      return createCXString(getCursorContext(C).getTypeDeclType(Type).
2751                              getAsString());
2752    }
2753    case CXCursor_TemplateRef: {
2754      TemplateDecl *Template = getCursorTemplateRef(C).first;
2755      assert(Template && "Missing template decl");
2756
2757      return createCXString(Template->getNameAsString());
2758    }
2759
2760    case CXCursor_NamespaceRef: {
2761      NamedDecl *NS = getCursorNamespaceRef(C).first;
2762      assert(NS && "Missing namespace decl");
2763
2764      return createCXString(NS->getNameAsString());
2765    }
2766
2767    case CXCursor_MemberRef: {
2768      FieldDecl *Field = getCursorMemberRef(C).first;
2769      assert(Field && "Missing member decl");
2770
2771      return createCXString(Field->getNameAsString());
2772    }
2773
2774    case CXCursor_LabelRef: {
2775      LabelStmt *Label = getCursorLabelRef(C).first;
2776      assert(Label && "Missing label");
2777
2778      return createCXString(Label->getID()->getName());
2779    }
2780
2781    case CXCursor_OverloadedDeclRef: {
2782      OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
2783      if (Decl *D = Storage.dyn_cast<Decl *>()) {
2784        if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
2785          return createCXString(ND->getNameAsString());
2786        return createCXString("");
2787      }
2788      if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
2789        return createCXString(E->getName().getAsString());
2790      OverloadedTemplateStorage *Ovl
2791        = Storage.get<OverloadedTemplateStorage*>();
2792      if (Ovl->size() == 0)
2793        return createCXString("");
2794      return createCXString((*Ovl->begin())->getNameAsString());
2795    }
2796
2797    default:
2798      return createCXString("<not implemented>");
2799    }
2800  }
2801
2802  if (clang_isExpression(C.kind)) {
2803    Decl *D = getDeclFromExpr(getCursorExpr(C));
2804    if (D)
2805      return getDeclSpelling(D);
2806    return createCXString("");
2807  }
2808
2809  if (clang_isStatement(C.kind)) {
2810    Stmt *S = getCursorStmt(C);
2811    if (LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
2812      return createCXString(Label->getID()->getName());
2813
2814    return createCXString("");
2815  }
2816
2817  if (C.kind == CXCursor_MacroInstantiation)
2818    return createCXString(getCursorMacroInstantiation(C)->getName()
2819                                                           ->getNameStart());
2820
2821  if (C.kind == CXCursor_MacroDefinition)
2822    return createCXString(getCursorMacroDefinition(C)->getName()
2823                                                           ->getNameStart());
2824
2825  if (C.kind == CXCursor_InclusionDirective)
2826    return createCXString(getCursorInclusionDirective(C)->getFileName());
2827
2828  if (clang_isDeclaration(C.kind))
2829    return getDeclSpelling(getCursorDecl(C));
2830
2831  return createCXString("");
2832}
2833
2834CXString clang_getCursorDisplayName(CXCursor C) {
2835  if (!clang_isDeclaration(C.kind))
2836    return clang_getCursorSpelling(C);
2837
2838  Decl *D = getCursorDecl(C);
2839  if (!D)
2840    return createCXString("");
2841
2842  PrintingPolicy &Policy = getCursorContext(C).PrintingPolicy;
2843  if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
2844    D = FunTmpl->getTemplatedDecl();
2845
2846  if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
2847    llvm::SmallString<64> Str;
2848    llvm::raw_svector_ostream OS(Str);
2849    OS << Function->getNameAsString();
2850    if (Function->getPrimaryTemplate())
2851      OS << "<>";
2852    OS << "(";
2853    for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
2854      if (I)
2855        OS << ", ";
2856      OS << Function->getParamDecl(I)->getType().getAsString(Policy);
2857    }
2858
2859    if (Function->isVariadic()) {
2860      if (Function->getNumParams())
2861        OS << ", ";
2862      OS << "...";
2863    }
2864    OS << ")";
2865    return createCXString(OS.str());
2866  }
2867
2868  if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
2869    llvm::SmallString<64> Str;
2870    llvm::raw_svector_ostream OS(Str);
2871    OS << ClassTemplate->getNameAsString();
2872    OS << "<";
2873    TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
2874    for (unsigned I = 0, N = Params->size(); I != N; ++I) {
2875      if (I)
2876        OS << ", ";
2877
2878      NamedDecl *Param = Params->getParam(I);
2879      if (Param->getIdentifier()) {
2880        OS << Param->getIdentifier()->getName();
2881        continue;
2882      }
2883
2884      // There is no parameter name, which makes this tricky. Try to come up
2885      // with something useful that isn't too long.
2886      if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
2887        OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
2888      else if (NonTypeTemplateParmDecl *NTTP
2889                                    = dyn_cast<NonTypeTemplateParmDecl>(Param))
2890        OS << NTTP->getType().getAsString(Policy);
2891      else
2892        OS << "template<...> class";
2893    }
2894
2895    OS << ">";
2896    return createCXString(OS.str());
2897  }
2898
2899  if (ClassTemplateSpecializationDecl *ClassSpec
2900                              = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
2901    // If the type was explicitly written, use that.
2902    if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
2903      return createCXString(TSInfo->getType().getAsString(Policy));
2904
2905    llvm::SmallString<64> Str;
2906    llvm::raw_svector_ostream OS(Str);
2907    OS << ClassSpec->getNameAsString();
2908    OS << TemplateSpecializationType::PrintTemplateArgumentList(
2909                                      ClassSpec->getTemplateArgs().data(),
2910                                      ClassSpec->getTemplateArgs().size(),
2911                                                                Policy);
2912    return createCXString(OS.str());
2913  }
2914
2915  return clang_getCursorSpelling(C);
2916}
2917
2918CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
2919  switch (Kind) {
2920  case CXCursor_FunctionDecl:
2921      return createCXString("FunctionDecl");
2922  case CXCursor_TypedefDecl:
2923      return createCXString("TypedefDecl");
2924  case CXCursor_EnumDecl:
2925      return createCXString("EnumDecl");
2926  case CXCursor_EnumConstantDecl:
2927      return createCXString("EnumConstantDecl");
2928  case CXCursor_StructDecl:
2929      return createCXString("StructDecl");
2930  case CXCursor_UnionDecl:
2931      return createCXString("UnionDecl");
2932  case CXCursor_ClassDecl:
2933      return createCXString("ClassDecl");
2934  case CXCursor_FieldDecl:
2935      return createCXString("FieldDecl");
2936  case CXCursor_VarDecl:
2937      return createCXString("VarDecl");
2938  case CXCursor_ParmDecl:
2939      return createCXString("ParmDecl");
2940  case CXCursor_ObjCInterfaceDecl:
2941      return createCXString("ObjCInterfaceDecl");
2942  case CXCursor_ObjCCategoryDecl:
2943      return createCXString("ObjCCategoryDecl");
2944  case CXCursor_ObjCProtocolDecl:
2945      return createCXString("ObjCProtocolDecl");
2946  case CXCursor_ObjCPropertyDecl:
2947      return createCXString("ObjCPropertyDecl");
2948  case CXCursor_ObjCIvarDecl:
2949      return createCXString("ObjCIvarDecl");
2950  case CXCursor_ObjCInstanceMethodDecl:
2951      return createCXString("ObjCInstanceMethodDecl");
2952  case CXCursor_ObjCClassMethodDecl:
2953      return createCXString("ObjCClassMethodDecl");
2954  case CXCursor_ObjCImplementationDecl:
2955      return createCXString("ObjCImplementationDecl");
2956  case CXCursor_ObjCCategoryImplDecl:
2957      return createCXString("ObjCCategoryImplDecl");
2958  case CXCursor_CXXMethod:
2959      return createCXString("CXXMethod");
2960  case CXCursor_UnexposedDecl:
2961      return createCXString("UnexposedDecl");
2962  case CXCursor_ObjCSuperClassRef:
2963      return createCXString("ObjCSuperClassRef");
2964  case CXCursor_ObjCProtocolRef:
2965      return createCXString("ObjCProtocolRef");
2966  case CXCursor_ObjCClassRef:
2967      return createCXString("ObjCClassRef");
2968  case CXCursor_TypeRef:
2969      return createCXString("TypeRef");
2970  case CXCursor_TemplateRef:
2971      return createCXString("TemplateRef");
2972  case CXCursor_NamespaceRef:
2973    return createCXString("NamespaceRef");
2974  case CXCursor_MemberRef:
2975    return createCXString("MemberRef");
2976  case CXCursor_LabelRef:
2977    return createCXString("LabelRef");
2978  case CXCursor_OverloadedDeclRef:
2979    return createCXString("OverloadedDeclRef");
2980  case CXCursor_UnexposedExpr:
2981      return createCXString("UnexposedExpr");
2982  case CXCursor_BlockExpr:
2983      return createCXString("BlockExpr");
2984  case CXCursor_DeclRefExpr:
2985      return createCXString("DeclRefExpr");
2986  case CXCursor_MemberRefExpr:
2987      return createCXString("MemberRefExpr");
2988  case CXCursor_CallExpr:
2989      return createCXString("CallExpr");
2990  case CXCursor_ObjCMessageExpr:
2991      return createCXString("ObjCMessageExpr");
2992  case CXCursor_UnexposedStmt:
2993      return createCXString("UnexposedStmt");
2994  case CXCursor_LabelStmt:
2995      return createCXString("LabelStmt");
2996  case CXCursor_InvalidFile:
2997      return createCXString("InvalidFile");
2998  case CXCursor_InvalidCode:
2999    return createCXString("InvalidCode");
3000  case CXCursor_NoDeclFound:
3001      return createCXString("NoDeclFound");
3002  case CXCursor_NotImplemented:
3003      return createCXString("NotImplemented");
3004  case CXCursor_TranslationUnit:
3005      return createCXString("TranslationUnit");
3006  case CXCursor_UnexposedAttr:
3007      return createCXString("UnexposedAttr");
3008  case CXCursor_IBActionAttr:
3009      return createCXString("attribute(ibaction)");
3010  case CXCursor_IBOutletAttr:
3011     return createCXString("attribute(iboutlet)");
3012  case CXCursor_IBOutletCollectionAttr:
3013      return createCXString("attribute(iboutletcollection)");
3014  case CXCursor_PreprocessingDirective:
3015    return createCXString("preprocessing directive");
3016  case CXCursor_MacroDefinition:
3017    return createCXString("macro definition");
3018  case CXCursor_MacroInstantiation:
3019    return createCXString("macro instantiation");
3020  case CXCursor_InclusionDirective:
3021    return createCXString("inclusion directive");
3022  case CXCursor_Namespace:
3023    return createCXString("Namespace");
3024  case CXCursor_LinkageSpec:
3025    return createCXString("LinkageSpec");
3026  case CXCursor_CXXBaseSpecifier:
3027    return createCXString("C++ base class specifier");
3028  case CXCursor_Constructor:
3029    return createCXString("CXXConstructor");
3030  case CXCursor_Destructor:
3031    return createCXString("CXXDestructor");
3032  case CXCursor_ConversionFunction:
3033    return createCXString("CXXConversion");
3034  case CXCursor_TemplateTypeParameter:
3035    return createCXString("TemplateTypeParameter");
3036  case CXCursor_NonTypeTemplateParameter:
3037    return createCXString("NonTypeTemplateParameter");
3038  case CXCursor_TemplateTemplateParameter:
3039    return createCXString("TemplateTemplateParameter");
3040  case CXCursor_FunctionTemplate:
3041    return createCXString("FunctionTemplate");
3042  case CXCursor_ClassTemplate:
3043    return createCXString("ClassTemplate");
3044  case CXCursor_ClassTemplatePartialSpecialization:
3045    return createCXString("ClassTemplatePartialSpecialization");
3046  case CXCursor_NamespaceAlias:
3047    return createCXString("NamespaceAlias");
3048  case CXCursor_UsingDirective:
3049    return createCXString("UsingDirective");
3050  case CXCursor_UsingDeclaration:
3051    return createCXString("UsingDeclaration");
3052  }
3053
3054  llvm_unreachable("Unhandled CXCursorKind");
3055  return createCXString(NULL);
3056}
3057
3058enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
3059                                         CXCursor parent,
3060                                         CXClientData client_data) {
3061  CXCursor *BestCursor = static_cast<CXCursor *>(client_data);
3062
3063  // If our current best cursor is the construction of a temporary object,
3064  // don't replace that cursor with a type reference, because we want
3065  // clang_getCursor() to point at the constructor.
3066  if (clang_isExpression(BestCursor->kind) &&
3067      isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
3068      cursor.kind == CXCursor_TypeRef)
3069    return CXChildVisit_Recurse;
3070
3071  *BestCursor = cursor;
3072  return CXChildVisit_Recurse;
3073}
3074
3075CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
3076  if (!TU)
3077    return clang_getNullCursor();
3078
3079  ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
3080  ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3081
3082  // Translate the given source location to make it point at the beginning of
3083  // the token under the cursor.
3084  SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
3085
3086  // Guard against an invalid SourceLocation, or we may assert in one
3087  // of the following calls.
3088  if (SLoc.isInvalid())
3089    return clang_getNullCursor();
3090
3091  bool Logging = getenv("LIBCLANG_LOGGING");
3092  SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
3093                                    CXXUnit->getASTContext().getLangOptions());
3094
3095  CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
3096  if (SLoc.isValid()) {
3097    // FIXME: Would be great to have a "hint" cursor, then walk from that
3098    // hint cursor upward until we find a cursor whose source range encloses
3099    // the region of interest, rather than starting from the translation unit.
3100    CXCursor Parent = clang_getTranslationUnitCursor(CXXUnit);
3101    CursorVisitor CursorVis(CXXUnit, GetCursorVisitor, &Result,
3102                            Decl::MaxPCHLevel, SourceLocation(SLoc));
3103    CursorVis.VisitChildren(Parent);
3104  }
3105
3106  if (Logging) {
3107    CXFile SearchFile;
3108    unsigned SearchLine, SearchColumn;
3109    CXFile ResultFile;
3110    unsigned ResultLine, ResultColumn;
3111    CXString SearchFileName, ResultFileName, KindSpelling;
3112    CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
3113
3114    clang_getInstantiationLocation(Loc, &SearchFile, &SearchLine, &SearchColumn,
3115                                   0);
3116    clang_getInstantiationLocation(ResultLoc, &ResultFile, &ResultLine,
3117                                   &ResultColumn, 0);
3118    SearchFileName = clang_getFileName(SearchFile);
3119    ResultFileName = clang_getFileName(ResultFile);
3120    KindSpelling = clang_getCursorKindSpelling(Result.kind);
3121    fprintf(stderr, "clang_getCursor(%s:%d:%d) = %s(%s:%d:%d)\n",
3122            clang_getCString(SearchFileName), SearchLine, SearchColumn,
3123            clang_getCString(KindSpelling),
3124            clang_getCString(ResultFileName), ResultLine, ResultColumn);
3125    clang_disposeString(SearchFileName);
3126    clang_disposeString(ResultFileName);
3127    clang_disposeString(KindSpelling);
3128  }
3129
3130  return Result;
3131}
3132
3133CXCursor clang_getNullCursor(void) {
3134  return MakeCXCursorInvalid(CXCursor_InvalidFile);
3135}
3136
3137unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
3138  return X == Y;
3139}
3140
3141unsigned clang_isInvalid(enum CXCursorKind K) {
3142  return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
3143}
3144
3145unsigned clang_isDeclaration(enum CXCursorKind K) {
3146  return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
3147}
3148
3149unsigned clang_isReference(enum CXCursorKind K) {
3150  return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
3151}
3152
3153unsigned clang_isExpression(enum CXCursorKind K) {
3154  return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
3155}
3156
3157unsigned clang_isStatement(enum CXCursorKind K) {
3158  return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
3159}
3160
3161unsigned clang_isTranslationUnit(enum CXCursorKind K) {
3162  return K == CXCursor_TranslationUnit;
3163}
3164
3165unsigned clang_isPreprocessing(enum CXCursorKind K) {
3166  return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
3167}
3168
3169unsigned clang_isUnexposed(enum CXCursorKind K) {
3170  switch (K) {
3171    case CXCursor_UnexposedDecl:
3172    case CXCursor_UnexposedExpr:
3173    case CXCursor_UnexposedStmt:
3174    case CXCursor_UnexposedAttr:
3175      return true;
3176    default:
3177      return false;
3178  }
3179}
3180
3181CXCursorKind clang_getCursorKind(CXCursor C) {
3182  return C.kind;
3183}
3184
3185CXSourceLocation clang_getCursorLocation(CXCursor C) {
3186  if (clang_isReference(C.kind)) {
3187    switch (C.kind) {
3188    case CXCursor_ObjCSuperClassRef: {
3189      std::pair<ObjCInterfaceDecl *, SourceLocation> P
3190        = getCursorObjCSuperClassRef(C);
3191      return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3192    }
3193
3194    case CXCursor_ObjCProtocolRef: {
3195      std::pair<ObjCProtocolDecl *, SourceLocation> P
3196        = getCursorObjCProtocolRef(C);
3197      return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3198    }
3199
3200    case CXCursor_ObjCClassRef: {
3201      std::pair<ObjCInterfaceDecl *, SourceLocation> P
3202        = getCursorObjCClassRef(C);
3203      return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3204    }
3205
3206    case CXCursor_TypeRef: {
3207      std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
3208      return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3209    }
3210
3211    case CXCursor_TemplateRef: {
3212      std::pair<TemplateDecl *, SourceLocation> P = getCursorTemplateRef(C);
3213      return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3214    }
3215
3216    case CXCursor_NamespaceRef: {
3217      std::pair<NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
3218      return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3219    }
3220
3221    case CXCursor_MemberRef: {
3222      std::pair<FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
3223      return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3224    }
3225
3226    case CXCursor_CXXBaseSpecifier: {
3227      CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
3228      if (!BaseSpec)
3229        return clang_getNullLocation();
3230
3231      if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
3232        return cxloc::translateSourceLocation(getCursorContext(C),
3233                                            TSInfo->getTypeLoc().getBeginLoc());
3234
3235      return cxloc::translateSourceLocation(getCursorContext(C),
3236                                        BaseSpec->getSourceRange().getBegin());
3237    }
3238
3239    case CXCursor_LabelRef: {
3240      std::pair<LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
3241      return cxloc::translateSourceLocation(getCursorContext(C), P.second);
3242    }
3243
3244    case CXCursor_OverloadedDeclRef:
3245      return cxloc::translateSourceLocation(getCursorContext(C),
3246                                          getCursorOverloadedDeclRef(C).second);
3247
3248    default:
3249      // FIXME: Need a way to enumerate all non-reference cases.
3250      llvm_unreachable("Missed a reference kind");
3251    }
3252  }
3253
3254  if (clang_isExpression(C.kind))
3255    return cxloc::translateSourceLocation(getCursorContext(C),
3256                                   getLocationFromExpr(getCursorExpr(C)));
3257
3258  if (clang_isStatement(C.kind))
3259    return cxloc::translateSourceLocation(getCursorContext(C),
3260                                          getCursorStmt(C)->getLocStart());
3261
3262  if (C.kind == CXCursor_PreprocessingDirective) {
3263    SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
3264    return cxloc::translateSourceLocation(getCursorContext(C), L);
3265  }
3266
3267  if (C.kind == CXCursor_MacroInstantiation) {
3268    SourceLocation L
3269      = cxcursor::getCursorMacroInstantiation(C)->getSourceRange().getBegin();
3270    return cxloc::translateSourceLocation(getCursorContext(C), L);
3271  }
3272
3273  if (C.kind == CXCursor_MacroDefinition) {
3274    SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
3275    return cxloc::translateSourceLocation(getCursorContext(C), L);
3276  }
3277
3278  if (C.kind == CXCursor_InclusionDirective) {
3279    SourceLocation L
3280      = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
3281    return cxloc::translateSourceLocation(getCursorContext(C), L);
3282  }
3283
3284  if (C.kind < CXCursor_FirstDecl || C.kind > CXCursor_LastDecl)
3285    return clang_getNullLocation();
3286
3287  Decl *D = getCursorDecl(C);
3288  SourceLocation Loc = D->getLocation();
3289  if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
3290    Loc = Class->getClassLoc();
3291  // FIXME: Multiple variables declared in a single declaration
3292  // currently lack the information needed to correctly determine their
3293  // ranges when accounting for the type-specifier.  We use context
3294  // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3295  // and if so, whether it is the first decl.
3296  if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3297    if (!cxcursor::isFirstInDeclGroup(C))
3298      Loc = VD->getLocation();
3299  }
3300
3301  return cxloc::translateSourceLocation(getCursorContext(C), Loc);
3302}
3303
3304} // end extern "C"
3305
3306static SourceRange getRawCursorExtent(CXCursor C) {
3307  if (clang_isReference(C.kind)) {
3308    switch (C.kind) {
3309    case CXCursor_ObjCSuperClassRef:
3310      return  getCursorObjCSuperClassRef(C).second;
3311
3312    case CXCursor_ObjCProtocolRef:
3313      return getCursorObjCProtocolRef(C).second;
3314
3315    case CXCursor_ObjCClassRef:
3316      return getCursorObjCClassRef(C).second;
3317
3318    case CXCursor_TypeRef:
3319      return getCursorTypeRef(C).second;
3320
3321    case CXCursor_TemplateRef:
3322      return getCursorTemplateRef(C).second;
3323
3324    case CXCursor_NamespaceRef:
3325      return getCursorNamespaceRef(C).second;
3326
3327    case CXCursor_MemberRef:
3328      return getCursorMemberRef(C).second;
3329
3330    case CXCursor_CXXBaseSpecifier:
3331      return getCursorCXXBaseSpecifier(C)->getSourceRange();
3332
3333    case CXCursor_LabelRef:
3334      return getCursorLabelRef(C).second;
3335
3336    case CXCursor_OverloadedDeclRef:
3337      return getCursorOverloadedDeclRef(C).second;
3338
3339    default:
3340      // FIXME: Need a way to enumerate all non-reference cases.
3341      llvm_unreachable("Missed a reference kind");
3342    }
3343  }
3344
3345  if (clang_isExpression(C.kind))
3346    return getCursorExpr(C)->getSourceRange();
3347
3348  if (clang_isStatement(C.kind))
3349    return getCursorStmt(C)->getSourceRange();
3350
3351  if (C.kind == CXCursor_PreprocessingDirective)
3352    return cxcursor::getCursorPreprocessingDirective(C);
3353
3354  if (C.kind == CXCursor_MacroInstantiation)
3355    return cxcursor::getCursorMacroInstantiation(C)->getSourceRange();
3356
3357  if (C.kind == CXCursor_MacroDefinition)
3358    return cxcursor::getCursorMacroDefinition(C)->getSourceRange();
3359
3360  if (C.kind == CXCursor_InclusionDirective)
3361    return cxcursor::getCursorInclusionDirective(C)->getSourceRange();
3362
3363  if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
3364    Decl *D = cxcursor::getCursorDecl(C);
3365    SourceRange R = D->getSourceRange();
3366    // FIXME: Multiple variables declared in a single declaration
3367    // currently lack the information needed to correctly determine their
3368    // ranges when accounting for the type-specifier.  We use context
3369    // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3370    // and if so, whether it is the first decl.
3371    if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3372      if (!cxcursor::isFirstInDeclGroup(C))
3373        R.setBegin(VD->getLocation());
3374    }
3375    return R;
3376  }
3377  return SourceRange();}
3378
3379extern "C" {
3380
3381CXSourceRange clang_getCursorExtent(CXCursor C) {
3382  SourceRange R = getRawCursorExtent(C);
3383  if (R.isInvalid())
3384    return clang_getNullRange();
3385
3386  return cxloc::translateSourceRange(getCursorContext(C), R);
3387}
3388
3389CXCursor clang_getCursorReferenced(CXCursor C) {
3390  if (clang_isInvalid(C.kind))
3391    return clang_getNullCursor();
3392
3393  ASTUnit *CXXUnit = getCursorASTUnit(C);
3394  if (clang_isDeclaration(C.kind)) {
3395    Decl *D = getCursorDecl(C);
3396    if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
3397      return MakeCursorOverloadedDeclRef(Using, D->getLocation(), CXXUnit);
3398    if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
3399      return MakeCursorOverloadedDeclRef(Classes, D->getLocation(), CXXUnit);
3400    if (ObjCForwardProtocolDecl *Protocols
3401                                        = dyn_cast<ObjCForwardProtocolDecl>(D))
3402      return MakeCursorOverloadedDeclRef(Protocols, D->getLocation(), CXXUnit);
3403
3404    return C;
3405  }
3406
3407  if (clang_isExpression(C.kind)) {
3408    Expr *E = getCursorExpr(C);
3409    Decl *D = getDeclFromExpr(E);
3410    if (D)
3411      return MakeCXCursor(D, CXXUnit);
3412
3413    if (OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
3414      return MakeCursorOverloadedDeclRef(Ovl, CXXUnit);
3415
3416    return clang_getNullCursor();
3417  }
3418
3419  if (clang_isStatement(C.kind)) {
3420    Stmt *S = getCursorStmt(C);
3421    if (GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
3422      return MakeCXCursor(Goto->getLabel(), getCursorDecl(C),
3423                          getCursorASTUnit(C));
3424
3425    return clang_getNullCursor();
3426  }
3427
3428  if (C.kind == CXCursor_MacroInstantiation) {
3429    if (MacroDefinition *Def = getCursorMacroInstantiation(C)->getDefinition())
3430      return MakeMacroDefinitionCursor(Def, CXXUnit);
3431  }
3432
3433  if (!clang_isReference(C.kind))
3434    return clang_getNullCursor();
3435
3436  switch (C.kind) {
3437    case CXCursor_ObjCSuperClassRef:
3438      return MakeCXCursor(getCursorObjCSuperClassRef(C).first, CXXUnit);
3439
3440    case CXCursor_ObjCProtocolRef: {
3441      return MakeCXCursor(getCursorObjCProtocolRef(C).first, CXXUnit);
3442
3443    case CXCursor_ObjCClassRef:
3444      return MakeCXCursor(getCursorObjCClassRef(C).first, CXXUnit);
3445
3446    case CXCursor_TypeRef:
3447      return MakeCXCursor(getCursorTypeRef(C).first, CXXUnit);
3448
3449    case CXCursor_TemplateRef:
3450      return MakeCXCursor(getCursorTemplateRef(C).first, CXXUnit);
3451
3452    case CXCursor_NamespaceRef:
3453      return MakeCXCursor(getCursorNamespaceRef(C).first, CXXUnit);
3454
3455    case CXCursor_MemberRef:
3456      return MakeCXCursor(getCursorMemberRef(C).first, CXXUnit);
3457
3458    case CXCursor_CXXBaseSpecifier: {
3459      CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
3460      return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
3461                                                         CXXUnit));
3462    }
3463
3464    case CXCursor_LabelRef:
3465      // FIXME: We end up faking the "parent" declaration here because we
3466      // don't want to make CXCursor larger.
3467      return MakeCXCursor(getCursorLabelRef(C).first,
3468                          CXXUnit->getASTContext().getTranslationUnitDecl(),
3469                          CXXUnit);
3470
3471    case CXCursor_OverloadedDeclRef:
3472      return C;
3473
3474    default:
3475      // We would prefer to enumerate all non-reference cursor kinds here.
3476      llvm_unreachable("Unhandled reference cursor kind");
3477      break;
3478    }
3479  }
3480
3481  return clang_getNullCursor();
3482}
3483
3484CXCursor clang_getCursorDefinition(CXCursor C) {
3485  if (clang_isInvalid(C.kind))
3486    return clang_getNullCursor();
3487
3488  ASTUnit *CXXUnit = getCursorASTUnit(C);
3489
3490  bool WasReference = false;
3491  if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
3492    C = clang_getCursorReferenced(C);
3493    WasReference = true;
3494  }
3495
3496  if (C.kind == CXCursor_MacroInstantiation)
3497    return clang_getCursorReferenced(C);
3498
3499  if (!clang_isDeclaration(C.kind))
3500    return clang_getNullCursor();
3501
3502  Decl *D = getCursorDecl(C);
3503  if (!D)
3504    return clang_getNullCursor();
3505
3506  switch (D->getKind()) {
3507  // Declaration kinds that don't really separate the notions of
3508  // declaration and definition.
3509  case Decl::Namespace:
3510  case Decl::Typedef:
3511  case Decl::TemplateTypeParm:
3512  case Decl::EnumConstant:
3513  case Decl::Field:
3514  case Decl::ObjCIvar:
3515  case Decl::ObjCAtDefsField:
3516  case Decl::ImplicitParam:
3517  case Decl::ParmVar:
3518  case Decl::NonTypeTemplateParm:
3519  case Decl::TemplateTemplateParm:
3520  case Decl::ObjCCategoryImpl:
3521  case Decl::ObjCImplementation:
3522  case Decl::AccessSpec:
3523  case Decl::LinkageSpec:
3524  case Decl::ObjCPropertyImpl:
3525  case Decl::FileScopeAsm:
3526  case Decl::StaticAssert:
3527  case Decl::Block:
3528    return C;
3529
3530  // Declaration kinds that don't make any sense here, but are
3531  // nonetheless harmless.
3532  case Decl::TranslationUnit:
3533    break;
3534
3535  // Declaration kinds for which the definition is not resolvable.
3536  case Decl::UnresolvedUsingTypename:
3537  case Decl::UnresolvedUsingValue:
3538    break;
3539
3540  case Decl::UsingDirective:
3541    return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
3542                        CXXUnit);
3543
3544  case Decl::NamespaceAlias:
3545    return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), CXXUnit);
3546
3547  case Decl::Enum:
3548  case Decl::Record:
3549  case Decl::CXXRecord:
3550  case Decl::ClassTemplateSpecialization:
3551  case Decl::ClassTemplatePartialSpecialization:
3552    if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
3553      return MakeCXCursor(Def, CXXUnit);
3554    return clang_getNullCursor();
3555
3556  case Decl::Function:
3557  case Decl::CXXMethod:
3558  case Decl::CXXConstructor:
3559  case Decl::CXXDestructor:
3560  case Decl::CXXConversion: {
3561    const FunctionDecl *Def = 0;
3562    if (cast<FunctionDecl>(D)->getBody(Def))
3563      return MakeCXCursor(const_cast<FunctionDecl *>(Def), CXXUnit);
3564    return clang_getNullCursor();
3565  }
3566
3567  case Decl::Var: {
3568    // Ask the variable if it has a definition.
3569    if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
3570      return MakeCXCursor(Def, CXXUnit);
3571    return clang_getNullCursor();
3572  }
3573
3574  case Decl::FunctionTemplate: {
3575    const FunctionDecl *Def = 0;
3576    if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
3577      return MakeCXCursor(Def->getDescribedFunctionTemplate(), CXXUnit);
3578    return clang_getNullCursor();
3579  }
3580
3581  case Decl::ClassTemplate: {
3582    if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
3583                                                            ->getDefinition())
3584      return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
3585                          CXXUnit);
3586    return clang_getNullCursor();
3587  }
3588
3589  case Decl::Using:
3590    return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
3591                                       D->getLocation(), CXXUnit);
3592
3593  case Decl::UsingShadow:
3594    return clang_getCursorDefinition(
3595                       MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
3596                                    CXXUnit));
3597
3598  case Decl::ObjCMethod: {
3599    ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
3600    if (Method->isThisDeclarationADefinition())
3601      return C;
3602
3603    // Dig out the method definition in the associated
3604    // @implementation, if we have it.
3605    // FIXME: The ASTs should make finding the definition easier.
3606    if (ObjCInterfaceDecl *Class
3607                       = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
3608      if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
3609        if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
3610                                                  Method->isInstanceMethod()))
3611          if (Def->isThisDeclarationADefinition())
3612            return MakeCXCursor(Def, CXXUnit);
3613
3614    return clang_getNullCursor();
3615  }
3616
3617  case Decl::ObjCCategory:
3618    if (ObjCCategoryImplDecl *Impl
3619                               = cast<ObjCCategoryDecl>(D)->getImplementation())
3620      return MakeCXCursor(Impl, CXXUnit);
3621    return clang_getNullCursor();
3622
3623  case Decl::ObjCProtocol:
3624    if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
3625      return C;
3626    return clang_getNullCursor();
3627
3628  case Decl::ObjCInterface:
3629    // There are two notions of a "definition" for an Objective-C
3630    // class: the interface and its implementation. When we resolved a
3631    // reference to an Objective-C class, produce the @interface as
3632    // the definition; when we were provided with the interface,
3633    // produce the @implementation as the definition.
3634    if (WasReference) {
3635      if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
3636        return C;
3637    } else if (ObjCImplementationDecl *Impl
3638                              = cast<ObjCInterfaceDecl>(D)->getImplementation())
3639      return MakeCXCursor(Impl, CXXUnit);
3640    return clang_getNullCursor();
3641
3642  case Decl::ObjCProperty:
3643    // FIXME: We don't really know where to find the
3644    // ObjCPropertyImplDecls that implement this property.
3645    return clang_getNullCursor();
3646
3647  case Decl::ObjCCompatibleAlias:
3648    if (ObjCInterfaceDecl *Class
3649          = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
3650      if (!Class->isForwardDecl())
3651        return MakeCXCursor(Class, CXXUnit);
3652
3653    return clang_getNullCursor();
3654
3655  case Decl::ObjCForwardProtocol:
3656    return MakeCursorOverloadedDeclRef(cast<ObjCForwardProtocolDecl>(D),
3657                                       D->getLocation(), CXXUnit);
3658
3659  case Decl::ObjCClass:
3660    return MakeCursorOverloadedDeclRef(cast<ObjCClassDecl>(D), D->getLocation(),
3661                                       CXXUnit);
3662
3663  case Decl::Friend:
3664    if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
3665      return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
3666    return clang_getNullCursor();
3667
3668  case Decl::FriendTemplate:
3669    if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
3670      return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
3671    return clang_getNullCursor();
3672  }
3673
3674  return clang_getNullCursor();
3675}
3676
3677unsigned clang_isCursorDefinition(CXCursor C) {
3678  if (!clang_isDeclaration(C.kind))
3679    return 0;
3680
3681  return clang_getCursorDefinition(C) == C;
3682}
3683
3684unsigned clang_getNumOverloadedDecls(CXCursor C) {
3685  if (C.kind != CXCursor_OverloadedDeclRef)
3686    return 0;
3687
3688  OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
3689  if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
3690    return E->getNumDecls();
3691
3692  if (OverloadedTemplateStorage *S
3693                              = Storage.dyn_cast<OverloadedTemplateStorage*>())
3694    return S->size();
3695
3696  Decl *D = Storage.get<Decl*>();
3697  if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
3698    return Using->shadow_size();
3699  if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
3700    return Classes->size();
3701  if (ObjCForwardProtocolDecl *Protocols =dyn_cast<ObjCForwardProtocolDecl>(D))
3702    return Protocols->protocol_size();
3703
3704  return 0;
3705}
3706
3707CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
3708  if (cursor.kind != CXCursor_OverloadedDeclRef)
3709    return clang_getNullCursor();
3710
3711  if (index >= clang_getNumOverloadedDecls(cursor))
3712    return clang_getNullCursor();
3713
3714  ASTUnit *Unit = getCursorASTUnit(cursor);
3715  OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
3716  if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
3717    return MakeCXCursor(E->decls_begin()[index], Unit);
3718
3719  if (OverloadedTemplateStorage *S
3720                              = Storage.dyn_cast<OverloadedTemplateStorage*>())
3721    return MakeCXCursor(S->begin()[index], Unit);
3722
3723  Decl *D = Storage.get<Decl*>();
3724  if (UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
3725    // FIXME: This is, unfortunately, linear time.
3726    UsingDecl::shadow_iterator Pos = Using->shadow_begin();
3727    std::advance(Pos, index);
3728    return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), Unit);
3729  }
3730
3731  if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
3732    return MakeCXCursor(Classes->begin()[index].getInterface(), Unit);
3733
3734  if (ObjCForwardProtocolDecl *Protocols = dyn_cast<ObjCForwardProtocolDecl>(D))
3735    return MakeCXCursor(Protocols->protocol_begin()[index], Unit);
3736
3737  return clang_getNullCursor();
3738}
3739
3740void clang_getDefinitionSpellingAndExtent(CXCursor C,
3741                                          const char **startBuf,
3742                                          const char **endBuf,
3743                                          unsigned *startLine,
3744                                          unsigned *startColumn,
3745                                          unsigned *endLine,
3746                                          unsigned *endColumn) {
3747  assert(getCursorDecl(C) && "CXCursor has null decl");
3748  NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
3749  FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
3750  CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
3751
3752  SourceManager &SM = FD->getASTContext().getSourceManager();
3753  *startBuf = SM.getCharacterData(Body->getLBracLoc());
3754  *endBuf = SM.getCharacterData(Body->getRBracLoc());
3755  *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
3756  *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
3757  *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
3758  *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
3759}
3760
3761void clang_enableStackTraces(void) {
3762  llvm::sys::PrintStackTraceOnErrorSignal();
3763}
3764
3765void clang_executeOnThread(void (*fn)(void*), void *user_data,
3766                           unsigned stack_size) {
3767  llvm::llvm_execute_on_thread(fn, user_data, stack_size);
3768}
3769
3770} // end: extern "C"
3771
3772//===----------------------------------------------------------------------===//
3773// Token-based Operations.
3774//===----------------------------------------------------------------------===//
3775
3776/* CXToken layout:
3777 *   int_data[0]: a CXTokenKind
3778 *   int_data[1]: starting token location
3779 *   int_data[2]: token length
3780 *   int_data[3]: reserved
3781 *   ptr_data: for identifiers and keywords, an IdentifierInfo*.
3782 *   otherwise unused.
3783 */
3784extern "C" {
3785
3786CXTokenKind clang_getTokenKind(CXToken CXTok) {
3787  return static_cast<CXTokenKind>(CXTok.int_data[0]);
3788}
3789
3790CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
3791  switch (clang_getTokenKind(CXTok)) {
3792  case CXToken_Identifier:
3793  case CXToken_Keyword:
3794    // We know we have an IdentifierInfo*, so use that.
3795    return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
3796                            ->getNameStart());
3797
3798  case CXToken_Literal: {
3799    // We have stashed the starting pointer in the ptr_data field. Use it.
3800    const char *Text = static_cast<const char *>(CXTok.ptr_data);
3801    return createCXString(llvm::StringRef(Text, CXTok.int_data[2]));
3802  }
3803
3804  case CXToken_Punctuation:
3805  case CXToken_Comment:
3806    break;
3807  }
3808
3809  // We have to find the starting buffer pointer the hard way, by
3810  // deconstructing the source location.
3811  ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
3812  if (!CXXUnit)
3813    return createCXString("");
3814
3815  SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
3816  std::pair<FileID, unsigned> LocInfo
3817    = CXXUnit->getSourceManager().getDecomposedLoc(Loc);
3818  bool Invalid = false;
3819  llvm::StringRef Buffer
3820    = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
3821  if (Invalid)
3822    return createCXString("");
3823
3824  return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
3825}
3826
3827CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
3828  ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
3829  if (!CXXUnit)
3830    return clang_getNullLocation();
3831
3832  return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
3833                        SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
3834}
3835
3836CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
3837  ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
3838  if (!CXXUnit)
3839    return clang_getNullRange();
3840
3841  return cxloc::translateSourceRange(CXXUnit->getASTContext(),
3842                        SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
3843}
3844
3845void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
3846                    CXToken **Tokens, unsigned *NumTokens) {
3847  if (Tokens)
3848    *Tokens = 0;
3849  if (NumTokens)
3850    *NumTokens = 0;
3851
3852  ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
3853  if (!CXXUnit || !Tokens || !NumTokens)
3854    return;
3855
3856  ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3857
3858  SourceRange R = cxloc::translateCXSourceRange(Range);
3859  if (R.isInvalid())
3860    return;
3861
3862  SourceManager &SourceMgr = CXXUnit->getSourceManager();
3863  std::pair<FileID, unsigned> BeginLocInfo
3864    = SourceMgr.getDecomposedLoc(R.getBegin());
3865  std::pair<FileID, unsigned> EndLocInfo
3866    = SourceMgr.getDecomposedLoc(R.getEnd());
3867
3868  // Cannot tokenize across files.
3869  if (BeginLocInfo.first != EndLocInfo.first)
3870    return;
3871
3872  // Create a lexer
3873  bool Invalid = false;
3874  llvm::StringRef Buffer
3875    = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
3876  if (Invalid)
3877    return;
3878
3879  Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
3880            CXXUnit->getASTContext().getLangOptions(),
3881            Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
3882  Lex.SetCommentRetentionState(true);
3883
3884  // Lex tokens until we hit the end of the range.
3885  const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
3886  llvm::SmallVector<CXToken, 32> CXTokens;
3887  Token Tok;
3888  bool previousWasAt = false;
3889  do {
3890    // Lex the next token
3891    Lex.LexFromRawLexer(Tok);
3892    if (Tok.is(tok::eof))
3893      break;
3894
3895    // Initialize the CXToken.
3896    CXToken CXTok;
3897
3898    //   - Common fields
3899    CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
3900    CXTok.int_data[2] = Tok.getLength();
3901    CXTok.int_data[3] = 0;
3902
3903    //   - Kind-specific fields
3904    if (Tok.isLiteral()) {
3905      CXTok.int_data[0] = CXToken_Literal;
3906      CXTok.ptr_data = (void *)Tok.getLiteralData();
3907    } else if (Tok.is(tok::identifier)) {
3908      // Lookup the identifier to determine whether we have a keyword.
3909      std::pair<FileID, unsigned> LocInfo
3910        = SourceMgr.getDecomposedLoc(Tok.getLocation());
3911      bool Invalid = false;
3912      llvm::StringRef Buf
3913        = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
3914      if (Invalid)
3915        return;
3916
3917      const char *StartPos = Buf.data() + LocInfo.second;
3918      IdentifierInfo *II
3919        = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok, StartPos);
3920
3921      if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
3922        CXTok.int_data[0] = CXToken_Keyword;
3923      }
3924      else {
3925        CXTok.int_data[0] = II->getTokenID() == tok::identifier?
3926                                CXToken_Identifier
3927                              : CXToken_Keyword;
3928      }
3929      CXTok.ptr_data = II;
3930    } else if (Tok.is(tok::comment)) {
3931      CXTok.int_data[0] = CXToken_Comment;
3932      CXTok.ptr_data = 0;
3933    } else {
3934      CXTok.int_data[0] = CXToken_Punctuation;
3935      CXTok.ptr_data = 0;
3936    }
3937    CXTokens.push_back(CXTok);
3938    previousWasAt = Tok.is(tok::at);
3939  } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
3940
3941  if (CXTokens.empty())
3942    return;
3943
3944  *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
3945  memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
3946  *NumTokens = CXTokens.size();
3947}
3948
3949void clang_disposeTokens(CXTranslationUnit TU,
3950                         CXToken *Tokens, unsigned NumTokens) {
3951  free(Tokens);
3952}
3953
3954} // end: extern "C"
3955
3956//===----------------------------------------------------------------------===//
3957// Token annotation APIs.
3958//===----------------------------------------------------------------------===//
3959
3960typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
3961static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
3962                                                     CXCursor parent,
3963                                                     CXClientData client_data);
3964namespace {
3965class AnnotateTokensWorker {
3966  AnnotateTokensData &Annotated;
3967  CXToken *Tokens;
3968  CXCursor *Cursors;
3969  unsigned NumTokens;
3970  unsigned TokIdx;
3971  unsigned PreprocessingTokIdx;
3972  CursorVisitor AnnotateVis;
3973  SourceManager &SrcMgr;
3974
3975  bool MoreTokens() const { return TokIdx < NumTokens; }
3976  unsigned NextToken() const { return TokIdx; }
3977  void AdvanceToken() { ++TokIdx; }
3978  SourceLocation GetTokenLoc(unsigned tokI) {
3979    return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
3980  }
3981
3982public:
3983  AnnotateTokensWorker(AnnotateTokensData &annotated,
3984                       CXToken *tokens, CXCursor *cursors, unsigned numTokens,
3985                       ASTUnit *CXXUnit, SourceRange RegionOfInterest)
3986    : Annotated(annotated), Tokens(tokens), Cursors(cursors),
3987      NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0),
3988      AnnotateVis(CXXUnit, AnnotateTokensVisitor, this,
3989                  Decl::MaxPCHLevel, RegionOfInterest),
3990      SrcMgr(CXXUnit->getSourceManager()) {}
3991
3992  void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
3993  enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
3994  void AnnotateTokens(CXCursor parent);
3995  void AnnotateTokens() {
3996    AnnotateTokens(clang_getTranslationUnitCursor(AnnotateVis.getASTUnit()));
3997  }
3998};
3999}
4000
4001void AnnotateTokensWorker::AnnotateTokens(CXCursor parent) {
4002  // Walk the AST within the region of interest, annotating tokens
4003  // along the way.
4004  VisitChildren(parent);
4005
4006  for (unsigned I = 0 ; I < TokIdx ; ++I) {
4007    AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
4008    if (Pos != Annotated.end() &&
4009        (clang_isInvalid(Cursors[I].kind) ||
4010         Pos->second.kind != CXCursor_PreprocessingDirective))
4011      Cursors[I] = Pos->second;
4012  }
4013
4014  // Finish up annotating any tokens left.
4015  if (!MoreTokens())
4016    return;
4017
4018  const CXCursor &C = clang_getNullCursor();
4019  for (unsigned I = TokIdx ; I < NumTokens ; ++I) {
4020    AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
4021    Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second;
4022  }
4023}
4024
4025enum CXChildVisitResult
4026AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
4027  CXSourceLocation Loc = clang_getCursorLocation(cursor);
4028  SourceRange cursorRange = getRawCursorExtent(cursor);
4029  if (cursorRange.isInvalid())
4030    return CXChildVisit_Recurse;
4031
4032  if (clang_isPreprocessing(cursor.kind)) {
4033    // For macro instantiations, just note where the beginning of the macro
4034    // instantiation occurs.
4035    if (cursor.kind == CXCursor_MacroInstantiation) {
4036      Annotated[Loc.int_data] = cursor;
4037      return CXChildVisit_Recurse;
4038    }
4039
4040    // Items in the preprocessing record are kept separate from items in
4041    // declarations, so we keep a separate token index.
4042    unsigned SavedTokIdx = TokIdx;
4043    TokIdx = PreprocessingTokIdx;
4044
4045    // Skip tokens up until we catch up to the beginning of the preprocessing
4046    // entry.
4047    while (MoreTokens()) {
4048      const unsigned I = NextToken();
4049      SourceLocation TokLoc = GetTokenLoc(I);
4050      switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4051      case RangeBefore:
4052        AdvanceToken();
4053        continue;
4054      case RangeAfter:
4055      case RangeOverlap:
4056        break;
4057      }
4058      break;
4059    }
4060
4061    // Look at all of the tokens within this range.
4062    while (MoreTokens()) {
4063      const unsigned I = NextToken();
4064      SourceLocation TokLoc = GetTokenLoc(I);
4065      switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4066      case RangeBefore:
4067        assert(0 && "Infeasible");
4068      case RangeAfter:
4069        break;
4070      case RangeOverlap:
4071        Cursors[I] = cursor;
4072        AdvanceToken();
4073        continue;
4074      }
4075      break;
4076    }
4077
4078    // Save the preprocessing token index; restore the non-preprocessing
4079    // token index.
4080    PreprocessingTokIdx = TokIdx;
4081    TokIdx = SavedTokIdx;
4082    return CXChildVisit_Recurse;
4083  }
4084
4085  if (cursorRange.isInvalid())
4086    return CXChildVisit_Continue;
4087
4088  SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data);
4089
4090  // Adjust the annotated range based specific declarations.
4091  const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
4092  if (cursorK >= CXCursor_FirstDecl && cursorK <= CXCursor_LastDecl) {
4093    Decl *D = cxcursor::getCursorDecl(cursor);
4094    // Don't visit synthesized ObjC methods, since they have no syntatic
4095    // representation in the source.
4096    if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
4097      if (MD->isSynthesized())
4098        return CXChildVisit_Continue;
4099    }
4100    if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
4101      if (TypeSourceInfo *TI = DD->getTypeSourceInfo()) {
4102        TypeLoc TL = TI->getTypeLoc();
4103        SourceLocation TLoc = TL.getSourceRange().getBegin();
4104        if (TLoc.isValid() && L.isValid() &&
4105            SrcMgr.isBeforeInTranslationUnit(TLoc, L))
4106          cursorRange.setBegin(TLoc);
4107      }
4108    }
4109  }
4110
4111  // If the location of the cursor occurs within a macro instantiation, record
4112  // the spelling location of the cursor in our annotation map.  We can then
4113  // paper over the token labelings during a post-processing step to try and
4114  // get cursor mappings for tokens that are the *arguments* of a macro
4115  // instantiation.
4116  if (L.isMacroID()) {
4117    unsigned rawEncoding = SrcMgr.getSpellingLoc(L).getRawEncoding();
4118    // Only invalidate the old annotation if it isn't part of a preprocessing
4119    // directive.  Here we assume that the default construction of CXCursor
4120    // results in CXCursor.kind being an initialized value (i.e., 0).  If
4121    // this isn't the case, we can fix by doing lookup + insertion.
4122
4123    CXCursor &oldC = Annotated[rawEncoding];
4124    if (!clang_isPreprocessing(oldC.kind))
4125      oldC = cursor;
4126  }
4127
4128  const enum CXCursorKind K = clang_getCursorKind(parent);
4129  const CXCursor updateC =
4130    (clang_isInvalid(K) || K == CXCursor_TranslationUnit)
4131     ? clang_getNullCursor() : parent;
4132
4133  while (MoreTokens()) {
4134    const unsigned I = NextToken();
4135    SourceLocation TokLoc = GetTokenLoc(I);
4136    switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4137      case RangeBefore:
4138        Cursors[I] = updateC;
4139        AdvanceToken();
4140        continue;
4141      case RangeAfter:
4142      case RangeOverlap:
4143        break;
4144    }
4145    break;
4146  }
4147
4148  // Visit children to get their cursor information.
4149  const unsigned BeforeChildren = NextToken();
4150  VisitChildren(cursor);
4151  const unsigned AfterChildren = NextToken();
4152
4153  // Adjust 'Last' to the last token within the extent of the cursor.
4154  while (MoreTokens()) {
4155    const unsigned I = NextToken();
4156    SourceLocation TokLoc = GetTokenLoc(I);
4157    switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4158      case RangeBefore:
4159        assert(0 && "Infeasible");
4160      case RangeAfter:
4161        break;
4162      case RangeOverlap:
4163        Cursors[I] = updateC;
4164        AdvanceToken();
4165        continue;
4166    }
4167    break;
4168  }
4169  const unsigned Last = NextToken();
4170
4171  // Scan the tokens that are at the beginning of the cursor, but are not
4172  // capture by the child cursors.
4173
4174  // For AST elements within macros, rely on a post-annotate pass to
4175  // to correctly annotate the tokens with cursors.  Otherwise we can
4176  // get confusing results of having tokens that map to cursors that really
4177  // are expanded by an instantiation.
4178  if (L.isMacroID())
4179    cursor = clang_getNullCursor();
4180
4181  for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
4182    if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
4183      break;
4184
4185    Cursors[I] = cursor;
4186  }
4187  // Scan the tokens that are at the end of the cursor, but are not captured
4188  // but the child cursors.
4189  for (unsigned I = AfterChildren; I != Last; ++I)
4190    Cursors[I] = cursor;
4191
4192  TokIdx = Last;
4193  return CXChildVisit_Continue;
4194}
4195
4196static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
4197                                                     CXCursor parent,
4198                                                     CXClientData client_data) {
4199  return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
4200}
4201
4202// This gets run a separate thread to avoid stack blowout.
4203static void runAnnotateTokensWorker(void *UserData) {
4204  ((AnnotateTokensWorker*)UserData)->AnnotateTokens();
4205}
4206
4207extern "C" {
4208
4209void clang_annotateTokens(CXTranslationUnit TU,
4210                          CXToken *Tokens, unsigned NumTokens,
4211                          CXCursor *Cursors) {
4212
4213  if (NumTokens == 0 || !Tokens || !Cursors)
4214    return;
4215
4216  // Any token we don't specifically annotate will have a NULL cursor.
4217  CXCursor C = clang_getNullCursor();
4218  for (unsigned I = 0; I != NumTokens; ++I)
4219    Cursors[I] = C;
4220
4221  ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
4222  if (!CXXUnit)
4223    return;
4224
4225  ASTUnit::ConcurrencyCheck Check(*CXXUnit);
4226
4227  // Determine the region of interest, which contains all of the tokens.
4228  SourceRange RegionOfInterest;
4229  RegionOfInterest.setBegin(cxloc::translateSourceLocation(
4230                                        clang_getTokenLocation(TU, Tokens[0])));
4231  RegionOfInterest.setEnd(cxloc::translateSourceLocation(
4232                                clang_getTokenLocation(TU,
4233                                                       Tokens[NumTokens - 1])));
4234
4235  // A mapping from the source locations found when re-lexing or traversing the
4236  // region of interest to the corresponding cursors.
4237  AnnotateTokensData Annotated;
4238
4239  // Relex the tokens within the source range to look for preprocessing
4240  // directives.
4241  SourceManager &SourceMgr = CXXUnit->getSourceManager();
4242  std::pair<FileID, unsigned> BeginLocInfo
4243    = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
4244  std::pair<FileID, unsigned> EndLocInfo
4245    = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
4246
4247  llvm::StringRef Buffer;
4248  bool Invalid = false;
4249  if (BeginLocInfo.first == EndLocInfo.first &&
4250      ((Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid)),true) &&
4251      !Invalid) {
4252    Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
4253              CXXUnit->getASTContext().getLangOptions(),
4254              Buffer.begin(), Buffer.data() + BeginLocInfo.second,
4255              Buffer.end());
4256    Lex.SetCommentRetentionState(true);
4257
4258    // Lex tokens in raw mode until we hit the end of the range, to avoid
4259    // entering #includes or expanding macros.
4260    while (true) {
4261      Token Tok;
4262      Lex.LexFromRawLexer(Tok);
4263
4264    reprocess:
4265      if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
4266        // We have found a preprocessing directive. Gobble it up so that we
4267        // don't see it while preprocessing these tokens later, but keep track
4268        // of all of the token locations inside this preprocessing directive so
4269        // that we can annotate them appropriately.
4270        //
4271        // FIXME: Some simple tests here could identify macro definitions and
4272        // #undefs, to provide specific cursor kinds for those.
4273        std::vector<SourceLocation> Locations;
4274        do {
4275          Locations.push_back(Tok.getLocation());
4276          Lex.LexFromRawLexer(Tok);
4277        } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
4278
4279        using namespace cxcursor;
4280        CXCursor Cursor
4281          = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
4282                                                         Locations.back()),
4283                                           CXXUnit);
4284        for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
4285          Annotated[Locations[I].getRawEncoding()] = Cursor;
4286        }
4287
4288        if (Tok.isAtStartOfLine())
4289          goto reprocess;
4290
4291        continue;
4292      }
4293
4294      if (Tok.is(tok::eof))
4295        break;
4296    }
4297  }
4298
4299  // Annotate all of the source locations in the region of interest that map to
4300  // a specific cursor.
4301  AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens,
4302                         CXXUnit, RegionOfInterest);
4303
4304  // Run the worker within a CrashRecoveryContext.
4305  llvm::CrashRecoveryContext CRC;
4306  if (!RunSafely(CRC, runAnnotateTokensWorker, &W)) {
4307    fprintf(stderr, "libclang: crash detected while annotating tokens\n");
4308  }
4309}
4310} // end: extern "C"
4311
4312//===----------------------------------------------------------------------===//
4313// Operations for querying linkage of a cursor.
4314//===----------------------------------------------------------------------===//
4315
4316extern "C" {
4317CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
4318  if (!clang_isDeclaration(cursor.kind))
4319    return CXLinkage_Invalid;
4320
4321  Decl *D = cxcursor::getCursorDecl(cursor);
4322  if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
4323    switch (ND->getLinkage()) {
4324      case NoLinkage: return CXLinkage_NoLinkage;
4325      case InternalLinkage: return CXLinkage_Internal;
4326      case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
4327      case ExternalLinkage: return CXLinkage_External;
4328    };
4329
4330  return CXLinkage_Invalid;
4331}
4332} // end: extern "C"
4333
4334//===----------------------------------------------------------------------===//
4335// Operations for querying language of a cursor.
4336//===----------------------------------------------------------------------===//
4337
4338static CXLanguageKind getDeclLanguage(const Decl *D) {
4339  switch (D->getKind()) {
4340    default:
4341      break;
4342    case Decl::ImplicitParam:
4343    case Decl::ObjCAtDefsField:
4344    case Decl::ObjCCategory:
4345    case Decl::ObjCCategoryImpl:
4346    case Decl::ObjCClass:
4347    case Decl::ObjCCompatibleAlias:
4348    case Decl::ObjCForwardProtocol:
4349    case Decl::ObjCImplementation:
4350    case Decl::ObjCInterface:
4351    case Decl::ObjCIvar:
4352    case Decl::ObjCMethod:
4353    case Decl::ObjCProperty:
4354    case Decl::ObjCPropertyImpl:
4355    case Decl::ObjCProtocol:
4356      return CXLanguage_ObjC;
4357    case Decl::CXXConstructor:
4358    case Decl::CXXConversion:
4359    case Decl::CXXDestructor:
4360    case Decl::CXXMethod:
4361    case Decl::CXXRecord:
4362    case Decl::ClassTemplate:
4363    case Decl::ClassTemplatePartialSpecialization:
4364    case Decl::ClassTemplateSpecialization:
4365    case Decl::Friend:
4366    case Decl::FriendTemplate:
4367    case Decl::FunctionTemplate:
4368    case Decl::LinkageSpec:
4369    case Decl::Namespace:
4370    case Decl::NamespaceAlias:
4371    case Decl::NonTypeTemplateParm:
4372    case Decl::StaticAssert:
4373    case Decl::TemplateTemplateParm:
4374    case Decl::TemplateTypeParm:
4375    case Decl::UnresolvedUsingTypename:
4376    case Decl::UnresolvedUsingValue:
4377    case Decl::Using:
4378    case Decl::UsingDirective:
4379    case Decl::UsingShadow:
4380      return CXLanguage_CPlusPlus;
4381  }
4382
4383  return CXLanguage_C;
4384}
4385
4386extern "C" {
4387
4388enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
4389  if (clang_isDeclaration(cursor.kind))
4390    if (Decl *D = cxcursor::getCursorDecl(cursor)) {
4391      if (D->hasAttr<UnavailableAttr>() ||
4392          (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted()))
4393        return CXAvailability_Available;
4394
4395      if (D->hasAttr<DeprecatedAttr>())
4396        return CXAvailability_Deprecated;
4397    }
4398
4399  return CXAvailability_Available;
4400}
4401
4402CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
4403  if (clang_isDeclaration(cursor.kind))
4404    return getDeclLanguage(cxcursor::getCursorDecl(cursor));
4405
4406  return CXLanguage_Invalid;
4407}
4408
4409CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
4410  if (clang_isDeclaration(cursor.kind)) {
4411    if (Decl *D = getCursorDecl(cursor)) {
4412      DeclContext *DC = D->getDeclContext();
4413      return MakeCXCursor(cast<Decl>(DC), getCursorASTUnit(cursor));
4414    }
4415  }
4416
4417  if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
4418    if (Decl *D = getCursorDecl(cursor))
4419      return MakeCXCursor(D, getCursorASTUnit(cursor));
4420  }
4421
4422  return clang_getNullCursor();
4423}
4424
4425CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
4426  if (clang_isDeclaration(cursor.kind)) {
4427    if (Decl *D = getCursorDecl(cursor)) {
4428      DeclContext *DC = D->getLexicalDeclContext();
4429      return MakeCXCursor(cast<Decl>(DC), getCursorASTUnit(cursor));
4430    }
4431  }
4432
4433  // FIXME: Note that we can't easily compute the lexical context of a
4434  // statement or expression, so we return nothing.
4435  return clang_getNullCursor();
4436}
4437
4438static void CollectOverriddenMethods(DeclContext *Ctx,
4439                                     ObjCMethodDecl *Method,
4440                            llvm::SmallVectorImpl<ObjCMethodDecl *> &Methods) {
4441  if (!Ctx)
4442    return;
4443
4444  // If we have a class or category implementation, jump straight to the
4445  // interface.
4446  if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(Ctx))
4447    return CollectOverriddenMethods(Impl->getClassInterface(), Method, Methods);
4448
4449  ObjCContainerDecl *Container = dyn_cast<ObjCContainerDecl>(Ctx);
4450  if (!Container)
4451    return;
4452
4453  // Check whether we have a matching method at this level.
4454  if (ObjCMethodDecl *Overridden = Container->getMethod(Method->getSelector(),
4455                                                    Method->isInstanceMethod()))
4456    if (Method != Overridden) {
4457      // We found an override at this level; there is no need to look
4458      // into other protocols or categories.
4459      Methods.push_back(Overridden);
4460      return;
4461    }
4462
4463  if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
4464    for (ObjCProtocolDecl::protocol_iterator P = Protocol->protocol_begin(),
4465                                          PEnd = Protocol->protocol_end();
4466         P != PEnd; ++P)
4467      CollectOverriddenMethods(*P, Method, Methods);
4468  }
4469
4470  if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Container)) {
4471    for (ObjCCategoryDecl::protocol_iterator P = Category->protocol_begin(),
4472                                          PEnd = Category->protocol_end();
4473         P != PEnd; ++P)
4474      CollectOverriddenMethods(*P, Method, Methods);
4475  }
4476
4477  if (ObjCInterfaceDecl *Interface = dyn_cast<ObjCInterfaceDecl>(Container)) {
4478    for (ObjCInterfaceDecl::protocol_iterator P = Interface->protocol_begin(),
4479                                           PEnd = Interface->protocol_end();
4480         P != PEnd; ++P)
4481      CollectOverriddenMethods(*P, Method, Methods);
4482
4483    for (ObjCCategoryDecl *Category = Interface->getCategoryList();
4484         Category; Category = Category->getNextClassCategory())
4485      CollectOverriddenMethods(Category, Method, Methods);
4486
4487    // We only look into the superclass if we haven't found anything yet.
4488    if (Methods.empty())
4489      if (ObjCInterfaceDecl *Super = Interface->getSuperClass())
4490        return CollectOverriddenMethods(Super, Method, Methods);
4491  }
4492}
4493
4494void clang_getOverriddenCursors(CXCursor cursor,
4495                                CXCursor **overridden,
4496                                unsigned *num_overridden) {
4497  if (overridden)
4498    *overridden = 0;
4499  if (num_overridden)
4500    *num_overridden = 0;
4501  if (!overridden || !num_overridden)
4502    return;
4503
4504  if (!clang_isDeclaration(cursor.kind))
4505    return;
4506
4507  Decl *D = getCursorDecl(cursor);
4508  if (!D)
4509    return;
4510
4511  // Handle C++ member functions.
4512  ASTUnit *CXXUnit = getCursorASTUnit(cursor);
4513  if (CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
4514    *num_overridden = CXXMethod->size_overridden_methods();
4515    if (!*num_overridden)
4516      return;
4517
4518    *overridden = new CXCursor [*num_overridden];
4519    unsigned I = 0;
4520    for (CXXMethodDecl::method_iterator
4521              M = CXXMethod->begin_overridden_methods(),
4522           MEnd = CXXMethod->end_overridden_methods();
4523         M != MEnd; (void)++M, ++I)
4524      (*overridden)[I] = MakeCXCursor(const_cast<CXXMethodDecl*>(*M), CXXUnit);
4525    return;
4526  }
4527
4528  ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
4529  if (!Method)
4530    return;
4531
4532  // Handle Objective-C methods.
4533  llvm::SmallVector<ObjCMethodDecl *, 4> Methods;
4534  CollectOverriddenMethods(Method->getDeclContext(), Method, Methods);
4535
4536  if (Methods.empty())
4537    return;
4538
4539  *num_overridden = Methods.size();
4540  *overridden = new CXCursor [Methods.size()];
4541  for (unsigned I = 0, N = Methods.size(); I != N; ++I)
4542    (*overridden)[I] = MakeCXCursor(Methods[I], CXXUnit);
4543}
4544
4545void clang_disposeOverriddenCursors(CXCursor *overridden) {
4546  delete [] overridden;
4547}
4548
4549CXFile clang_getIncludedFile(CXCursor cursor) {
4550  if (cursor.kind != CXCursor_InclusionDirective)
4551    return 0;
4552
4553  InclusionDirective *ID = getCursorInclusionDirective(cursor);
4554  return (void *)ID->getFile();
4555}
4556
4557} // end: extern "C"
4558
4559
4560//===----------------------------------------------------------------------===//
4561// C++ AST instrospection.
4562//===----------------------------------------------------------------------===//
4563
4564extern "C" {
4565unsigned clang_CXXMethod_isStatic(CXCursor C) {
4566  if (!clang_isDeclaration(C.kind))
4567    return 0;
4568
4569  CXXMethodDecl *Method = 0;
4570  Decl *D = cxcursor::getCursorDecl(C);
4571  if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
4572    Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
4573  else
4574    Method = dyn_cast_or_null<CXXMethodDecl>(D);
4575  return (Method && Method->isStatic()) ? 1 : 0;
4576}
4577
4578} // end: extern "C"
4579
4580//===----------------------------------------------------------------------===//
4581// Attribute introspection.
4582//===----------------------------------------------------------------------===//
4583
4584extern "C" {
4585CXType clang_getIBOutletCollectionType(CXCursor C) {
4586  if (C.kind != CXCursor_IBOutletCollectionAttr)
4587    return cxtype::MakeCXType(QualType(), cxcursor::getCursorASTUnit(C));
4588
4589  IBOutletCollectionAttr *A =
4590    cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
4591
4592  return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorASTUnit(C));
4593}
4594} // end: extern "C"
4595
4596//===----------------------------------------------------------------------===//
4597// CXString Operations.
4598//===----------------------------------------------------------------------===//
4599
4600extern "C" {
4601const char *clang_getCString(CXString string) {
4602  return string.Spelling;
4603}
4604
4605void clang_disposeString(CXString string) {
4606  if (string.MustFreeString && string.Spelling)
4607    free((void*)string.Spelling);
4608}
4609
4610} // end: extern "C"
4611
4612namespace clang { namespace cxstring {
4613CXString createCXString(const char *String, bool DupString){
4614  CXString Str;
4615  if (DupString) {
4616    Str.Spelling = strdup(String);
4617    Str.MustFreeString = 1;
4618  } else {
4619    Str.Spelling = String;
4620    Str.MustFreeString = 0;
4621  }
4622  return Str;
4623}
4624
4625CXString createCXString(llvm::StringRef String, bool DupString) {
4626  CXString Result;
4627  if (DupString || (!String.empty() && String.data()[String.size()] != 0)) {
4628    char *Spelling = (char *)malloc(String.size() + 1);
4629    memmove(Spelling, String.data(), String.size());
4630    Spelling[String.size()] = 0;
4631    Result.Spelling = Spelling;
4632    Result.MustFreeString = 1;
4633  } else {
4634    Result.Spelling = String.data();
4635    Result.MustFreeString = 0;
4636  }
4637  return Result;
4638}
4639}}
4640
4641//===----------------------------------------------------------------------===//
4642// Misc. utility functions.
4643//===----------------------------------------------------------------------===//
4644
4645/// Default to using an 8 MB stack size on "safety" threads.
4646static unsigned SafetyStackThreadSize = 8 << 20;
4647
4648namespace clang {
4649
4650bool RunSafely(llvm::CrashRecoveryContext &CRC,
4651               void (*Fn)(void*), void *UserData) {
4652  if (unsigned Size = GetSafetyThreadStackSize())
4653    return CRC.RunSafelyOnThread(Fn, UserData, Size);
4654  return CRC.RunSafely(Fn, UserData);
4655}
4656
4657unsigned GetSafetyThreadStackSize() {
4658  return SafetyStackThreadSize;
4659}
4660
4661void SetSafetyThreadStackSize(unsigned Value) {
4662  SafetyStackThreadSize = Value;
4663}
4664
4665}
4666
4667extern "C" {
4668
4669CXString clang_getClangVersion() {
4670  return createCXString(getClangFullVersion());
4671}
4672
4673} // end: extern "C"
4674