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