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