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