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