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