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