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