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