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