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