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