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