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