CIndex.cpp revision e4979ccb5960608edce73f3b274eb7c2de15dac5
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 VisitBlockExpr(BlockExpr *B);
316  bool VisitObjCEncodeExpr(ObjCEncodeExpr *E);
317  bool VisitOffsetOfExpr(OffsetOfExpr *E);
318  bool VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E);
319  bool VisitAddrLabelExpr(AddrLabelExpr *E);
320  bool VisitTypesCompatibleExpr(TypesCompatibleExpr *E);
321  bool VisitVAArgExpr(VAArgExpr *E);
322  bool VisitDesignatedInitExpr(DesignatedInitExpr *E);
323  bool VisitCXXTypeidExpr(CXXTypeidExpr *E);
324  bool VisitCXXUuidofExpr(CXXUuidofExpr *E);
325  bool VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { return false; }
326  bool VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E);
327  bool VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
328  bool VisitCXXNewExpr(CXXNewExpr *E);
329  bool VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E);
330  bool VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E);
331  bool VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E);
332  bool VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr *E);
333  bool VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E);
334
335#define DATA_RECURSIVE_VISIT(NAME)\
336bool Visit##NAME(NAME *S) { return VisitDataRecursive(S); }
337  DATA_RECURSIVE_VISIT(BinaryOperator)
338  DATA_RECURSIVE_VISIT(CompoundLiteralExpr)
339  DATA_RECURSIVE_VISIT(CXXMemberCallExpr)
340  DATA_RECURSIVE_VISIT(CXXOperatorCallExpr)
341  DATA_RECURSIVE_VISIT(DeclRefExpr)
342  DATA_RECURSIVE_VISIT(DeclStmt)
343  DATA_RECURSIVE_VISIT(ExplicitCastExpr)
344  DATA_RECURSIVE_VISIT(DoStmt)
345  DATA_RECURSIVE_VISIT(IfStmt)
346  DATA_RECURSIVE_VISIT(InitListExpr)
347  DATA_RECURSIVE_VISIT(ForStmt)
348  DATA_RECURSIVE_VISIT(GotoStmt)
349  DATA_RECURSIVE_VISIT(MemberExpr)
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
1454
1455bool CursorVisitor::VisitBlockExpr(BlockExpr *B) {
1456  return Visit(B->getBlockDecl());
1457}
1458
1459bool CursorVisitor::VisitOffsetOfExpr(OffsetOfExpr *E) {
1460  // Visit the type into which we're computing an offset.
1461  if (Visit(E->getTypeSourceInfo()->getTypeLoc()))
1462    return true;
1463
1464  // Visit the components of the offsetof expression.
1465  for (unsigned I = 0, N = E->getNumComponents(); I != N; ++I) {
1466    typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
1467    const OffsetOfNode &Node = E->getComponent(I);
1468    switch (Node.getKind()) {
1469    case OffsetOfNode::Array:
1470      if (Visit(MakeCXCursor(E->getIndexExpr(Node.getArrayExprIndex()),
1471                             StmtParent, TU)))
1472        return true;
1473      break;
1474
1475    case OffsetOfNode::Field:
1476      if (Visit(MakeCursorMemberRef(Node.getField(), Node.getRange().getEnd(),
1477                                    TU)))
1478        return true;
1479      break;
1480
1481    case OffsetOfNode::Identifier:
1482    case OffsetOfNode::Base:
1483      continue;
1484    }
1485  }
1486
1487  return false;
1488}
1489
1490bool CursorVisitor::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E) {
1491  if (E->isArgumentType()) {
1492    if (TypeSourceInfo *TSInfo = E->getArgumentTypeInfo())
1493      return Visit(TSInfo->getTypeLoc());
1494
1495    return false;
1496  }
1497
1498  return VisitExpr(E);
1499}
1500
1501bool CursorVisitor::VisitAddrLabelExpr(AddrLabelExpr *E) {
1502  return Visit(MakeCursorLabelRef(E->getLabel(), E->getLabelLoc(), TU));
1503}
1504
1505bool CursorVisitor::VisitTypesCompatibleExpr(TypesCompatibleExpr *E) {
1506  return Visit(E->getArgTInfo1()->getTypeLoc()) ||
1507         Visit(E->getArgTInfo2()->getTypeLoc());
1508}
1509
1510bool CursorVisitor::VisitVAArgExpr(VAArgExpr *E) {
1511  if (Visit(E->getWrittenTypeInfo()->getTypeLoc()))
1512    return true;
1513
1514  return Visit(MakeCXCursor(E->getSubExpr(), StmtParent, TU));
1515}
1516
1517bool CursorVisitor::VisitDesignatedInitExpr(DesignatedInitExpr *E) {
1518  // Visit the designators.
1519  typedef DesignatedInitExpr::Designator Designator;
1520  for (DesignatedInitExpr::designators_iterator D = E->designators_begin(),
1521                                             DEnd = E->designators_end();
1522       D != DEnd; ++D) {
1523    if (D->isFieldDesignator()) {
1524      if (FieldDecl *Field = D->getField())
1525        if (Visit(MakeCursorMemberRef(Field, D->getFieldLoc(), TU)))
1526          return true;
1527
1528      continue;
1529    }
1530
1531    if (D->isArrayDesignator()) {
1532      if (Visit(MakeCXCursor(E->getArrayIndex(*D), StmtParent, TU)))
1533        return true;
1534
1535      continue;
1536    }
1537
1538    assert(D->isArrayRangeDesignator() && "Unknown designator kind");
1539    if (Visit(MakeCXCursor(E->getArrayRangeStart(*D), StmtParent, TU)) ||
1540        Visit(MakeCXCursor(E->getArrayRangeEnd(*D), StmtParent, TU)))
1541      return true;
1542  }
1543
1544  // Visit the initializer value itself.
1545  return Visit(MakeCXCursor(E->getInit(), StmtParent, TU));
1546}
1547
1548bool CursorVisitor::VisitCXXTypeidExpr(CXXTypeidExpr *E) {
1549  if (E->isTypeOperand()) {
1550    if (TypeSourceInfo *TSInfo = E->getTypeOperandSourceInfo())
1551      return Visit(TSInfo->getTypeLoc());
1552
1553    return false;
1554  }
1555
1556  return VisitExpr(E);
1557}
1558
1559bool CursorVisitor::VisitCXXUuidofExpr(CXXUuidofExpr *E) {
1560  if (E->isTypeOperand()) {
1561    if (TypeSourceInfo *TSInfo = E->getTypeOperandSourceInfo())
1562      return Visit(TSInfo->getTypeLoc());
1563
1564    return false;
1565  }
1566
1567  return VisitExpr(E);
1568}
1569
1570bool CursorVisitor::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E) {
1571  if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
1572    if (Visit(TSInfo->getTypeLoc()))
1573      return true;
1574
1575  return VisitExpr(E);
1576}
1577
1578bool CursorVisitor::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
1579  if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
1580    return Visit(TSInfo->getTypeLoc());
1581
1582  return false;
1583}
1584
1585bool CursorVisitor::VisitCXXNewExpr(CXXNewExpr *E) {
1586  // Visit placement arguments.
1587  for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I)
1588    if (Visit(MakeCXCursor(E->getPlacementArg(I), StmtParent, TU)))
1589      return true;
1590
1591  // Visit the allocated type.
1592  if (TypeSourceInfo *TSInfo = E->getAllocatedTypeSourceInfo())
1593    if (Visit(TSInfo->getTypeLoc()))
1594      return true;
1595
1596  // Visit the array size, if any.
1597  if (E->isArray() && Visit(MakeCXCursor(E->getArraySize(), StmtParent, TU)))
1598    return true;
1599
1600  // Visit the initializer or constructor arguments.
1601  for (unsigned I = 0, N = E->getNumConstructorArgs(); I != N; ++I)
1602    if (Visit(MakeCXCursor(E->getConstructorArg(I), StmtParent, TU)))
1603      return true;
1604
1605  return false;
1606}
1607
1608bool CursorVisitor::VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E) {
1609  // Visit base expression.
1610  if (Visit(MakeCXCursor(E->getBase(), StmtParent, TU)))
1611    return true;
1612
1613  // Visit the nested-name-specifier.
1614  if (NestedNameSpecifier *Qualifier = E->getQualifier())
1615    if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1616      return true;
1617
1618  // Visit the scope type that looks disturbingly like the nested-name-specifier
1619  // but isn't.
1620  if (TypeSourceInfo *TSInfo = E->getScopeTypeInfo())
1621    if (Visit(TSInfo->getTypeLoc()))
1622      return true;
1623
1624  // Visit the name of the type being destroyed.
1625  if (TypeSourceInfo *TSInfo = E->getDestroyedTypeInfo())
1626    if (Visit(TSInfo->getTypeLoc()))
1627      return true;
1628
1629  return false;
1630}
1631
1632bool CursorVisitor::VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E) {
1633  return Visit(E->getQueriedTypeSourceInfo()->getTypeLoc());
1634}
1635
1636bool CursorVisitor::VisitDependentScopeDeclRefExpr(
1637                                                DependentScopeDeclRefExpr *E) {
1638  // Visit the nested-name-specifier.
1639  if (NestedNameSpecifier *Qualifier = E->getQualifier())
1640    if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1641      return true;
1642
1643  // Visit the declaration name.
1644  if (VisitDeclarationNameInfo(E->getNameInfo()))
1645    return true;
1646
1647  // Visit the explicitly-specified template arguments.
1648  if (const ExplicitTemplateArgumentList *ArgList
1649      = E->getOptionalExplicitTemplateArgs()) {
1650    for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
1651         *ArgEnd = Arg + ArgList->NumTemplateArgs;
1652         Arg != ArgEnd; ++Arg) {
1653      if (VisitTemplateArgumentLoc(*Arg))
1654        return true;
1655    }
1656  }
1657
1658  return false;
1659}
1660
1661bool CursorVisitor::VisitCXXUnresolvedConstructExpr(
1662                                                CXXUnresolvedConstructExpr *E) {
1663  if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
1664    if (Visit(TSInfo->getTypeLoc()))
1665      return true;
1666
1667  return VisitExpr(E);
1668}
1669
1670bool CursorVisitor::VisitCXXDependentScopeMemberExpr(
1671                                              CXXDependentScopeMemberExpr *E) {
1672  // Visit the base expression, if there is one.
1673  if (!E->isImplicitAccess() &&
1674      Visit(MakeCXCursor(E->getBase(), StmtParent, TU)))
1675    return true;
1676
1677  // Visit the nested-name-specifier.
1678  if (NestedNameSpecifier *Qualifier = E->getQualifier())
1679    if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1680      return true;
1681
1682  // Visit the declaration name.
1683  if (VisitDeclarationNameInfo(E->getMemberNameInfo()))
1684    return true;
1685
1686  // Visit the explicitly-specified template arguments.
1687  if (const ExplicitTemplateArgumentList *ArgList
1688      = E->getOptionalExplicitTemplateArgs()) {
1689    for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
1690         *ArgEnd = Arg + ArgList->NumTemplateArgs;
1691         Arg != ArgEnd; ++Arg) {
1692      if (VisitTemplateArgumentLoc(*Arg))
1693        return true;
1694    }
1695  }
1696
1697  return false;
1698}
1699
1700bool CursorVisitor::VisitObjCEncodeExpr(ObjCEncodeExpr *E) {
1701  return Visit(E->getEncodedTypeSourceInfo()->getTypeLoc());
1702}
1703
1704
1705bool CursorVisitor::VisitAttributes(Decl *D) {
1706  for (AttrVec::const_iterator i = D->attr_begin(), e = D->attr_end();
1707       i != e; ++i)
1708    if (Visit(MakeCXCursor(*i, D, TU)))
1709        return true;
1710
1711  return false;
1712}
1713
1714//===----------------------------------------------------------------------===//
1715// Data-recursive visitor methods.
1716//===----------------------------------------------------------------------===//
1717
1718namespace {
1719#define DEF_JOB(NAME, DATA, KIND)\
1720class NAME : public VisitorJob {\
1721public:\
1722  NAME(DATA *d, CXCursor parent) : VisitorJob(parent, VisitorJob::KIND, d) {} \
1723  static bool classof(const VisitorJob *VJ) { return VJ->getKind() == KIND; }\
1724  DATA *get() const { return static_cast<DATA*>(dataA); }\
1725};
1726
1727DEF_JOB(StmtVisit, Stmt, StmtVisitKind)
1728DEF_JOB(MemberExprParts, MemberExpr, MemberExprPartsKind)
1729DEF_JOB(DeclRefExprParts, DeclRefExpr, DeclRefExprPartsKind)
1730DEF_JOB(OverloadExprParts, OverloadExpr, OverloadExprPartsKind)
1731#undef DEF_JOB
1732
1733class DeclVisit : public VisitorJob {
1734public:
1735  DeclVisit(Decl *d, CXCursor parent, bool isFirst) :
1736    VisitorJob(parent, VisitorJob::DeclVisitKind,
1737               d, isFirst ? (void*) 1 : (void*) 0) {}
1738  static bool classof(const VisitorJob *VJ) {
1739    return VJ->getKind () == DeclVisitKind;
1740  }
1741  Decl *get() { return static_cast<Decl*>(dataA);}
1742  bool isFirst() const { return dataB ? true : false; }
1743};
1744
1745class TypeLocVisit : public VisitorJob {
1746public:
1747  TypeLocVisit(TypeLoc tl, CXCursor parent) :
1748    VisitorJob(parent, VisitorJob::TypeLocVisitKind,
1749               tl.getType().getAsOpaquePtr(), tl.getOpaqueData()) {}
1750
1751  static bool classof(const VisitorJob *VJ) {
1752    return VJ->getKind() == TypeLocVisitKind;
1753  }
1754
1755  TypeLoc get() {
1756    QualType T = QualType::getFromOpaquePtr(dataA);
1757    return TypeLoc(T, dataB);
1758  }
1759};
1760
1761class EnqueueVisitor : public StmtVisitor<EnqueueVisitor, void> {
1762  VisitorWorkList &WL;
1763  CXCursor Parent;
1764public:
1765  EnqueueVisitor(VisitorWorkList &wl, CXCursor parent)
1766    : WL(wl), Parent(parent) {}
1767
1768  void VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
1769  void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E);
1770  void VisitDeclRefExpr(DeclRefExpr *D);
1771  void VisitDeclStmt(DeclStmt *S);
1772  void VisitExplicitCastExpr(ExplicitCastExpr *E);
1773  void VisitForStmt(ForStmt *FS);
1774  void VisitIfStmt(IfStmt *If);
1775  void VisitInitListExpr(InitListExpr *IE);
1776  void VisitMemberExpr(MemberExpr *M);
1777  void VisitObjCMessageExpr(ObjCMessageExpr *M);
1778  void VisitOverloadExpr(OverloadExpr *E);
1779  void VisitStmt(Stmt *S);
1780  void VisitSwitchStmt(SwitchStmt *S);
1781  void VisitWhileStmt(WhileStmt *W);
1782  void VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U);
1783
1784private:
1785  void AddStmt(Stmt *S);
1786  void AddDecl(Decl *D, bool isFirst = true);
1787  void AddTypeLoc(TypeSourceInfo *TI);
1788  void EnqueueChildren(Stmt *S);
1789};
1790} // end anonyous namespace
1791
1792void EnqueueVisitor::AddStmt(Stmt *S) {
1793  if (S)
1794    WL.push_back(StmtVisit(S, Parent));
1795}
1796void EnqueueVisitor::AddDecl(Decl *D, bool isFirst) {
1797  if (D)
1798    WL.push_back(DeclVisit(D, Parent, isFirst));
1799}
1800void EnqueueVisitor::AddTypeLoc(TypeSourceInfo *TI) {
1801  if (TI)
1802    WL.push_back(TypeLocVisit(TI->getTypeLoc(), Parent));
1803 }
1804void EnqueueVisitor::EnqueueChildren(Stmt *S) {
1805  unsigned size = WL.size();
1806  for (Stmt::child_iterator Child = S->child_begin(), ChildEnd = S->child_end();
1807       Child != ChildEnd; ++Child) {
1808    AddStmt(*Child);
1809  }
1810  if (size == WL.size())
1811    return;
1812  // Now reverse the entries we just added.  This will match the DFS
1813  // ordering performed by the worklist.
1814  VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1815  std::reverse(I, E);
1816}
1817void EnqueueVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
1818  EnqueueChildren(E);
1819  AddTypeLoc(E->getTypeSourceInfo());
1820}
1821void EnqueueVisitor::VisitCXXOperatorCallExpr(CXXOperatorCallExpr *CE) {
1822  // Note that we enqueue things in reverse order so that
1823  // they are visited correctly by the DFS.
1824  for (unsigned I = 1, N = CE->getNumArgs(); I != N; ++I)
1825    AddStmt(CE->getArg(N-I));
1826  AddStmt(CE->getCallee());
1827  AddStmt(CE->getArg(0));
1828}
1829void EnqueueVisitor::VisitDeclRefExpr(DeclRefExpr *DR) {
1830  WL.push_back(DeclRefExprParts(DR, Parent));
1831}
1832void EnqueueVisitor::VisitDeclStmt(DeclStmt *S) {
1833  unsigned size = WL.size();
1834  bool isFirst = true;
1835  for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
1836       D != DEnd; ++D) {
1837    AddDecl(*D, isFirst);
1838    isFirst = false;
1839  }
1840  if (size == WL.size())
1841    return;
1842  // Now reverse the entries we just added.  This will match the DFS
1843  // ordering performed by the worklist.
1844  VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1845  std::reverse(I, E);
1846}
1847void EnqueueVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
1848  EnqueueChildren(E);
1849  AddTypeLoc(E->getTypeInfoAsWritten());
1850}
1851void EnqueueVisitor::VisitForStmt(ForStmt *FS) {
1852  AddStmt(FS->getBody());
1853  AddStmt(FS->getInc());
1854  AddStmt(FS->getCond());
1855  AddDecl(FS->getConditionVariable());
1856  AddStmt(FS->getInit());
1857}
1858void EnqueueVisitor::VisitIfStmt(IfStmt *If) {
1859  AddStmt(If->getElse());
1860  AddStmt(If->getThen());
1861  AddStmt(If->getCond());
1862  AddDecl(If->getConditionVariable());
1863}
1864void EnqueueVisitor::VisitInitListExpr(InitListExpr *IE) {
1865  // We care about the syntactic form of the initializer list, only.
1866  if (InitListExpr *Syntactic = IE->getSyntacticForm())
1867    IE = Syntactic;
1868  EnqueueChildren(IE);
1869}
1870void EnqueueVisitor::VisitMemberExpr(MemberExpr *M) {
1871  WL.push_back(MemberExprParts(M, Parent));
1872  AddStmt(M->getBase());
1873}
1874void EnqueueVisitor::VisitObjCMessageExpr(ObjCMessageExpr *M) {
1875  EnqueueChildren(M);
1876  AddTypeLoc(M->getClassReceiverTypeInfo());
1877}
1878void EnqueueVisitor::VisitOverloadExpr(OverloadExpr *E) {
1879  WL.push_back(OverloadExprParts(E, Parent));
1880}
1881void EnqueueVisitor::VisitStmt(Stmt *S) {
1882  EnqueueChildren(S);
1883}
1884void EnqueueVisitor::VisitSwitchStmt(SwitchStmt *S) {
1885  AddStmt(S->getBody());
1886  AddStmt(S->getCond());
1887  AddDecl(S->getConditionVariable());
1888}
1889void EnqueueVisitor::VisitWhileStmt(WhileStmt *W) {
1890  AddStmt(W->getBody());
1891  AddStmt(W->getCond());
1892  AddDecl(W->getConditionVariable());
1893}
1894void EnqueueVisitor::VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U) {
1895  VisitOverloadExpr(U);
1896  if (!U->isImplicitAccess())
1897    AddStmt(U->getBase());
1898}
1899
1900void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, Stmt *S) {
1901  EnqueueVisitor(WL, MakeCXCursor(S, StmtParent, TU)).Visit(S);
1902}
1903
1904bool CursorVisitor::IsInRegionOfInterest(CXCursor C) {
1905  if (RegionOfInterest.isValid()) {
1906    SourceRange Range = getRawCursorExtent(C);
1907    if (Range.isInvalid() || CompareRegionOfInterest(Range))
1908      return false;
1909  }
1910  return true;
1911}
1912
1913bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) {
1914  while (!WL.empty()) {
1915    // Dequeue the worklist item.
1916    VisitorJob LI = WL.back(); WL.pop_back();
1917
1918    // Set the Parent field, then back to its old value once we're done.
1919    SetParentRAII SetParent(Parent, StmtParent, LI.getParent());
1920
1921    switch (LI.getKind()) {
1922      case VisitorJob::DeclVisitKind: {
1923        Decl *D = cast<DeclVisit>(LI).get();
1924        if (!D)
1925          continue;
1926
1927        // For now, perform default visitation for Decls.
1928        if (Visit(MakeCXCursor(D, TU, cast<DeclVisit>(LI).isFirst())))
1929            return true;
1930
1931        continue;
1932      }
1933      case VisitorJob::TypeLocVisitKind: {
1934        // Perform default visitation for TypeLocs.
1935        if (Visit(cast<TypeLocVisit>(LI).get()))
1936          return true;
1937        continue;
1938      }
1939      case VisitorJob::StmtVisitKind: {
1940        Stmt *S = cast<StmtVisit>(LI).get();
1941        if (!S)
1942          continue;
1943
1944        // Update the current cursor.
1945        CXCursor Cursor = MakeCXCursor(S, StmtParent, TU);
1946
1947        switch (S->getStmtClass()) {
1948          case Stmt::GotoStmtClass: {
1949            GotoStmt *GS = cast<GotoStmt>(S);
1950            if (Visit(MakeCursorLabelRef(GS->getLabel(),
1951                                         GS->getLabelLoc(), TU))) {
1952              return true;
1953            }
1954            continue;
1955          }
1956          default: {
1957            // FIXME: this entire switch stmt will eventually
1958            // go away.
1959            if (!isa<ExplicitCastExpr>(S)) {
1960              // Perform default visitation for other cases.
1961              if (Visit(Cursor))
1962                return true;
1963              continue;
1964            }
1965            // Fall-through.
1966          }
1967          case Stmt::BinaryOperatorClass:
1968          case Stmt::CallExprClass:
1969          case Stmt::CaseStmtClass:
1970          case Stmt::CompoundLiteralExprClass:
1971          case Stmt::CompoundStmtClass:
1972          case Stmt::CXXMemberCallExprClass:
1973          case Stmt::CXXOperatorCallExprClass:
1974          case Stmt::DefaultStmtClass:
1975          case Stmt::DoStmtClass:
1976          case Stmt::ForStmtClass:
1977          case Stmt::IfStmtClass:
1978          case Stmt::InitListExprClass:
1979          case Stmt::MemberExprClass:
1980          case Stmt::ObjCMessageExprClass:
1981          case Stmt::ParenExprClass:
1982          case Stmt::SwitchStmtClass:
1983          case Stmt::UnaryOperatorClass:
1984          case Stmt::UnresolvedLookupExprClass:
1985          case Stmt::UnresolvedMemberExprClass:
1986          case Stmt::WhileStmtClass:
1987          {
1988            if (!IsInRegionOfInterest(Cursor))
1989              continue;
1990            switch (Visitor(Cursor, Parent, ClientData)) {
1991              case CXChildVisit_Break:
1992                return true;
1993              case CXChildVisit_Continue:
1994                break;
1995              case CXChildVisit_Recurse:
1996                EnqueueWorkList(WL, S);
1997                break;
1998            }
1999          }
2000        }
2001        continue;
2002      }
2003      case VisitorJob::MemberExprPartsKind: {
2004        // Handle the other pieces in the MemberExpr besides the base.
2005        MemberExpr *M = cast<MemberExprParts>(LI).get();
2006
2007        // Visit the nested-name-specifier
2008        if (NestedNameSpecifier *Qualifier = M->getQualifier())
2009          if (VisitNestedNameSpecifier(Qualifier, M->getQualifierRange()))
2010            return true;
2011
2012        // Visit the declaration name.
2013        if (VisitDeclarationNameInfo(M->getMemberNameInfo()))
2014          return true;
2015
2016        // Visit the explicitly-specified template arguments, if any.
2017        if (M->hasExplicitTemplateArgs()) {
2018          for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(),
2019               *ArgEnd = Arg + M->getNumTemplateArgs();
2020               Arg != ArgEnd; ++Arg) {
2021            if (VisitTemplateArgumentLoc(*Arg))
2022              return true;
2023          }
2024        }
2025        continue;
2026      }
2027      case VisitorJob::DeclRefExprPartsKind: {
2028        DeclRefExpr *DR = cast<DeclRefExprParts>(LI).get();
2029        // Visit nested-name-specifier, if present.
2030        if (NestedNameSpecifier *Qualifier = DR->getQualifier())
2031          if (VisitNestedNameSpecifier(Qualifier, DR->getQualifierRange()))
2032            return true;
2033        // Visit declaration name.
2034        if (VisitDeclarationNameInfo(DR->getNameInfo()))
2035          return true;
2036        // Visit explicitly-specified template arguments.
2037        if (DR->hasExplicitTemplateArgs()) {
2038          ExplicitTemplateArgumentList &Args = DR->getExplicitTemplateArgs();
2039          for (TemplateArgumentLoc *Arg = Args.getTemplateArgs(),
2040                 *ArgEnd = Arg + Args.NumTemplateArgs;
2041               Arg != ArgEnd; ++Arg)
2042            if (VisitTemplateArgumentLoc(*Arg))
2043              return true;
2044        }
2045        continue;
2046      }
2047      case VisitorJob::OverloadExprPartsKind: {
2048        OverloadExpr *O = cast<OverloadExprParts>(LI).get();
2049        // Visit the nested-name-specifier.
2050        if (NestedNameSpecifier *Qualifier = O->getQualifier())
2051          if (VisitNestedNameSpecifier(Qualifier, O->getQualifierRange()))
2052            return true;
2053        // Visit the declaration name.
2054        if (VisitDeclarationNameInfo(O->getNameInfo()))
2055          return true;
2056        // Visit the overloaded declaration reference.
2057        if (Visit(MakeCursorOverloadedDeclRef(O, TU)))
2058          return true;
2059        // Visit the explicitly-specified template arguments.
2060        if (const ExplicitTemplateArgumentList *ArgList
2061                                      = O->getOptionalExplicitTemplateArgs()) {
2062          for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
2063                 *ArgEnd = Arg + ArgList->NumTemplateArgs;
2064               Arg != ArgEnd; ++Arg) {
2065            if (VisitTemplateArgumentLoc(*Arg))
2066              return true;
2067          }
2068        }
2069        continue;
2070      }
2071    }
2072  }
2073  return false;
2074}
2075
2076bool CursorVisitor::VisitDataRecursive(Stmt *S) {
2077  VisitorWorkList WL;
2078  EnqueueWorkList(WL, S);
2079  return RunVisitorWorkList(WL);
2080}
2081
2082//===----------------------------------------------------------------------===//
2083// Misc. API hooks.
2084//===----------------------------------------------------------------------===//
2085
2086static llvm::sys::Mutex EnableMultithreadingMutex;
2087static bool EnabledMultithreading;
2088
2089extern "C" {
2090CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
2091                          int displayDiagnostics) {
2092  // Disable pretty stack trace functionality, which will otherwise be a very
2093  // poor citizen of the world and set up all sorts of signal handlers.
2094  llvm::DisablePrettyStackTrace = true;
2095
2096  // We use crash recovery to make some of our APIs more reliable, implicitly
2097  // enable it.
2098  llvm::CrashRecoveryContext::Enable();
2099
2100  // Enable support for multithreading in LLVM.
2101  {
2102    llvm::sys::ScopedLock L(EnableMultithreadingMutex);
2103    if (!EnabledMultithreading) {
2104      llvm::llvm_start_multithreaded();
2105      EnabledMultithreading = true;
2106    }
2107  }
2108
2109  CIndexer *CIdxr = new CIndexer();
2110  if (excludeDeclarationsFromPCH)
2111    CIdxr->setOnlyLocalDecls();
2112  if (displayDiagnostics)
2113    CIdxr->setDisplayDiagnostics();
2114  return CIdxr;
2115}
2116
2117void clang_disposeIndex(CXIndex CIdx) {
2118  if (CIdx)
2119    delete static_cast<CIndexer *>(CIdx);
2120}
2121
2122CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
2123                                              const char *ast_filename) {
2124  if (!CIdx)
2125    return 0;
2126
2127  CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
2128  FileSystemOptions FileSystemOpts;
2129  FileSystemOpts.WorkingDir = CXXIdx->getWorkingDirectory();
2130
2131  llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
2132  return ASTUnit::LoadFromASTFile(ast_filename, Diags, FileSystemOpts,
2133                                  CXXIdx->getOnlyLocalDecls(),
2134                                  0, 0, true);
2135}
2136
2137unsigned clang_defaultEditingTranslationUnitOptions() {
2138  return CXTranslationUnit_PrecompiledPreamble |
2139         CXTranslationUnit_CacheCompletionResults |
2140         CXTranslationUnit_CXXPrecompiledPreamble;
2141}
2142
2143CXTranslationUnit
2144clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
2145                                          const char *source_filename,
2146                                          int num_command_line_args,
2147                                          const char * const *command_line_args,
2148                                          unsigned num_unsaved_files,
2149                                          struct CXUnsavedFile *unsaved_files) {
2150  return clang_parseTranslationUnit(CIdx, source_filename,
2151                                    command_line_args, num_command_line_args,
2152                                    unsaved_files, num_unsaved_files,
2153                                 CXTranslationUnit_DetailedPreprocessingRecord);
2154}
2155
2156struct ParseTranslationUnitInfo {
2157  CXIndex CIdx;
2158  const char *source_filename;
2159  const char *const *command_line_args;
2160  int num_command_line_args;
2161  struct CXUnsavedFile *unsaved_files;
2162  unsigned num_unsaved_files;
2163  unsigned options;
2164  CXTranslationUnit result;
2165};
2166static void clang_parseTranslationUnit_Impl(void *UserData) {
2167  ParseTranslationUnitInfo *PTUI =
2168    static_cast<ParseTranslationUnitInfo*>(UserData);
2169  CXIndex CIdx = PTUI->CIdx;
2170  const char *source_filename = PTUI->source_filename;
2171  const char * const *command_line_args = PTUI->command_line_args;
2172  int num_command_line_args = PTUI->num_command_line_args;
2173  struct CXUnsavedFile *unsaved_files = PTUI->unsaved_files;
2174  unsigned num_unsaved_files = PTUI->num_unsaved_files;
2175  unsigned options = PTUI->options;
2176  PTUI->result = 0;
2177
2178  if (!CIdx)
2179    return;
2180
2181  CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
2182
2183  bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
2184  bool CompleteTranslationUnit
2185    = ((options & CXTranslationUnit_Incomplete) == 0);
2186  bool CacheCodeCompetionResults
2187    = options & CXTranslationUnit_CacheCompletionResults;
2188  bool CXXPrecompilePreamble
2189    = options & CXTranslationUnit_CXXPrecompiledPreamble;
2190  bool CXXChainedPCH
2191    = options & CXTranslationUnit_CXXChainedPCH;
2192
2193  // Configure the diagnostics.
2194  DiagnosticOptions DiagOpts;
2195  llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
2196  Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
2197
2198  llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
2199  for (unsigned I = 0; I != num_unsaved_files; ++I) {
2200    llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
2201    const llvm::MemoryBuffer *Buffer
2202      = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
2203    RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
2204                                           Buffer));
2205  }
2206
2207  llvm::SmallVector<const char *, 16> Args;
2208
2209  // The 'source_filename' argument is optional.  If the caller does not
2210  // specify it then it is assumed that the source file is specified
2211  // in the actual argument list.
2212  if (source_filename)
2213    Args.push_back(source_filename);
2214
2215  // Since the Clang C library is primarily used by batch tools dealing with
2216  // (often very broken) source code, where spell-checking can have a
2217  // significant negative impact on performance (particularly when
2218  // precompiled headers are involved), we disable it by default.
2219  // Only do this if we haven't found a spell-checking-related argument.
2220  bool FoundSpellCheckingArgument = false;
2221  for (int I = 0; I != num_command_line_args; ++I) {
2222    if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
2223        strcmp(command_line_args[I], "-fspell-checking") == 0) {
2224      FoundSpellCheckingArgument = true;
2225      break;
2226    }
2227  }
2228  if (!FoundSpellCheckingArgument)
2229    Args.push_back("-fno-spell-checking");
2230
2231  Args.insert(Args.end(), command_line_args,
2232              command_line_args + num_command_line_args);
2233
2234  // Do we need the detailed preprocessing record?
2235  if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
2236    Args.push_back("-Xclang");
2237    Args.push_back("-detailed-preprocessing-record");
2238  }
2239
2240  unsigned NumErrors = Diags->getNumErrors();
2241  llvm::OwningPtr<ASTUnit> Unit(
2242    ASTUnit::LoadFromCommandLine(Args.data(), Args.data() + Args.size(),
2243                                 Diags,
2244                                 CXXIdx->getClangResourcesPath(),
2245                                 CXXIdx->getOnlyLocalDecls(),
2246                                 /*CaptureDiagnostics=*/true,
2247                                 RemappedFiles.data(),
2248                                 RemappedFiles.size(),
2249                                 PrecompilePreamble,
2250                                 CompleteTranslationUnit,
2251                                 CacheCodeCompetionResults,
2252                                 CXXPrecompilePreamble,
2253                                 CXXChainedPCH));
2254
2255  if (NumErrors != Diags->getNumErrors()) {
2256    // Make sure to check that 'Unit' is non-NULL.
2257    if (CXXIdx->getDisplayDiagnostics() && Unit.get()) {
2258      for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
2259                                      DEnd = Unit->stored_diag_end();
2260           D != DEnd; ++D) {
2261        CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOptions());
2262        CXString Msg = clang_formatDiagnostic(&Diag,
2263                                    clang_defaultDiagnosticDisplayOptions());
2264        fprintf(stderr, "%s\n", clang_getCString(Msg));
2265        clang_disposeString(Msg);
2266      }
2267#ifdef LLVM_ON_WIN32
2268      // On Windows, force a flush, since there may be multiple copies of
2269      // stderr and stdout in the file system, all with different buffers
2270      // but writing to the same device.
2271      fflush(stderr);
2272#endif
2273    }
2274  }
2275
2276  PTUI->result = Unit.take();
2277}
2278CXTranslationUnit clang_parseTranslationUnit(CXIndex CIdx,
2279                                             const char *source_filename,
2280                                         const char * const *command_line_args,
2281                                             int num_command_line_args,
2282                                            struct CXUnsavedFile *unsaved_files,
2283                                             unsigned num_unsaved_files,
2284                                             unsigned options) {
2285  ParseTranslationUnitInfo PTUI = { CIdx, source_filename, command_line_args,
2286                                    num_command_line_args, unsaved_files,
2287                                    num_unsaved_files, options, 0 };
2288  llvm::CrashRecoveryContext CRC;
2289
2290  if (!RunSafely(CRC, clang_parseTranslationUnit_Impl, &PTUI)) {
2291    fprintf(stderr, "libclang: crash detected during parsing: {\n");
2292    fprintf(stderr, "  'source_filename' : '%s'\n", source_filename);
2293    fprintf(stderr, "  'command_line_args' : [");
2294    for (int i = 0; i != num_command_line_args; ++i) {
2295      if (i)
2296        fprintf(stderr, ", ");
2297      fprintf(stderr, "'%s'", command_line_args[i]);
2298    }
2299    fprintf(stderr, "],\n");
2300    fprintf(stderr, "  'unsaved_files' : [");
2301    for (unsigned i = 0; i != num_unsaved_files; ++i) {
2302      if (i)
2303        fprintf(stderr, ", ");
2304      fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
2305              unsaved_files[i].Length);
2306    }
2307    fprintf(stderr, "],\n");
2308    fprintf(stderr, "  'options' : %d,\n", options);
2309    fprintf(stderr, "}\n");
2310
2311    return 0;
2312  }
2313
2314  return PTUI.result;
2315}
2316
2317unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
2318  return CXSaveTranslationUnit_None;
2319}
2320
2321int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
2322                              unsigned options) {
2323  if (!TU)
2324    return 1;
2325
2326  return static_cast<ASTUnit *>(TU)->Save(FileName);
2327}
2328
2329void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
2330  if (CTUnit) {
2331    // If the translation unit has been marked as unsafe to free, just discard
2332    // it.
2333    if (static_cast<ASTUnit *>(CTUnit)->isUnsafeToFree())
2334      return;
2335
2336    delete static_cast<ASTUnit *>(CTUnit);
2337  }
2338}
2339
2340unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
2341  return CXReparse_None;
2342}
2343
2344struct ReparseTranslationUnitInfo {
2345  CXTranslationUnit TU;
2346  unsigned num_unsaved_files;
2347  struct CXUnsavedFile *unsaved_files;
2348  unsigned options;
2349  int result;
2350};
2351
2352static void clang_reparseTranslationUnit_Impl(void *UserData) {
2353  ReparseTranslationUnitInfo *RTUI =
2354    static_cast<ReparseTranslationUnitInfo*>(UserData);
2355  CXTranslationUnit TU = RTUI->TU;
2356  unsigned num_unsaved_files = RTUI->num_unsaved_files;
2357  struct CXUnsavedFile *unsaved_files = RTUI->unsaved_files;
2358  unsigned options = RTUI->options;
2359  (void) options;
2360  RTUI->result = 1;
2361
2362  if (!TU)
2363    return;
2364
2365  ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2366  ASTUnit::ConcurrencyCheck Check(*CXXUnit);
2367
2368  llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
2369  for (unsigned I = 0; I != num_unsaved_files; ++I) {
2370    llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
2371    const llvm::MemoryBuffer *Buffer
2372      = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
2373    RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
2374                                           Buffer));
2375  }
2376
2377  if (!CXXUnit->Reparse(RemappedFiles.data(), RemappedFiles.size()))
2378    RTUI->result = 0;
2379}
2380
2381int clang_reparseTranslationUnit(CXTranslationUnit TU,
2382                                 unsigned num_unsaved_files,
2383                                 struct CXUnsavedFile *unsaved_files,
2384                                 unsigned options) {
2385  ReparseTranslationUnitInfo RTUI = { TU, num_unsaved_files, unsaved_files,
2386                                      options, 0 };
2387  llvm::CrashRecoveryContext CRC;
2388
2389  if (!RunSafely(CRC, clang_reparseTranslationUnit_Impl, &RTUI)) {
2390    fprintf(stderr, "libclang: crash detected during reparsing\n");
2391    static_cast<ASTUnit *>(TU)->setUnsafeToFree(true);
2392    return 1;
2393  }
2394
2395
2396  return RTUI.result;
2397}
2398
2399
2400CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
2401  if (!CTUnit)
2402    return createCXString("");
2403
2404  ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit);
2405  return createCXString(CXXUnit->getOriginalSourceFileName(), true);
2406}
2407
2408CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
2409  CXCursor Result = { CXCursor_TranslationUnit, { 0, 0, TU } };
2410  return Result;
2411}
2412
2413} // end: extern "C"
2414
2415//===----------------------------------------------------------------------===//
2416// CXSourceLocation and CXSourceRange Operations.
2417//===----------------------------------------------------------------------===//
2418
2419extern "C" {
2420CXSourceLocation clang_getNullLocation() {
2421  CXSourceLocation Result = { { 0, 0 }, 0 };
2422  return Result;
2423}
2424
2425unsigned clang_equalLocations(CXSourceLocation loc1, CXSourceLocation loc2) {
2426  return (loc1.ptr_data[0] == loc2.ptr_data[0] &&
2427          loc1.ptr_data[1] == loc2.ptr_data[1] &&
2428          loc1.int_data == loc2.int_data);
2429}
2430
2431CXSourceLocation clang_getLocation(CXTranslationUnit tu,
2432                                   CXFile file,
2433                                   unsigned line,
2434                                   unsigned column) {
2435  if (!tu || !file)
2436    return clang_getNullLocation();
2437
2438  ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
2439  SourceLocation SLoc
2440    = CXXUnit->getSourceManager().getLocation(
2441                                        static_cast<const FileEntry *>(file),
2442                                              line, column);
2443  if (SLoc.isInvalid()) return clang_getNullLocation();
2444
2445  return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
2446}
2447
2448CXSourceLocation clang_getLocationForOffset(CXTranslationUnit tu,
2449                                            CXFile file,
2450                                            unsigned offset) {
2451  if (!tu || !file)
2452    return clang_getNullLocation();
2453
2454  ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
2455  SourceLocation Start
2456    = CXXUnit->getSourceManager().getLocation(
2457                                        static_cast<const FileEntry *>(file),
2458                                              1, 1);
2459  if (Start.isInvalid()) return clang_getNullLocation();
2460
2461  SourceLocation SLoc = Start.getFileLocWithOffset(offset);
2462
2463  if (SLoc.isInvalid()) return clang_getNullLocation();
2464
2465  return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
2466}
2467
2468CXSourceRange clang_getNullRange() {
2469  CXSourceRange Result = { { 0, 0 }, 0, 0 };
2470  return Result;
2471}
2472
2473CXSourceRange clang_getRange(CXSourceLocation begin, CXSourceLocation end) {
2474  if (begin.ptr_data[0] != end.ptr_data[0] ||
2475      begin.ptr_data[1] != end.ptr_data[1])
2476    return clang_getNullRange();
2477
2478  CXSourceRange Result = { { begin.ptr_data[0], begin.ptr_data[1] },
2479                           begin.int_data, end.int_data };
2480  return Result;
2481}
2482
2483void clang_getInstantiationLocation(CXSourceLocation location,
2484                                    CXFile *file,
2485                                    unsigned *line,
2486                                    unsigned *column,
2487                                    unsigned *offset) {
2488  SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2489
2490  if (!location.ptr_data[0] || Loc.isInvalid()) {
2491    if (file)
2492      *file = 0;
2493    if (line)
2494      *line = 0;
2495    if (column)
2496      *column = 0;
2497    if (offset)
2498      *offset = 0;
2499    return;
2500  }
2501
2502  const SourceManager &SM =
2503    *static_cast<const SourceManager*>(location.ptr_data[0]);
2504  SourceLocation InstLoc = SM.getInstantiationLoc(Loc);
2505
2506  if (file)
2507    *file = (void *)SM.getFileEntryForID(SM.getFileID(InstLoc));
2508  if (line)
2509    *line = SM.getInstantiationLineNumber(InstLoc);
2510  if (column)
2511    *column = SM.getInstantiationColumnNumber(InstLoc);
2512  if (offset)
2513    *offset = SM.getDecomposedLoc(InstLoc).second;
2514}
2515
2516void clang_getSpellingLocation(CXSourceLocation location,
2517                               CXFile *file,
2518                               unsigned *line,
2519                               unsigned *column,
2520                               unsigned *offset) {
2521  SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2522
2523  if (!location.ptr_data[0] || Loc.isInvalid()) {
2524    if (file)
2525      *file = 0;
2526    if (line)
2527      *line = 0;
2528    if (column)
2529      *column = 0;
2530    if (offset)
2531      *offset = 0;
2532    return;
2533  }
2534
2535  const SourceManager &SM =
2536    *static_cast<const SourceManager*>(location.ptr_data[0]);
2537  SourceLocation SpellLoc = Loc;
2538  if (SpellLoc.isMacroID()) {
2539    SourceLocation SimpleSpellingLoc = SM.getImmediateSpellingLoc(SpellLoc);
2540    if (SimpleSpellingLoc.isFileID() &&
2541        SM.getFileEntryForID(SM.getDecomposedLoc(SimpleSpellingLoc).first))
2542      SpellLoc = SimpleSpellingLoc;
2543    else
2544      SpellLoc = SM.getInstantiationLoc(SpellLoc);
2545  }
2546
2547  std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(SpellLoc);
2548  FileID FID = LocInfo.first;
2549  unsigned FileOffset = LocInfo.second;
2550
2551  if (file)
2552    *file = (void *)SM.getFileEntryForID(FID);
2553  if (line)
2554    *line = SM.getLineNumber(FID, FileOffset);
2555  if (column)
2556    *column = SM.getColumnNumber(FID, FileOffset);
2557  if (offset)
2558    *offset = FileOffset;
2559}
2560
2561CXSourceLocation clang_getRangeStart(CXSourceRange range) {
2562  CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
2563                              range.begin_int_data };
2564  return Result;
2565}
2566
2567CXSourceLocation clang_getRangeEnd(CXSourceRange range) {
2568  CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
2569                              range.end_int_data };
2570  return Result;
2571}
2572
2573} // end: extern "C"
2574
2575//===----------------------------------------------------------------------===//
2576// CXFile Operations.
2577//===----------------------------------------------------------------------===//
2578
2579extern "C" {
2580CXString clang_getFileName(CXFile SFile) {
2581  if (!SFile)
2582    return createCXString(NULL);
2583
2584  FileEntry *FEnt = static_cast<FileEntry *>(SFile);
2585  return createCXString(FEnt->getName());
2586}
2587
2588time_t clang_getFileTime(CXFile SFile) {
2589  if (!SFile)
2590    return 0;
2591
2592  FileEntry *FEnt = static_cast<FileEntry *>(SFile);
2593  return FEnt->getModificationTime();
2594}
2595
2596CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
2597  if (!tu)
2598    return 0;
2599
2600  ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
2601
2602  FileManager &FMgr = CXXUnit->getFileManager();
2603  const FileEntry *File = FMgr.getFile(file_name, file_name+strlen(file_name),
2604                                       CXXUnit->getFileSystemOpts());
2605  return const_cast<FileEntry *>(File);
2606}
2607
2608} // end: extern "C"
2609
2610//===----------------------------------------------------------------------===//
2611// CXCursor Operations.
2612//===----------------------------------------------------------------------===//
2613
2614static Decl *getDeclFromExpr(Stmt *E) {
2615  if (CastExpr *CE = dyn_cast<CastExpr>(E))
2616    return getDeclFromExpr(CE->getSubExpr());
2617
2618  if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
2619    return RefExpr->getDecl();
2620  if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2621    return RefExpr->getDecl();
2622  if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
2623    return ME->getMemberDecl();
2624  if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
2625    return RE->getDecl();
2626  if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E))
2627    return PRE->getProperty();
2628
2629  if (CallExpr *CE = dyn_cast<CallExpr>(E))
2630    return getDeclFromExpr(CE->getCallee());
2631  if (CXXConstructExpr *CE = llvm::dyn_cast<CXXConstructExpr>(E))
2632    if (!CE->isElidable())
2633    return CE->getConstructor();
2634  if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
2635    return OME->getMethodDecl();
2636
2637  if (ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
2638    return PE->getProtocol();
2639
2640  return 0;
2641}
2642
2643static SourceLocation getLocationFromExpr(Expr *E) {
2644  if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
2645    return /*FIXME:*/Msg->getLeftLoc();
2646  if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
2647    return DRE->getLocation();
2648  if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2649    return RefExpr->getLocation();
2650  if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
2651    return Member->getMemberLoc();
2652  if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
2653    return Ivar->getLocation();
2654  return E->getLocStart();
2655}
2656
2657extern "C" {
2658
2659unsigned clang_visitChildren(CXCursor parent,
2660                             CXCursorVisitor visitor,
2661                             CXClientData client_data) {
2662  ASTUnit *CXXUnit = getCursorASTUnit(parent);
2663
2664  CursorVisitor CursorVis(CXXUnit, visitor, client_data,
2665                          CXXUnit->getMaxPCHLevel());
2666  return CursorVis.VisitChildren(parent);
2667}
2668
2669#ifndef __has_feature
2670#define __has_feature(x) 0
2671#endif
2672#if __has_feature(blocks)
2673typedef enum CXChildVisitResult
2674     (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent);
2675
2676static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
2677    CXClientData client_data) {
2678  CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
2679  return block(cursor, parent);
2680}
2681#else
2682// If we are compiled with a compiler that doesn't have native blocks support,
2683// define and call the block manually, so the
2684typedef struct _CXChildVisitResult
2685{
2686	void *isa;
2687	int flags;
2688	int reserved;
2689	enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor,
2690                                         CXCursor);
2691} *CXCursorVisitorBlock;
2692
2693static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
2694    CXClientData client_data) {
2695  CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
2696  return block->invoke(block, cursor, parent);
2697}
2698#endif
2699
2700
2701unsigned clang_visitChildrenWithBlock(CXCursor parent,
2702                                      CXCursorVisitorBlock block) {
2703  return clang_visitChildren(parent, visitWithBlock, block);
2704}
2705
2706static CXString getDeclSpelling(Decl *D) {
2707  NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
2708  if (!ND)
2709    return createCXString("");
2710
2711  if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
2712    return createCXString(OMD->getSelector().getAsString());
2713
2714  if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
2715    // No, this isn't the same as the code below. getIdentifier() is non-virtual
2716    // and returns different names. NamedDecl returns the class name and
2717    // ObjCCategoryImplDecl returns the category name.
2718    return createCXString(CIMP->getIdentifier()->getNameStart());
2719
2720  if (isa<UsingDirectiveDecl>(D))
2721    return createCXString("");
2722
2723  llvm::SmallString<1024> S;
2724  llvm::raw_svector_ostream os(S);
2725  ND->printName(os);
2726
2727  return createCXString(os.str());
2728}
2729
2730CXString clang_getCursorSpelling(CXCursor C) {
2731  if (clang_isTranslationUnit(C.kind))
2732    return clang_getTranslationUnitSpelling(C.data[2]);
2733
2734  if (clang_isReference(C.kind)) {
2735    switch (C.kind) {
2736    case CXCursor_ObjCSuperClassRef: {
2737      ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
2738      return createCXString(Super->getIdentifier()->getNameStart());
2739    }
2740    case CXCursor_ObjCClassRef: {
2741      ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
2742      return createCXString(Class->getIdentifier()->getNameStart());
2743    }
2744    case CXCursor_ObjCProtocolRef: {
2745      ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
2746      assert(OID && "getCursorSpelling(): Missing protocol decl");
2747      return createCXString(OID->getIdentifier()->getNameStart());
2748    }
2749    case CXCursor_CXXBaseSpecifier: {
2750      CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
2751      return createCXString(B->getType().getAsString());
2752    }
2753    case CXCursor_TypeRef: {
2754      TypeDecl *Type = getCursorTypeRef(C).first;
2755      assert(Type && "Missing type decl");
2756
2757      return createCXString(getCursorContext(C).getTypeDeclType(Type).
2758                              getAsString());
2759    }
2760    case CXCursor_TemplateRef: {
2761      TemplateDecl *Template = getCursorTemplateRef(C).first;
2762      assert(Template && "Missing template decl");
2763
2764      return createCXString(Template->getNameAsString());
2765    }
2766
2767    case CXCursor_NamespaceRef: {
2768      NamedDecl *NS = getCursorNamespaceRef(C).first;
2769      assert(NS && "Missing namespace decl");
2770
2771      return createCXString(NS->getNameAsString());
2772    }
2773
2774    case CXCursor_MemberRef: {
2775      FieldDecl *Field = getCursorMemberRef(C).first;
2776      assert(Field && "Missing member decl");
2777
2778      return createCXString(Field->getNameAsString());
2779    }
2780
2781    case CXCursor_LabelRef: {
2782      LabelStmt *Label = getCursorLabelRef(C).first;
2783      assert(Label && "Missing label");
2784
2785      return createCXString(Label->getID()->getName());
2786    }
2787
2788    case CXCursor_OverloadedDeclRef: {
2789      OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
2790      if (Decl *D = Storage.dyn_cast<Decl *>()) {
2791        if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
2792          return createCXString(ND->getNameAsString());
2793        return createCXString("");
2794      }
2795      if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
2796        return createCXString(E->getName().getAsString());
2797      OverloadedTemplateStorage *Ovl
2798        = Storage.get<OverloadedTemplateStorage*>();
2799      if (Ovl->size() == 0)
2800        return createCXString("");
2801      return createCXString((*Ovl->begin())->getNameAsString());
2802    }
2803
2804    default:
2805      return createCXString("<not implemented>");
2806    }
2807  }
2808
2809  if (clang_isExpression(C.kind)) {
2810    Decl *D = getDeclFromExpr(getCursorExpr(C));
2811    if (D)
2812      return getDeclSpelling(D);
2813    return createCXString("");
2814  }
2815
2816  if (clang_isStatement(C.kind)) {
2817    Stmt *S = getCursorStmt(C);
2818    if (LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
2819      return createCXString(Label->getID()->getName());
2820
2821    return createCXString("");
2822  }
2823
2824  if (C.kind == CXCursor_MacroInstantiation)
2825    return createCXString(getCursorMacroInstantiation(C)->getName()
2826                                                           ->getNameStart());
2827
2828  if (C.kind == CXCursor_MacroDefinition)
2829    return createCXString(getCursorMacroDefinition(C)->getName()
2830                                                           ->getNameStart());
2831
2832  if (C.kind == CXCursor_InclusionDirective)
2833    return createCXString(getCursorInclusionDirective(C)->getFileName());
2834
2835  if (clang_isDeclaration(C.kind))
2836    return getDeclSpelling(getCursorDecl(C));
2837
2838  return createCXString("");
2839}
2840
2841CXString clang_getCursorDisplayName(CXCursor C) {
2842  if (!clang_isDeclaration(C.kind))
2843    return clang_getCursorSpelling(C);
2844
2845  Decl *D = getCursorDecl(C);
2846  if (!D)
2847    return createCXString("");
2848
2849  PrintingPolicy &Policy = getCursorContext(C).PrintingPolicy;
2850  if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
2851    D = FunTmpl->getTemplatedDecl();
2852
2853  if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
2854    llvm::SmallString<64> Str;
2855    llvm::raw_svector_ostream OS(Str);
2856    OS << Function->getNameAsString();
2857    if (Function->getPrimaryTemplate())
2858      OS << "<>";
2859    OS << "(";
2860    for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
2861      if (I)
2862        OS << ", ";
2863      OS << Function->getParamDecl(I)->getType().getAsString(Policy);
2864    }
2865
2866    if (Function->isVariadic()) {
2867      if (Function->getNumParams())
2868        OS << ", ";
2869      OS << "...";
2870    }
2871    OS << ")";
2872    return createCXString(OS.str());
2873  }
2874
2875  if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
2876    llvm::SmallString<64> Str;
2877    llvm::raw_svector_ostream OS(Str);
2878    OS << ClassTemplate->getNameAsString();
2879    OS << "<";
2880    TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
2881    for (unsigned I = 0, N = Params->size(); I != N; ++I) {
2882      if (I)
2883        OS << ", ";
2884
2885      NamedDecl *Param = Params->getParam(I);
2886      if (Param->getIdentifier()) {
2887        OS << Param->getIdentifier()->getName();
2888        continue;
2889      }
2890
2891      // There is no parameter name, which makes this tricky. Try to come up
2892      // with something useful that isn't too long.
2893      if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
2894        OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
2895      else if (NonTypeTemplateParmDecl *NTTP
2896                                    = dyn_cast<NonTypeTemplateParmDecl>(Param))
2897        OS << NTTP->getType().getAsString(Policy);
2898      else
2899        OS << "template<...> class";
2900    }
2901
2902    OS << ">";
2903    return createCXString(OS.str());
2904  }
2905
2906  if (ClassTemplateSpecializationDecl *ClassSpec
2907                              = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
2908    // If the type was explicitly written, use that.
2909    if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
2910      return createCXString(TSInfo->getType().getAsString(Policy));
2911
2912    llvm::SmallString<64> Str;
2913    llvm::raw_svector_ostream OS(Str);
2914    OS << ClassSpec->getNameAsString();
2915    OS << TemplateSpecializationType::PrintTemplateArgumentList(
2916                                      ClassSpec->getTemplateArgs().data(),
2917                                      ClassSpec->getTemplateArgs().size(),
2918                                                                Policy);
2919    return createCXString(OS.str());
2920  }
2921
2922  return clang_getCursorSpelling(C);
2923}
2924
2925CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
2926  switch (Kind) {
2927  case CXCursor_FunctionDecl:
2928      return createCXString("FunctionDecl");
2929  case CXCursor_TypedefDecl:
2930      return createCXString("TypedefDecl");
2931  case CXCursor_EnumDecl:
2932      return createCXString("EnumDecl");
2933  case CXCursor_EnumConstantDecl:
2934      return createCXString("EnumConstantDecl");
2935  case CXCursor_StructDecl:
2936      return createCXString("StructDecl");
2937  case CXCursor_UnionDecl:
2938      return createCXString("UnionDecl");
2939  case CXCursor_ClassDecl:
2940      return createCXString("ClassDecl");
2941  case CXCursor_FieldDecl:
2942      return createCXString("FieldDecl");
2943  case CXCursor_VarDecl:
2944      return createCXString("VarDecl");
2945  case CXCursor_ParmDecl:
2946      return createCXString("ParmDecl");
2947  case CXCursor_ObjCInterfaceDecl:
2948      return createCXString("ObjCInterfaceDecl");
2949  case CXCursor_ObjCCategoryDecl:
2950      return createCXString("ObjCCategoryDecl");
2951  case CXCursor_ObjCProtocolDecl:
2952      return createCXString("ObjCProtocolDecl");
2953  case CXCursor_ObjCPropertyDecl:
2954      return createCXString("ObjCPropertyDecl");
2955  case CXCursor_ObjCIvarDecl:
2956      return createCXString("ObjCIvarDecl");
2957  case CXCursor_ObjCInstanceMethodDecl:
2958      return createCXString("ObjCInstanceMethodDecl");
2959  case CXCursor_ObjCClassMethodDecl:
2960      return createCXString("ObjCClassMethodDecl");
2961  case CXCursor_ObjCImplementationDecl:
2962      return createCXString("ObjCImplementationDecl");
2963  case CXCursor_ObjCCategoryImplDecl:
2964      return createCXString("ObjCCategoryImplDecl");
2965  case CXCursor_CXXMethod:
2966      return createCXString("CXXMethod");
2967  case CXCursor_UnexposedDecl:
2968      return createCXString("UnexposedDecl");
2969  case CXCursor_ObjCSuperClassRef:
2970      return createCXString("ObjCSuperClassRef");
2971  case CXCursor_ObjCProtocolRef:
2972      return createCXString("ObjCProtocolRef");
2973  case CXCursor_ObjCClassRef:
2974      return createCXString("ObjCClassRef");
2975  case CXCursor_TypeRef:
2976      return createCXString("TypeRef");
2977  case CXCursor_TemplateRef:
2978      return createCXString("TemplateRef");
2979  case CXCursor_NamespaceRef:
2980    return createCXString("NamespaceRef");
2981  case CXCursor_MemberRef:
2982    return createCXString("MemberRef");
2983  case CXCursor_LabelRef:
2984    return createCXString("LabelRef");
2985  case CXCursor_OverloadedDeclRef:
2986    return createCXString("OverloadedDeclRef");
2987  case CXCursor_UnexposedExpr:
2988      return createCXString("UnexposedExpr");
2989  case CXCursor_BlockExpr:
2990      return createCXString("BlockExpr");
2991  case CXCursor_DeclRefExpr:
2992      return createCXString("DeclRefExpr");
2993  case CXCursor_MemberRefExpr:
2994      return createCXString("MemberRefExpr");
2995  case CXCursor_CallExpr:
2996      return createCXString("CallExpr");
2997  case CXCursor_ObjCMessageExpr:
2998      return createCXString("ObjCMessageExpr");
2999  case CXCursor_UnexposedStmt:
3000      return createCXString("UnexposedStmt");
3001  case CXCursor_LabelStmt:
3002      return createCXString("LabelStmt");
3003  case CXCursor_InvalidFile:
3004      return createCXString("InvalidFile");
3005  case CXCursor_InvalidCode:
3006    return createCXString("InvalidCode");
3007  case CXCursor_NoDeclFound:
3008      return createCXString("NoDeclFound");
3009  case CXCursor_NotImplemented:
3010      return createCXString("NotImplemented");
3011  case CXCursor_TranslationUnit:
3012      return createCXString("TranslationUnit");
3013  case CXCursor_UnexposedAttr:
3014      return createCXString("UnexposedAttr");
3015  case CXCursor_IBActionAttr:
3016      return createCXString("attribute(ibaction)");
3017  case CXCursor_IBOutletAttr:
3018     return createCXString("attribute(iboutlet)");
3019  case CXCursor_IBOutletCollectionAttr:
3020      return createCXString("attribute(iboutletcollection)");
3021  case CXCursor_PreprocessingDirective:
3022    return createCXString("preprocessing directive");
3023  case CXCursor_MacroDefinition:
3024    return createCXString("macro definition");
3025  case CXCursor_MacroInstantiation:
3026    return createCXString("macro instantiation");
3027  case CXCursor_InclusionDirective:
3028    return createCXString("inclusion directive");
3029  case CXCursor_Namespace:
3030    return createCXString("Namespace");
3031  case CXCursor_LinkageSpec:
3032    return createCXString("LinkageSpec");
3033  case CXCursor_CXXBaseSpecifier:
3034    return createCXString("C++ base class specifier");
3035  case CXCursor_Constructor:
3036    return createCXString("CXXConstructor");
3037  case CXCursor_Destructor:
3038    return createCXString("CXXDestructor");
3039  case CXCursor_ConversionFunction:
3040    return createCXString("CXXConversion");
3041  case CXCursor_TemplateTypeParameter:
3042    return createCXString("TemplateTypeParameter");
3043  case CXCursor_NonTypeTemplateParameter:
3044    return createCXString("NonTypeTemplateParameter");
3045  case CXCursor_TemplateTemplateParameter:
3046    return createCXString("TemplateTemplateParameter");
3047  case CXCursor_FunctionTemplate:
3048    return createCXString("FunctionTemplate");
3049  case CXCursor_ClassTemplate:
3050    return createCXString("ClassTemplate");
3051  case CXCursor_ClassTemplatePartialSpecialization:
3052    return createCXString("ClassTemplatePartialSpecialization");
3053  case CXCursor_NamespaceAlias:
3054    return createCXString("NamespaceAlias");
3055  case CXCursor_UsingDirective:
3056    return createCXString("UsingDirective");
3057  case CXCursor_UsingDeclaration:
3058    return createCXString("UsingDeclaration");
3059  }
3060
3061  llvm_unreachable("Unhandled CXCursorKind");
3062  return createCXString(NULL);
3063}
3064
3065enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
3066                                         CXCursor parent,
3067                                         CXClientData client_data) {
3068  CXCursor *BestCursor = static_cast<CXCursor *>(client_data);
3069
3070  // If our current best cursor is the construction of a temporary object,
3071  // don't replace that cursor with a type reference, because we want
3072  // clang_getCursor() to point at the constructor.
3073  if (clang_isExpression(BestCursor->kind) &&
3074      isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
3075      cursor.kind == CXCursor_TypeRef)
3076    return CXChildVisit_Recurse;
3077
3078  *BestCursor = cursor;
3079  return CXChildVisit_Recurse;
3080}
3081
3082CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
3083  if (!TU)
3084    return clang_getNullCursor();
3085
3086  ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
3087  ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3088
3089  // Translate the given source location to make it point at the beginning of
3090  // the token under the cursor.
3091  SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
3092
3093  // Guard against an invalid SourceLocation, or we may assert in one
3094  // of the following calls.
3095  if (SLoc.isInvalid())
3096    return clang_getNullCursor();
3097
3098  bool Logging = getenv("LIBCLANG_LOGGING");
3099  SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
3100                                    CXXUnit->getASTContext().getLangOptions());
3101
3102  CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
3103  if (SLoc.isValid()) {
3104    // FIXME: Would be great to have a "hint" cursor, then walk from that
3105    // hint cursor upward until we find a cursor whose source range encloses
3106    // the region of interest, rather than starting from the translation unit.
3107    CXCursor Parent = clang_getTranslationUnitCursor(CXXUnit);
3108    CursorVisitor CursorVis(CXXUnit, GetCursorVisitor, &Result,
3109                            Decl::MaxPCHLevel, SourceLocation(SLoc));
3110    CursorVis.VisitChildren(Parent);
3111  }
3112
3113  if (Logging) {
3114    CXFile SearchFile;
3115    unsigned SearchLine, SearchColumn;
3116    CXFile ResultFile;
3117    unsigned ResultLine, ResultColumn;
3118    CXString SearchFileName, ResultFileName, KindSpelling;
3119    CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
3120
3121    clang_getInstantiationLocation(Loc, &SearchFile, &SearchLine, &SearchColumn,
3122                                   0);
3123    clang_getInstantiationLocation(ResultLoc, &ResultFile, &ResultLine,
3124                                   &ResultColumn, 0);
3125    SearchFileName = clang_getFileName(SearchFile);
3126    ResultFileName = clang_getFileName(ResultFile);
3127    KindSpelling = clang_getCursorKindSpelling(Result.kind);
3128    fprintf(stderr, "clang_getCursor(%s:%d:%d) = %s(%s:%d:%d)\n",
3129            clang_getCString(SearchFileName), SearchLine, SearchColumn,
3130            clang_getCString(KindSpelling),
3131            clang_getCString(ResultFileName), ResultLine, ResultColumn);
3132    clang_disposeString(SearchFileName);
3133    clang_disposeString(ResultFileName);
3134    clang_disposeString(KindSpelling);
3135  }
3136
3137  return Result;
3138}
3139
3140CXCursor clang_getNullCursor(void) {
3141  return MakeCXCursorInvalid(CXCursor_InvalidFile);
3142}
3143
3144unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
3145  return X == Y;
3146}
3147
3148unsigned clang_isInvalid(enum CXCursorKind K) {
3149  return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
3150}
3151
3152unsigned clang_isDeclaration(enum CXCursorKind K) {
3153  return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
3154}
3155
3156unsigned clang_isReference(enum CXCursorKind K) {
3157  return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
3158}
3159
3160unsigned clang_isExpression(enum CXCursorKind K) {
3161  return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
3162}
3163
3164unsigned clang_isStatement(enum CXCursorKind K) {
3165  return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
3166}
3167
3168unsigned clang_isTranslationUnit(enum CXCursorKind K) {
3169  return K == CXCursor_TranslationUnit;
3170}
3171
3172unsigned clang_isPreprocessing(enum CXCursorKind K) {
3173  return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
3174}
3175
3176unsigned clang_isUnexposed(enum CXCursorKind K) {
3177  switch (K) {
3178    case CXCursor_UnexposedDecl:
3179    case CXCursor_UnexposedExpr:
3180    case CXCursor_UnexposedStmt:
3181    case CXCursor_UnexposedAttr:
3182      return true;
3183    default:
3184      return false;
3185  }
3186}
3187
3188CXCursorKind clang_getCursorKind(CXCursor C) {
3189  return C.kind;
3190}
3191
3192CXSourceLocation clang_getCursorLocation(CXCursor C) {
3193  if (clang_isReference(C.kind)) {
3194    switch (C.kind) {
3195    case CXCursor_ObjCSuperClassRef: {
3196      std::pair<ObjCInterfaceDecl *, SourceLocation> P
3197        = getCursorObjCSuperClassRef(C);
3198      return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3199    }
3200
3201    case CXCursor_ObjCProtocolRef: {
3202      std::pair<ObjCProtocolDecl *, SourceLocation> P
3203        = getCursorObjCProtocolRef(C);
3204      return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3205    }
3206
3207    case CXCursor_ObjCClassRef: {
3208      std::pair<ObjCInterfaceDecl *, SourceLocation> P
3209        = getCursorObjCClassRef(C);
3210      return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3211    }
3212
3213    case CXCursor_TypeRef: {
3214      std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
3215      return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3216    }
3217
3218    case CXCursor_TemplateRef: {
3219      std::pair<TemplateDecl *, SourceLocation> P = getCursorTemplateRef(C);
3220      return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3221    }
3222
3223    case CXCursor_NamespaceRef: {
3224      std::pair<NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
3225      return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3226    }
3227
3228    case CXCursor_MemberRef: {
3229      std::pair<FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
3230      return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3231    }
3232
3233    case CXCursor_CXXBaseSpecifier: {
3234      CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
3235      if (!BaseSpec)
3236        return clang_getNullLocation();
3237
3238      if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
3239        return cxloc::translateSourceLocation(getCursorContext(C),
3240                                            TSInfo->getTypeLoc().getBeginLoc());
3241
3242      return cxloc::translateSourceLocation(getCursorContext(C),
3243                                        BaseSpec->getSourceRange().getBegin());
3244    }
3245
3246    case CXCursor_LabelRef: {
3247      std::pair<LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
3248      return cxloc::translateSourceLocation(getCursorContext(C), P.second);
3249    }
3250
3251    case CXCursor_OverloadedDeclRef:
3252      return cxloc::translateSourceLocation(getCursorContext(C),
3253                                          getCursorOverloadedDeclRef(C).second);
3254
3255    default:
3256      // FIXME: Need a way to enumerate all non-reference cases.
3257      llvm_unreachable("Missed a reference kind");
3258    }
3259  }
3260
3261  if (clang_isExpression(C.kind))
3262    return cxloc::translateSourceLocation(getCursorContext(C),
3263                                   getLocationFromExpr(getCursorExpr(C)));
3264
3265  if (clang_isStatement(C.kind))
3266    return cxloc::translateSourceLocation(getCursorContext(C),
3267                                          getCursorStmt(C)->getLocStart());
3268
3269  if (C.kind == CXCursor_PreprocessingDirective) {
3270    SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
3271    return cxloc::translateSourceLocation(getCursorContext(C), L);
3272  }
3273
3274  if (C.kind == CXCursor_MacroInstantiation) {
3275    SourceLocation L
3276      = cxcursor::getCursorMacroInstantiation(C)->getSourceRange().getBegin();
3277    return cxloc::translateSourceLocation(getCursorContext(C), L);
3278  }
3279
3280  if (C.kind == CXCursor_MacroDefinition) {
3281    SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
3282    return cxloc::translateSourceLocation(getCursorContext(C), L);
3283  }
3284
3285  if (C.kind == CXCursor_InclusionDirective) {
3286    SourceLocation L
3287      = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
3288    return cxloc::translateSourceLocation(getCursorContext(C), L);
3289  }
3290
3291  if (C.kind < CXCursor_FirstDecl || C.kind > CXCursor_LastDecl)
3292    return clang_getNullLocation();
3293
3294  Decl *D = getCursorDecl(C);
3295  SourceLocation Loc = D->getLocation();
3296  if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
3297    Loc = Class->getClassLoc();
3298  // FIXME: Multiple variables declared in a single declaration
3299  // currently lack the information needed to correctly determine their
3300  // ranges when accounting for the type-specifier.  We use context
3301  // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3302  // and if so, whether it is the first decl.
3303  if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3304    if (!cxcursor::isFirstInDeclGroup(C))
3305      Loc = VD->getLocation();
3306  }
3307
3308  return cxloc::translateSourceLocation(getCursorContext(C), Loc);
3309}
3310
3311} // end extern "C"
3312
3313static SourceRange getRawCursorExtent(CXCursor C) {
3314  if (clang_isReference(C.kind)) {
3315    switch (C.kind) {
3316    case CXCursor_ObjCSuperClassRef:
3317      return  getCursorObjCSuperClassRef(C).second;
3318
3319    case CXCursor_ObjCProtocolRef:
3320      return getCursorObjCProtocolRef(C).second;
3321
3322    case CXCursor_ObjCClassRef:
3323      return getCursorObjCClassRef(C).second;
3324
3325    case CXCursor_TypeRef:
3326      return getCursorTypeRef(C).second;
3327
3328    case CXCursor_TemplateRef:
3329      return getCursorTemplateRef(C).second;
3330
3331    case CXCursor_NamespaceRef:
3332      return getCursorNamespaceRef(C).second;
3333
3334    case CXCursor_MemberRef:
3335      return getCursorMemberRef(C).second;
3336
3337    case CXCursor_CXXBaseSpecifier:
3338      return getCursorCXXBaseSpecifier(C)->getSourceRange();
3339
3340    case CXCursor_LabelRef:
3341      return getCursorLabelRef(C).second;
3342
3343    case CXCursor_OverloadedDeclRef:
3344      return getCursorOverloadedDeclRef(C).second;
3345
3346    default:
3347      // FIXME: Need a way to enumerate all non-reference cases.
3348      llvm_unreachable("Missed a reference kind");
3349    }
3350  }
3351
3352  if (clang_isExpression(C.kind))
3353    return getCursorExpr(C)->getSourceRange();
3354
3355  if (clang_isStatement(C.kind))
3356    return getCursorStmt(C)->getSourceRange();
3357
3358  if (C.kind == CXCursor_PreprocessingDirective)
3359    return cxcursor::getCursorPreprocessingDirective(C);
3360
3361  if (C.kind == CXCursor_MacroInstantiation)
3362    return cxcursor::getCursorMacroInstantiation(C)->getSourceRange();
3363
3364  if (C.kind == CXCursor_MacroDefinition)
3365    return cxcursor::getCursorMacroDefinition(C)->getSourceRange();
3366
3367  if (C.kind == CXCursor_InclusionDirective)
3368    return cxcursor::getCursorInclusionDirective(C)->getSourceRange();
3369
3370  if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
3371    Decl *D = cxcursor::getCursorDecl(C);
3372    SourceRange R = D->getSourceRange();
3373    // FIXME: Multiple variables declared in a single declaration
3374    // currently lack the information needed to correctly determine their
3375    // ranges when accounting for the type-specifier.  We use context
3376    // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3377    // and if so, whether it is the first decl.
3378    if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3379      if (!cxcursor::isFirstInDeclGroup(C))
3380        R.setBegin(VD->getLocation());
3381    }
3382    return R;
3383  }
3384  return SourceRange();}
3385
3386extern "C" {
3387
3388CXSourceRange clang_getCursorExtent(CXCursor C) {
3389  SourceRange R = getRawCursorExtent(C);
3390  if (R.isInvalid())
3391    return clang_getNullRange();
3392
3393  return cxloc::translateSourceRange(getCursorContext(C), R);
3394}
3395
3396CXCursor clang_getCursorReferenced(CXCursor C) {
3397  if (clang_isInvalid(C.kind))
3398    return clang_getNullCursor();
3399
3400  ASTUnit *CXXUnit = getCursorASTUnit(C);
3401  if (clang_isDeclaration(C.kind)) {
3402    Decl *D = getCursorDecl(C);
3403    if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
3404      return MakeCursorOverloadedDeclRef(Using, D->getLocation(), CXXUnit);
3405    if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
3406      return MakeCursorOverloadedDeclRef(Classes, D->getLocation(), CXXUnit);
3407    if (ObjCForwardProtocolDecl *Protocols
3408                                        = dyn_cast<ObjCForwardProtocolDecl>(D))
3409      return MakeCursorOverloadedDeclRef(Protocols, D->getLocation(), CXXUnit);
3410
3411    return C;
3412  }
3413
3414  if (clang_isExpression(C.kind)) {
3415    Expr *E = getCursorExpr(C);
3416    Decl *D = getDeclFromExpr(E);
3417    if (D)
3418      return MakeCXCursor(D, CXXUnit);
3419
3420    if (OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
3421      return MakeCursorOverloadedDeclRef(Ovl, CXXUnit);
3422
3423    return clang_getNullCursor();
3424  }
3425
3426  if (clang_isStatement(C.kind)) {
3427    Stmt *S = getCursorStmt(C);
3428    if (GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
3429      return MakeCXCursor(Goto->getLabel(), getCursorDecl(C),
3430                          getCursorASTUnit(C));
3431
3432    return clang_getNullCursor();
3433  }
3434
3435  if (C.kind == CXCursor_MacroInstantiation) {
3436    if (MacroDefinition *Def = getCursorMacroInstantiation(C)->getDefinition())
3437      return MakeMacroDefinitionCursor(Def, CXXUnit);
3438  }
3439
3440  if (!clang_isReference(C.kind))
3441    return clang_getNullCursor();
3442
3443  switch (C.kind) {
3444    case CXCursor_ObjCSuperClassRef:
3445      return MakeCXCursor(getCursorObjCSuperClassRef(C).first, CXXUnit);
3446
3447    case CXCursor_ObjCProtocolRef: {
3448      return MakeCXCursor(getCursorObjCProtocolRef(C).first, CXXUnit);
3449
3450    case CXCursor_ObjCClassRef:
3451      return MakeCXCursor(getCursorObjCClassRef(C).first, CXXUnit);
3452
3453    case CXCursor_TypeRef:
3454      return MakeCXCursor(getCursorTypeRef(C).first, CXXUnit);
3455
3456    case CXCursor_TemplateRef:
3457      return MakeCXCursor(getCursorTemplateRef(C).first, CXXUnit);
3458
3459    case CXCursor_NamespaceRef:
3460      return MakeCXCursor(getCursorNamespaceRef(C).first, CXXUnit);
3461
3462    case CXCursor_MemberRef:
3463      return MakeCXCursor(getCursorMemberRef(C).first, CXXUnit);
3464
3465    case CXCursor_CXXBaseSpecifier: {
3466      CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
3467      return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
3468                                                         CXXUnit));
3469    }
3470
3471    case CXCursor_LabelRef:
3472      // FIXME: We end up faking the "parent" declaration here because we
3473      // don't want to make CXCursor larger.
3474      return MakeCXCursor(getCursorLabelRef(C).first,
3475                          CXXUnit->getASTContext().getTranslationUnitDecl(),
3476                          CXXUnit);
3477
3478    case CXCursor_OverloadedDeclRef:
3479      return C;
3480
3481    default:
3482      // We would prefer to enumerate all non-reference cursor kinds here.
3483      llvm_unreachable("Unhandled reference cursor kind");
3484      break;
3485    }
3486  }
3487
3488  return clang_getNullCursor();
3489}
3490
3491CXCursor clang_getCursorDefinition(CXCursor C) {
3492  if (clang_isInvalid(C.kind))
3493    return clang_getNullCursor();
3494
3495  ASTUnit *CXXUnit = getCursorASTUnit(C);
3496
3497  bool WasReference = false;
3498  if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
3499    C = clang_getCursorReferenced(C);
3500    WasReference = true;
3501  }
3502
3503  if (C.kind == CXCursor_MacroInstantiation)
3504    return clang_getCursorReferenced(C);
3505
3506  if (!clang_isDeclaration(C.kind))
3507    return clang_getNullCursor();
3508
3509  Decl *D = getCursorDecl(C);
3510  if (!D)
3511    return clang_getNullCursor();
3512
3513  switch (D->getKind()) {
3514  // Declaration kinds that don't really separate the notions of
3515  // declaration and definition.
3516  case Decl::Namespace:
3517  case Decl::Typedef:
3518  case Decl::TemplateTypeParm:
3519  case Decl::EnumConstant:
3520  case Decl::Field:
3521  case Decl::ObjCIvar:
3522  case Decl::ObjCAtDefsField:
3523  case Decl::ImplicitParam:
3524  case Decl::ParmVar:
3525  case Decl::NonTypeTemplateParm:
3526  case Decl::TemplateTemplateParm:
3527  case Decl::ObjCCategoryImpl:
3528  case Decl::ObjCImplementation:
3529  case Decl::AccessSpec:
3530  case Decl::LinkageSpec:
3531  case Decl::ObjCPropertyImpl:
3532  case Decl::FileScopeAsm:
3533  case Decl::StaticAssert:
3534  case Decl::Block:
3535    return C;
3536
3537  // Declaration kinds that don't make any sense here, but are
3538  // nonetheless harmless.
3539  case Decl::TranslationUnit:
3540    break;
3541
3542  // Declaration kinds for which the definition is not resolvable.
3543  case Decl::UnresolvedUsingTypename:
3544  case Decl::UnresolvedUsingValue:
3545    break;
3546
3547  case Decl::UsingDirective:
3548    return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
3549                        CXXUnit);
3550
3551  case Decl::NamespaceAlias:
3552    return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), CXXUnit);
3553
3554  case Decl::Enum:
3555  case Decl::Record:
3556  case Decl::CXXRecord:
3557  case Decl::ClassTemplateSpecialization:
3558  case Decl::ClassTemplatePartialSpecialization:
3559    if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
3560      return MakeCXCursor(Def, CXXUnit);
3561    return clang_getNullCursor();
3562
3563  case Decl::Function:
3564  case Decl::CXXMethod:
3565  case Decl::CXXConstructor:
3566  case Decl::CXXDestructor:
3567  case Decl::CXXConversion: {
3568    const FunctionDecl *Def = 0;
3569    if (cast<FunctionDecl>(D)->getBody(Def))
3570      return MakeCXCursor(const_cast<FunctionDecl *>(Def), CXXUnit);
3571    return clang_getNullCursor();
3572  }
3573
3574  case Decl::Var: {
3575    // Ask the variable if it has a definition.
3576    if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
3577      return MakeCXCursor(Def, CXXUnit);
3578    return clang_getNullCursor();
3579  }
3580
3581  case Decl::FunctionTemplate: {
3582    const FunctionDecl *Def = 0;
3583    if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
3584      return MakeCXCursor(Def->getDescribedFunctionTemplate(), CXXUnit);
3585    return clang_getNullCursor();
3586  }
3587
3588  case Decl::ClassTemplate: {
3589    if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
3590                                                            ->getDefinition())
3591      return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
3592                          CXXUnit);
3593    return clang_getNullCursor();
3594  }
3595
3596  case Decl::Using:
3597    return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
3598                                       D->getLocation(), CXXUnit);
3599
3600  case Decl::UsingShadow:
3601    return clang_getCursorDefinition(
3602                       MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
3603                                    CXXUnit));
3604
3605  case Decl::ObjCMethod: {
3606    ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
3607    if (Method->isThisDeclarationADefinition())
3608      return C;
3609
3610    // Dig out the method definition in the associated
3611    // @implementation, if we have it.
3612    // FIXME: The ASTs should make finding the definition easier.
3613    if (ObjCInterfaceDecl *Class
3614                       = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
3615      if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
3616        if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
3617                                                  Method->isInstanceMethod()))
3618          if (Def->isThisDeclarationADefinition())
3619            return MakeCXCursor(Def, CXXUnit);
3620
3621    return clang_getNullCursor();
3622  }
3623
3624  case Decl::ObjCCategory:
3625    if (ObjCCategoryImplDecl *Impl
3626                               = cast<ObjCCategoryDecl>(D)->getImplementation())
3627      return MakeCXCursor(Impl, CXXUnit);
3628    return clang_getNullCursor();
3629
3630  case Decl::ObjCProtocol:
3631    if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
3632      return C;
3633    return clang_getNullCursor();
3634
3635  case Decl::ObjCInterface:
3636    // There are two notions of a "definition" for an Objective-C
3637    // class: the interface and its implementation. When we resolved a
3638    // reference to an Objective-C class, produce the @interface as
3639    // the definition; when we were provided with the interface,
3640    // produce the @implementation as the definition.
3641    if (WasReference) {
3642      if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
3643        return C;
3644    } else if (ObjCImplementationDecl *Impl
3645                              = cast<ObjCInterfaceDecl>(D)->getImplementation())
3646      return MakeCXCursor(Impl, CXXUnit);
3647    return clang_getNullCursor();
3648
3649  case Decl::ObjCProperty:
3650    // FIXME: We don't really know where to find the
3651    // ObjCPropertyImplDecls that implement this property.
3652    return clang_getNullCursor();
3653
3654  case Decl::ObjCCompatibleAlias:
3655    if (ObjCInterfaceDecl *Class
3656          = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
3657      if (!Class->isForwardDecl())
3658        return MakeCXCursor(Class, CXXUnit);
3659
3660    return clang_getNullCursor();
3661
3662  case Decl::ObjCForwardProtocol:
3663    return MakeCursorOverloadedDeclRef(cast<ObjCForwardProtocolDecl>(D),
3664                                       D->getLocation(), CXXUnit);
3665
3666  case Decl::ObjCClass:
3667    return MakeCursorOverloadedDeclRef(cast<ObjCClassDecl>(D), D->getLocation(),
3668                                       CXXUnit);
3669
3670  case Decl::Friend:
3671    if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
3672      return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
3673    return clang_getNullCursor();
3674
3675  case Decl::FriendTemplate:
3676    if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
3677      return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
3678    return clang_getNullCursor();
3679  }
3680
3681  return clang_getNullCursor();
3682}
3683
3684unsigned clang_isCursorDefinition(CXCursor C) {
3685  if (!clang_isDeclaration(C.kind))
3686    return 0;
3687
3688  return clang_getCursorDefinition(C) == C;
3689}
3690
3691unsigned clang_getNumOverloadedDecls(CXCursor C) {
3692  if (C.kind != CXCursor_OverloadedDeclRef)
3693    return 0;
3694
3695  OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
3696  if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
3697    return E->getNumDecls();
3698
3699  if (OverloadedTemplateStorage *S
3700                              = Storage.dyn_cast<OverloadedTemplateStorage*>())
3701    return S->size();
3702
3703  Decl *D = Storage.get<Decl*>();
3704  if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
3705    return Using->shadow_size();
3706  if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
3707    return Classes->size();
3708  if (ObjCForwardProtocolDecl *Protocols =dyn_cast<ObjCForwardProtocolDecl>(D))
3709    return Protocols->protocol_size();
3710
3711  return 0;
3712}
3713
3714CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
3715  if (cursor.kind != CXCursor_OverloadedDeclRef)
3716    return clang_getNullCursor();
3717
3718  if (index >= clang_getNumOverloadedDecls(cursor))
3719    return clang_getNullCursor();
3720
3721  ASTUnit *Unit = getCursorASTUnit(cursor);
3722  OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
3723  if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
3724    return MakeCXCursor(E->decls_begin()[index], Unit);
3725
3726  if (OverloadedTemplateStorage *S
3727                              = Storage.dyn_cast<OverloadedTemplateStorage*>())
3728    return MakeCXCursor(S->begin()[index], Unit);
3729
3730  Decl *D = Storage.get<Decl*>();
3731  if (UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
3732    // FIXME: This is, unfortunately, linear time.
3733    UsingDecl::shadow_iterator Pos = Using->shadow_begin();
3734    std::advance(Pos, index);
3735    return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), Unit);
3736  }
3737
3738  if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
3739    return MakeCXCursor(Classes->begin()[index].getInterface(), Unit);
3740
3741  if (ObjCForwardProtocolDecl *Protocols = dyn_cast<ObjCForwardProtocolDecl>(D))
3742    return MakeCXCursor(Protocols->protocol_begin()[index], Unit);
3743
3744  return clang_getNullCursor();
3745}
3746
3747void clang_getDefinitionSpellingAndExtent(CXCursor C,
3748                                          const char **startBuf,
3749                                          const char **endBuf,
3750                                          unsigned *startLine,
3751                                          unsigned *startColumn,
3752                                          unsigned *endLine,
3753                                          unsigned *endColumn) {
3754  assert(getCursorDecl(C) && "CXCursor has null decl");
3755  NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
3756  FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
3757  CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
3758
3759  SourceManager &SM = FD->getASTContext().getSourceManager();
3760  *startBuf = SM.getCharacterData(Body->getLBracLoc());
3761  *endBuf = SM.getCharacterData(Body->getRBracLoc());
3762  *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
3763  *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
3764  *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
3765  *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
3766}
3767
3768void clang_enableStackTraces(void) {
3769  llvm::sys::PrintStackTraceOnErrorSignal();
3770}
3771
3772void clang_executeOnThread(void (*fn)(void*), void *user_data,
3773                           unsigned stack_size) {
3774  llvm::llvm_execute_on_thread(fn, user_data, stack_size);
3775}
3776
3777} // end: extern "C"
3778
3779//===----------------------------------------------------------------------===//
3780// Token-based Operations.
3781//===----------------------------------------------------------------------===//
3782
3783/* CXToken layout:
3784 *   int_data[0]: a CXTokenKind
3785 *   int_data[1]: starting token location
3786 *   int_data[2]: token length
3787 *   int_data[3]: reserved
3788 *   ptr_data: for identifiers and keywords, an IdentifierInfo*.
3789 *   otherwise unused.
3790 */
3791extern "C" {
3792
3793CXTokenKind clang_getTokenKind(CXToken CXTok) {
3794  return static_cast<CXTokenKind>(CXTok.int_data[0]);
3795}
3796
3797CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
3798  switch (clang_getTokenKind(CXTok)) {
3799  case CXToken_Identifier:
3800  case CXToken_Keyword:
3801    // We know we have an IdentifierInfo*, so use that.
3802    return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
3803                            ->getNameStart());
3804
3805  case CXToken_Literal: {
3806    // We have stashed the starting pointer in the ptr_data field. Use it.
3807    const char *Text = static_cast<const char *>(CXTok.ptr_data);
3808    return createCXString(llvm::StringRef(Text, CXTok.int_data[2]));
3809  }
3810
3811  case CXToken_Punctuation:
3812  case CXToken_Comment:
3813    break;
3814  }
3815
3816  // We have to find the starting buffer pointer the hard way, by
3817  // deconstructing the source location.
3818  ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
3819  if (!CXXUnit)
3820    return createCXString("");
3821
3822  SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
3823  std::pair<FileID, unsigned> LocInfo
3824    = CXXUnit->getSourceManager().getDecomposedLoc(Loc);
3825  bool Invalid = false;
3826  llvm::StringRef Buffer
3827    = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
3828  if (Invalid)
3829    return createCXString("");
3830
3831  return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
3832}
3833
3834CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
3835  ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
3836  if (!CXXUnit)
3837    return clang_getNullLocation();
3838
3839  return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
3840                        SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
3841}
3842
3843CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
3844  ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
3845  if (!CXXUnit)
3846    return clang_getNullRange();
3847
3848  return cxloc::translateSourceRange(CXXUnit->getASTContext(),
3849                        SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
3850}
3851
3852void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
3853                    CXToken **Tokens, unsigned *NumTokens) {
3854  if (Tokens)
3855    *Tokens = 0;
3856  if (NumTokens)
3857    *NumTokens = 0;
3858
3859  ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
3860  if (!CXXUnit || !Tokens || !NumTokens)
3861    return;
3862
3863  ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3864
3865  SourceRange R = cxloc::translateCXSourceRange(Range);
3866  if (R.isInvalid())
3867    return;
3868
3869  SourceManager &SourceMgr = CXXUnit->getSourceManager();
3870  std::pair<FileID, unsigned> BeginLocInfo
3871    = SourceMgr.getDecomposedLoc(R.getBegin());
3872  std::pair<FileID, unsigned> EndLocInfo
3873    = SourceMgr.getDecomposedLoc(R.getEnd());
3874
3875  // Cannot tokenize across files.
3876  if (BeginLocInfo.first != EndLocInfo.first)
3877    return;
3878
3879  // Create a lexer
3880  bool Invalid = false;
3881  llvm::StringRef Buffer
3882    = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
3883  if (Invalid)
3884    return;
3885
3886  Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
3887            CXXUnit->getASTContext().getLangOptions(),
3888            Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
3889  Lex.SetCommentRetentionState(true);
3890
3891  // Lex tokens until we hit the end of the range.
3892  const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
3893  llvm::SmallVector<CXToken, 32> CXTokens;
3894  Token Tok;
3895  bool previousWasAt = false;
3896  do {
3897    // Lex the next token
3898    Lex.LexFromRawLexer(Tok);
3899    if (Tok.is(tok::eof))
3900      break;
3901
3902    // Initialize the CXToken.
3903    CXToken CXTok;
3904
3905    //   - Common fields
3906    CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
3907    CXTok.int_data[2] = Tok.getLength();
3908    CXTok.int_data[3] = 0;
3909
3910    //   - Kind-specific fields
3911    if (Tok.isLiteral()) {
3912      CXTok.int_data[0] = CXToken_Literal;
3913      CXTok.ptr_data = (void *)Tok.getLiteralData();
3914    } else if (Tok.is(tok::identifier)) {
3915      // Lookup the identifier to determine whether we have a keyword.
3916      std::pair<FileID, unsigned> LocInfo
3917        = SourceMgr.getDecomposedLoc(Tok.getLocation());
3918      bool Invalid = false;
3919      llvm::StringRef Buf
3920        = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
3921      if (Invalid)
3922        return;
3923
3924      const char *StartPos = Buf.data() + LocInfo.second;
3925      IdentifierInfo *II
3926        = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok, StartPos);
3927
3928      if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
3929        CXTok.int_data[0] = CXToken_Keyword;
3930      }
3931      else {
3932        CXTok.int_data[0] = II->getTokenID() == tok::identifier?
3933                                CXToken_Identifier
3934                              : CXToken_Keyword;
3935      }
3936      CXTok.ptr_data = II;
3937    } else if (Tok.is(tok::comment)) {
3938      CXTok.int_data[0] = CXToken_Comment;
3939      CXTok.ptr_data = 0;
3940    } else {
3941      CXTok.int_data[0] = CXToken_Punctuation;
3942      CXTok.ptr_data = 0;
3943    }
3944    CXTokens.push_back(CXTok);
3945    previousWasAt = Tok.is(tok::at);
3946  } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
3947
3948  if (CXTokens.empty())
3949    return;
3950
3951  *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
3952  memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
3953  *NumTokens = CXTokens.size();
3954}
3955
3956void clang_disposeTokens(CXTranslationUnit TU,
3957                         CXToken *Tokens, unsigned NumTokens) {
3958  free(Tokens);
3959}
3960
3961} // end: extern "C"
3962
3963//===----------------------------------------------------------------------===//
3964// Token annotation APIs.
3965//===----------------------------------------------------------------------===//
3966
3967typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
3968static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
3969                                                     CXCursor parent,
3970                                                     CXClientData client_data);
3971namespace {
3972class AnnotateTokensWorker {
3973  AnnotateTokensData &Annotated;
3974  CXToken *Tokens;
3975  CXCursor *Cursors;
3976  unsigned NumTokens;
3977  unsigned TokIdx;
3978  unsigned PreprocessingTokIdx;
3979  CursorVisitor AnnotateVis;
3980  SourceManager &SrcMgr;
3981
3982  bool MoreTokens() const { return TokIdx < NumTokens; }
3983  unsigned NextToken() const { return TokIdx; }
3984  void AdvanceToken() { ++TokIdx; }
3985  SourceLocation GetTokenLoc(unsigned tokI) {
3986    return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
3987  }
3988
3989public:
3990  AnnotateTokensWorker(AnnotateTokensData &annotated,
3991                       CXToken *tokens, CXCursor *cursors, unsigned numTokens,
3992                       ASTUnit *CXXUnit, SourceRange RegionOfInterest)
3993    : Annotated(annotated), Tokens(tokens), Cursors(cursors),
3994      NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0),
3995      AnnotateVis(CXXUnit, AnnotateTokensVisitor, this,
3996                  Decl::MaxPCHLevel, RegionOfInterest),
3997      SrcMgr(CXXUnit->getSourceManager()) {}
3998
3999  void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
4000  enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
4001  void AnnotateTokens(CXCursor parent);
4002  void AnnotateTokens() {
4003    AnnotateTokens(clang_getTranslationUnitCursor(AnnotateVis.getASTUnit()));
4004  }
4005};
4006}
4007
4008void AnnotateTokensWorker::AnnotateTokens(CXCursor parent) {
4009  // Walk the AST within the region of interest, annotating tokens
4010  // along the way.
4011  VisitChildren(parent);
4012
4013  for (unsigned I = 0 ; I < TokIdx ; ++I) {
4014    AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
4015    if (Pos != Annotated.end() &&
4016        (clang_isInvalid(Cursors[I].kind) ||
4017         Pos->second.kind != CXCursor_PreprocessingDirective))
4018      Cursors[I] = Pos->second;
4019  }
4020
4021  // Finish up annotating any tokens left.
4022  if (!MoreTokens())
4023    return;
4024
4025  const CXCursor &C = clang_getNullCursor();
4026  for (unsigned I = TokIdx ; I < NumTokens ; ++I) {
4027    AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
4028    Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second;
4029  }
4030}
4031
4032enum CXChildVisitResult
4033AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
4034  CXSourceLocation Loc = clang_getCursorLocation(cursor);
4035  SourceRange cursorRange = getRawCursorExtent(cursor);
4036  if (cursorRange.isInvalid())
4037    return CXChildVisit_Recurse;
4038
4039  if (clang_isPreprocessing(cursor.kind)) {
4040    // For macro instantiations, just note where the beginning of the macro
4041    // instantiation occurs.
4042    if (cursor.kind == CXCursor_MacroInstantiation) {
4043      Annotated[Loc.int_data] = cursor;
4044      return CXChildVisit_Recurse;
4045    }
4046
4047    // Items in the preprocessing record are kept separate from items in
4048    // declarations, so we keep a separate token index.
4049    unsigned SavedTokIdx = TokIdx;
4050    TokIdx = PreprocessingTokIdx;
4051
4052    // Skip tokens up until we catch up to the beginning of the preprocessing
4053    // entry.
4054    while (MoreTokens()) {
4055      const unsigned I = NextToken();
4056      SourceLocation TokLoc = GetTokenLoc(I);
4057      switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4058      case RangeBefore:
4059        AdvanceToken();
4060        continue;
4061      case RangeAfter:
4062      case RangeOverlap:
4063        break;
4064      }
4065      break;
4066    }
4067
4068    // Look at all of the tokens within this range.
4069    while (MoreTokens()) {
4070      const unsigned I = NextToken();
4071      SourceLocation TokLoc = GetTokenLoc(I);
4072      switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4073      case RangeBefore:
4074        assert(0 && "Infeasible");
4075      case RangeAfter:
4076        break;
4077      case RangeOverlap:
4078        Cursors[I] = cursor;
4079        AdvanceToken();
4080        continue;
4081      }
4082      break;
4083    }
4084
4085    // Save the preprocessing token index; restore the non-preprocessing
4086    // token index.
4087    PreprocessingTokIdx = TokIdx;
4088    TokIdx = SavedTokIdx;
4089    return CXChildVisit_Recurse;
4090  }
4091
4092  if (cursorRange.isInvalid())
4093    return CXChildVisit_Continue;
4094
4095  SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data);
4096
4097  // Adjust the annotated range based specific declarations.
4098  const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
4099  if (cursorK >= CXCursor_FirstDecl && cursorK <= CXCursor_LastDecl) {
4100    Decl *D = cxcursor::getCursorDecl(cursor);
4101    // Don't visit synthesized ObjC methods, since they have no syntatic
4102    // representation in the source.
4103    if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
4104      if (MD->isSynthesized())
4105        return CXChildVisit_Continue;
4106    }
4107    if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
4108      if (TypeSourceInfo *TI = DD->getTypeSourceInfo()) {
4109        TypeLoc TL = TI->getTypeLoc();
4110        SourceLocation TLoc = TL.getSourceRange().getBegin();
4111        if (TLoc.isValid() && L.isValid() &&
4112            SrcMgr.isBeforeInTranslationUnit(TLoc, L))
4113          cursorRange.setBegin(TLoc);
4114      }
4115    }
4116  }
4117
4118  // If the location of the cursor occurs within a macro instantiation, record
4119  // the spelling location of the cursor in our annotation map.  We can then
4120  // paper over the token labelings during a post-processing step to try and
4121  // get cursor mappings for tokens that are the *arguments* of a macro
4122  // instantiation.
4123  if (L.isMacroID()) {
4124    unsigned rawEncoding = SrcMgr.getSpellingLoc(L).getRawEncoding();
4125    // Only invalidate the old annotation if it isn't part of a preprocessing
4126    // directive.  Here we assume that the default construction of CXCursor
4127    // results in CXCursor.kind being an initialized value (i.e., 0).  If
4128    // this isn't the case, we can fix by doing lookup + insertion.
4129
4130    CXCursor &oldC = Annotated[rawEncoding];
4131    if (!clang_isPreprocessing(oldC.kind))
4132      oldC = cursor;
4133  }
4134
4135  const enum CXCursorKind K = clang_getCursorKind(parent);
4136  const CXCursor updateC =
4137    (clang_isInvalid(K) || K == CXCursor_TranslationUnit)
4138     ? clang_getNullCursor() : parent;
4139
4140  while (MoreTokens()) {
4141    const unsigned I = NextToken();
4142    SourceLocation TokLoc = GetTokenLoc(I);
4143    switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4144      case RangeBefore:
4145        Cursors[I] = updateC;
4146        AdvanceToken();
4147        continue;
4148      case RangeAfter:
4149      case RangeOverlap:
4150        break;
4151    }
4152    break;
4153  }
4154
4155  // Visit children to get their cursor information.
4156  const unsigned BeforeChildren = NextToken();
4157  VisitChildren(cursor);
4158  const unsigned AfterChildren = NextToken();
4159
4160  // Adjust 'Last' to the last token within the extent of the cursor.
4161  while (MoreTokens()) {
4162    const unsigned I = NextToken();
4163    SourceLocation TokLoc = GetTokenLoc(I);
4164    switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4165      case RangeBefore:
4166        assert(0 && "Infeasible");
4167      case RangeAfter:
4168        break;
4169      case RangeOverlap:
4170        Cursors[I] = updateC;
4171        AdvanceToken();
4172        continue;
4173    }
4174    break;
4175  }
4176  const unsigned Last = NextToken();
4177
4178  // Scan the tokens that are at the beginning of the cursor, but are not
4179  // capture by the child cursors.
4180
4181  // For AST elements within macros, rely on a post-annotate pass to
4182  // to correctly annotate the tokens with cursors.  Otherwise we can
4183  // get confusing results of having tokens that map to cursors that really
4184  // are expanded by an instantiation.
4185  if (L.isMacroID())
4186    cursor = clang_getNullCursor();
4187
4188  for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
4189    if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
4190      break;
4191
4192    Cursors[I] = cursor;
4193  }
4194  // Scan the tokens that are at the end of the cursor, but are not captured
4195  // but the child cursors.
4196  for (unsigned I = AfterChildren; I != Last; ++I)
4197    Cursors[I] = cursor;
4198
4199  TokIdx = Last;
4200  return CXChildVisit_Continue;
4201}
4202
4203static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
4204                                                     CXCursor parent,
4205                                                     CXClientData client_data) {
4206  return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
4207}
4208
4209// This gets run a separate thread to avoid stack blowout.
4210static void runAnnotateTokensWorker(void *UserData) {
4211  ((AnnotateTokensWorker*)UserData)->AnnotateTokens();
4212}
4213
4214extern "C" {
4215
4216void clang_annotateTokens(CXTranslationUnit TU,
4217                          CXToken *Tokens, unsigned NumTokens,
4218                          CXCursor *Cursors) {
4219
4220  if (NumTokens == 0 || !Tokens || !Cursors)
4221    return;
4222
4223  // Any token we don't specifically annotate will have a NULL cursor.
4224  CXCursor C = clang_getNullCursor();
4225  for (unsigned I = 0; I != NumTokens; ++I)
4226    Cursors[I] = C;
4227
4228  ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
4229  if (!CXXUnit)
4230    return;
4231
4232  ASTUnit::ConcurrencyCheck Check(*CXXUnit);
4233
4234  // Determine the region of interest, which contains all of the tokens.
4235  SourceRange RegionOfInterest;
4236  RegionOfInterest.setBegin(cxloc::translateSourceLocation(
4237                                        clang_getTokenLocation(TU, Tokens[0])));
4238  RegionOfInterest.setEnd(cxloc::translateSourceLocation(
4239                                clang_getTokenLocation(TU,
4240                                                       Tokens[NumTokens - 1])));
4241
4242  // A mapping from the source locations found when re-lexing or traversing the
4243  // region of interest to the corresponding cursors.
4244  AnnotateTokensData Annotated;
4245
4246  // Relex the tokens within the source range to look for preprocessing
4247  // directives.
4248  SourceManager &SourceMgr = CXXUnit->getSourceManager();
4249  std::pair<FileID, unsigned> BeginLocInfo
4250    = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
4251  std::pair<FileID, unsigned> EndLocInfo
4252    = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
4253
4254  llvm::StringRef Buffer;
4255  bool Invalid = false;
4256  if (BeginLocInfo.first == EndLocInfo.first &&
4257      ((Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid)),true) &&
4258      !Invalid) {
4259    Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
4260              CXXUnit->getASTContext().getLangOptions(),
4261              Buffer.begin(), Buffer.data() + BeginLocInfo.second,
4262              Buffer.end());
4263    Lex.SetCommentRetentionState(true);
4264
4265    // Lex tokens in raw mode until we hit the end of the range, to avoid
4266    // entering #includes or expanding macros.
4267    while (true) {
4268      Token Tok;
4269      Lex.LexFromRawLexer(Tok);
4270
4271    reprocess:
4272      if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
4273        // We have found a preprocessing directive. Gobble it up so that we
4274        // don't see it while preprocessing these tokens later, but keep track
4275        // of all of the token locations inside this preprocessing directive so
4276        // that we can annotate them appropriately.
4277        //
4278        // FIXME: Some simple tests here could identify macro definitions and
4279        // #undefs, to provide specific cursor kinds for those.
4280        std::vector<SourceLocation> Locations;
4281        do {
4282          Locations.push_back(Tok.getLocation());
4283          Lex.LexFromRawLexer(Tok);
4284        } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
4285
4286        using namespace cxcursor;
4287        CXCursor Cursor
4288          = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
4289                                                         Locations.back()),
4290                                           CXXUnit);
4291        for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
4292          Annotated[Locations[I].getRawEncoding()] = Cursor;
4293        }
4294
4295        if (Tok.isAtStartOfLine())
4296          goto reprocess;
4297
4298        continue;
4299      }
4300
4301      if (Tok.is(tok::eof))
4302        break;
4303    }
4304  }
4305
4306  // Annotate all of the source locations in the region of interest that map to
4307  // a specific cursor.
4308  AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens,
4309                         CXXUnit, RegionOfInterest);
4310
4311  // Run the worker within a CrashRecoveryContext.
4312  llvm::CrashRecoveryContext CRC;
4313  if (!RunSafely(CRC, runAnnotateTokensWorker, &W)) {
4314    fprintf(stderr, "libclang: crash detected while annotating tokens\n");
4315  }
4316}
4317} // end: extern "C"
4318
4319//===----------------------------------------------------------------------===//
4320// Operations for querying linkage of a cursor.
4321//===----------------------------------------------------------------------===//
4322
4323extern "C" {
4324CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
4325  if (!clang_isDeclaration(cursor.kind))
4326    return CXLinkage_Invalid;
4327
4328  Decl *D = cxcursor::getCursorDecl(cursor);
4329  if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
4330    switch (ND->getLinkage()) {
4331      case NoLinkage: return CXLinkage_NoLinkage;
4332      case InternalLinkage: return CXLinkage_Internal;
4333      case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
4334      case ExternalLinkage: return CXLinkage_External;
4335    };
4336
4337  return CXLinkage_Invalid;
4338}
4339} // end: extern "C"
4340
4341//===----------------------------------------------------------------------===//
4342// Operations for querying language of a cursor.
4343//===----------------------------------------------------------------------===//
4344
4345static CXLanguageKind getDeclLanguage(const Decl *D) {
4346  switch (D->getKind()) {
4347    default:
4348      break;
4349    case Decl::ImplicitParam:
4350    case Decl::ObjCAtDefsField:
4351    case Decl::ObjCCategory:
4352    case Decl::ObjCCategoryImpl:
4353    case Decl::ObjCClass:
4354    case Decl::ObjCCompatibleAlias:
4355    case Decl::ObjCForwardProtocol:
4356    case Decl::ObjCImplementation:
4357    case Decl::ObjCInterface:
4358    case Decl::ObjCIvar:
4359    case Decl::ObjCMethod:
4360    case Decl::ObjCProperty:
4361    case Decl::ObjCPropertyImpl:
4362    case Decl::ObjCProtocol:
4363      return CXLanguage_ObjC;
4364    case Decl::CXXConstructor:
4365    case Decl::CXXConversion:
4366    case Decl::CXXDestructor:
4367    case Decl::CXXMethod:
4368    case Decl::CXXRecord:
4369    case Decl::ClassTemplate:
4370    case Decl::ClassTemplatePartialSpecialization:
4371    case Decl::ClassTemplateSpecialization:
4372    case Decl::Friend:
4373    case Decl::FriendTemplate:
4374    case Decl::FunctionTemplate:
4375    case Decl::LinkageSpec:
4376    case Decl::Namespace:
4377    case Decl::NamespaceAlias:
4378    case Decl::NonTypeTemplateParm:
4379    case Decl::StaticAssert:
4380    case Decl::TemplateTemplateParm:
4381    case Decl::TemplateTypeParm:
4382    case Decl::UnresolvedUsingTypename:
4383    case Decl::UnresolvedUsingValue:
4384    case Decl::Using:
4385    case Decl::UsingDirective:
4386    case Decl::UsingShadow:
4387      return CXLanguage_CPlusPlus;
4388  }
4389
4390  return CXLanguage_C;
4391}
4392
4393extern "C" {
4394
4395enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
4396  if (clang_isDeclaration(cursor.kind))
4397    if (Decl *D = cxcursor::getCursorDecl(cursor)) {
4398      if (D->hasAttr<UnavailableAttr>() ||
4399          (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted()))
4400        return CXAvailability_Available;
4401
4402      if (D->hasAttr<DeprecatedAttr>())
4403        return CXAvailability_Deprecated;
4404    }
4405
4406  return CXAvailability_Available;
4407}
4408
4409CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
4410  if (clang_isDeclaration(cursor.kind))
4411    return getDeclLanguage(cxcursor::getCursorDecl(cursor));
4412
4413  return CXLanguage_Invalid;
4414}
4415
4416CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
4417  if (clang_isDeclaration(cursor.kind)) {
4418    if (Decl *D = getCursorDecl(cursor)) {
4419      DeclContext *DC = D->getDeclContext();
4420      return MakeCXCursor(cast<Decl>(DC), getCursorASTUnit(cursor));
4421    }
4422  }
4423
4424  if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
4425    if (Decl *D = getCursorDecl(cursor))
4426      return MakeCXCursor(D, getCursorASTUnit(cursor));
4427  }
4428
4429  return clang_getNullCursor();
4430}
4431
4432CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
4433  if (clang_isDeclaration(cursor.kind)) {
4434    if (Decl *D = getCursorDecl(cursor)) {
4435      DeclContext *DC = D->getLexicalDeclContext();
4436      return MakeCXCursor(cast<Decl>(DC), getCursorASTUnit(cursor));
4437    }
4438  }
4439
4440  // FIXME: Note that we can't easily compute the lexical context of a
4441  // statement or expression, so we return nothing.
4442  return clang_getNullCursor();
4443}
4444
4445static void CollectOverriddenMethods(DeclContext *Ctx,
4446                                     ObjCMethodDecl *Method,
4447                            llvm::SmallVectorImpl<ObjCMethodDecl *> &Methods) {
4448  if (!Ctx)
4449    return;
4450
4451  // If we have a class or category implementation, jump straight to the
4452  // interface.
4453  if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(Ctx))
4454    return CollectOverriddenMethods(Impl->getClassInterface(), Method, Methods);
4455
4456  ObjCContainerDecl *Container = dyn_cast<ObjCContainerDecl>(Ctx);
4457  if (!Container)
4458    return;
4459
4460  // Check whether we have a matching method at this level.
4461  if (ObjCMethodDecl *Overridden = Container->getMethod(Method->getSelector(),
4462                                                    Method->isInstanceMethod()))
4463    if (Method != Overridden) {
4464      // We found an override at this level; there is no need to look
4465      // into other protocols or categories.
4466      Methods.push_back(Overridden);
4467      return;
4468    }
4469
4470  if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
4471    for (ObjCProtocolDecl::protocol_iterator P = Protocol->protocol_begin(),
4472                                          PEnd = Protocol->protocol_end();
4473         P != PEnd; ++P)
4474      CollectOverriddenMethods(*P, Method, Methods);
4475  }
4476
4477  if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Container)) {
4478    for (ObjCCategoryDecl::protocol_iterator P = Category->protocol_begin(),
4479                                          PEnd = Category->protocol_end();
4480         P != PEnd; ++P)
4481      CollectOverriddenMethods(*P, Method, Methods);
4482  }
4483
4484  if (ObjCInterfaceDecl *Interface = dyn_cast<ObjCInterfaceDecl>(Container)) {
4485    for (ObjCInterfaceDecl::protocol_iterator P = Interface->protocol_begin(),
4486                                           PEnd = Interface->protocol_end();
4487         P != PEnd; ++P)
4488      CollectOverriddenMethods(*P, Method, Methods);
4489
4490    for (ObjCCategoryDecl *Category = Interface->getCategoryList();
4491         Category; Category = Category->getNextClassCategory())
4492      CollectOverriddenMethods(Category, Method, Methods);
4493
4494    // We only look into the superclass if we haven't found anything yet.
4495    if (Methods.empty())
4496      if (ObjCInterfaceDecl *Super = Interface->getSuperClass())
4497        return CollectOverriddenMethods(Super, Method, Methods);
4498  }
4499}
4500
4501void clang_getOverriddenCursors(CXCursor cursor,
4502                                CXCursor **overridden,
4503                                unsigned *num_overridden) {
4504  if (overridden)
4505    *overridden = 0;
4506  if (num_overridden)
4507    *num_overridden = 0;
4508  if (!overridden || !num_overridden)
4509    return;
4510
4511  if (!clang_isDeclaration(cursor.kind))
4512    return;
4513
4514  Decl *D = getCursorDecl(cursor);
4515  if (!D)
4516    return;
4517
4518  // Handle C++ member functions.
4519  ASTUnit *CXXUnit = getCursorASTUnit(cursor);
4520  if (CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
4521    *num_overridden = CXXMethod->size_overridden_methods();
4522    if (!*num_overridden)
4523      return;
4524
4525    *overridden = new CXCursor [*num_overridden];
4526    unsigned I = 0;
4527    for (CXXMethodDecl::method_iterator
4528              M = CXXMethod->begin_overridden_methods(),
4529           MEnd = CXXMethod->end_overridden_methods();
4530         M != MEnd; (void)++M, ++I)
4531      (*overridden)[I] = MakeCXCursor(const_cast<CXXMethodDecl*>(*M), CXXUnit);
4532    return;
4533  }
4534
4535  ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
4536  if (!Method)
4537    return;
4538
4539  // Handle Objective-C methods.
4540  llvm::SmallVector<ObjCMethodDecl *, 4> Methods;
4541  CollectOverriddenMethods(Method->getDeclContext(), Method, Methods);
4542
4543  if (Methods.empty())
4544    return;
4545
4546  *num_overridden = Methods.size();
4547  *overridden = new CXCursor [Methods.size()];
4548  for (unsigned I = 0, N = Methods.size(); I != N; ++I)
4549    (*overridden)[I] = MakeCXCursor(Methods[I], CXXUnit);
4550}
4551
4552void clang_disposeOverriddenCursors(CXCursor *overridden) {
4553  delete [] overridden;
4554}
4555
4556CXFile clang_getIncludedFile(CXCursor cursor) {
4557  if (cursor.kind != CXCursor_InclusionDirective)
4558    return 0;
4559
4560  InclusionDirective *ID = getCursorInclusionDirective(cursor);
4561  return (void *)ID->getFile();
4562}
4563
4564} // end: extern "C"
4565
4566
4567//===----------------------------------------------------------------------===//
4568// C++ AST instrospection.
4569//===----------------------------------------------------------------------===//
4570
4571extern "C" {
4572unsigned clang_CXXMethod_isStatic(CXCursor C) {
4573  if (!clang_isDeclaration(C.kind))
4574    return 0;
4575
4576  CXXMethodDecl *Method = 0;
4577  Decl *D = cxcursor::getCursorDecl(C);
4578  if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
4579    Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
4580  else
4581    Method = dyn_cast_or_null<CXXMethodDecl>(D);
4582  return (Method && Method->isStatic()) ? 1 : 0;
4583}
4584
4585} // end: extern "C"
4586
4587//===----------------------------------------------------------------------===//
4588// Attribute introspection.
4589//===----------------------------------------------------------------------===//
4590
4591extern "C" {
4592CXType clang_getIBOutletCollectionType(CXCursor C) {
4593  if (C.kind != CXCursor_IBOutletCollectionAttr)
4594    return cxtype::MakeCXType(QualType(), cxcursor::getCursorASTUnit(C));
4595
4596  IBOutletCollectionAttr *A =
4597    cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
4598
4599  return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorASTUnit(C));
4600}
4601} // end: extern "C"
4602
4603//===----------------------------------------------------------------------===//
4604// CXString Operations.
4605//===----------------------------------------------------------------------===//
4606
4607extern "C" {
4608const char *clang_getCString(CXString string) {
4609  return string.Spelling;
4610}
4611
4612void clang_disposeString(CXString string) {
4613  if (string.MustFreeString && string.Spelling)
4614    free((void*)string.Spelling);
4615}
4616
4617} // end: extern "C"
4618
4619namespace clang { namespace cxstring {
4620CXString createCXString(const char *String, bool DupString){
4621  CXString Str;
4622  if (DupString) {
4623    Str.Spelling = strdup(String);
4624    Str.MustFreeString = 1;
4625  } else {
4626    Str.Spelling = String;
4627    Str.MustFreeString = 0;
4628  }
4629  return Str;
4630}
4631
4632CXString createCXString(llvm::StringRef String, bool DupString) {
4633  CXString Result;
4634  if (DupString || (!String.empty() && String.data()[String.size()] != 0)) {
4635    char *Spelling = (char *)malloc(String.size() + 1);
4636    memmove(Spelling, String.data(), String.size());
4637    Spelling[String.size()] = 0;
4638    Result.Spelling = Spelling;
4639    Result.MustFreeString = 1;
4640  } else {
4641    Result.Spelling = String.data();
4642    Result.MustFreeString = 0;
4643  }
4644  return Result;
4645}
4646}}
4647
4648//===----------------------------------------------------------------------===//
4649// Misc. utility functions.
4650//===----------------------------------------------------------------------===//
4651
4652/// Default to using an 8 MB stack size on "safety" threads.
4653static unsigned SafetyStackThreadSize = 8 << 20;
4654
4655namespace clang {
4656
4657bool RunSafely(llvm::CrashRecoveryContext &CRC,
4658               void (*Fn)(void*), void *UserData) {
4659  if (unsigned Size = GetSafetyThreadStackSize())
4660    return CRC.RunSafelyOnThread(Fn, UserData, Size);
4661  return CRC.RunSafely(Fn, UserData);
4662}
4663
4664unsigned GetSafetyThreadStackSize() {
4665  return SafetyStackThreadSize;
4666}
4667
4668void SetSafetyThreadStackSize(unsigned Value) {
4669  SafetyStackThreadSize = Value;
4670}
4671
4672}
4673
4674extern "C" {
4675
4676CXString clang_getClangVersion() {
4677  return createCXString(getClangFullVersion());
4678}
4679
4680} // end: extern "C"
4681