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