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