CIndex.cpp revision e0a22d06888c13989b3f72db319f1d498bf69153
1663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng//===- CIndex.cpp - Clang-C Source Indexing Library -----------------------===//
2663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng//
3663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng//                     The LLVM Compiler Infrastructure
4663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng//
5663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng// This file is distributed under the University of Illinois Open Source
6663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng// License. See LICENSE.TXT for details.
7663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng//
8663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng//===----------------------------------------------------------------------===//
9663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng//
10663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng// This file implements the main API hooks in the Clang-C Source Indexing
11663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng// library.
12663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng//
13663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng//===----------------------------------------------------------------------===//
14663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng
15663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng#include "CIndexer.h"
16663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng#include "CXCursor.h"
17663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng#include "CXTranslationUnit.h"
18663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng#include "CXString.h"
19663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng#include "CXType.h"
20663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng#include "CXSourceLocation.h"
21663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng#include "CIndexDiagnostic.h"
22663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng
23663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng#include "clang/Basic/Version.h"
24663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng
25663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng#include "clang/AST/DeclVisitor.h"
26663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng#include "clang/AST/StmtVisitor.h"
27663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng#include "clang/AST/TypeLocVisitor.h"
28663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng#include "clang/Basic/Diagnostic.h"
29663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng#include "clang/Frontend/ASTUnit.h"
30663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng#include "clang/Frontend/CompilerInstance.h"
31663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng#include "clang/Frontend/FrontendDiagnostic.h"
32663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng#include "clang/Lex/Lexer.h"
33663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng#include "clang/Lex/HeaderSearch.h"
34663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng#include "clang/Lex/PreprocessingRecord.h"
35663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng#include "clang/Lex/Preprocessor.h"
36663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng#include "llvm/ADT/STLExtras.h"
37663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng#include "llvm/ADT/Optional.h"
38663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng#include "llvm/ADT/StringSwitch.h"
39663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng#include "clang/Analysis/Support/SaveAndRestore.h"
40663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng#include "llvm/Support/CrashRecoveryContext.h"
41663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng#include "llvm/Support/PrettyStackTrace.h"
42663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng#include "llvm/Support/MemoryBuffer.h"
43663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng#include "llvm/Support/raw_ostream.h"
44663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng#include "llvm/Support/Timer.h"
45663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng#include "llvm/Support/Mutex.h"
46663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng#include "llvm/Support/Program.h"
47663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng#include "llvm/Support/Signals.h"
48663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng#include "llvm/Support/Threading.h"
49663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng#include "llvm/Support/Compiler.h"
50663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng
51663860b1408516d02ebfcb3a9999a134e6cfb223Ben Chengusing namespace clang;
52663860b1408516d02ebfcb3a9999a134e6cfb223Ben Chengusing namespace clang::cxcursor;
53663860b1408516d02ebfcb3a9999a134e6cfb223Ben Chengusing namespace clang::cxstring;
54663860b1408516d02ebfcb3a9999a134e6cfb223Ben Chengusing namespace clang::cxtu;
55663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng
56663860b1408516d02ebfcb3a9999a134e6cfb223Ben ChengCXTranslationUnit cxtu::MakeCXTranslationUnit(ASTUnit *TU) {
57663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng  if (!TU)
58663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng    return 0;
59663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng  CXTranslationUnit D = new CXTranslationUnitImpl();
60663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng  D->TUData = TU;
61663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng  D->StringPool = createCXStringPool();
62663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng  return D;
63663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng}
64663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng
65663860b1408516d02ebfcb3a9999a134e6cfb223Ben Chengcxtu::CXTUOwner::~CXTUOwner() {
66663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng  if (TU)
67663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng    clang_disposeTranslationUnit(TU);
68663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng}
69663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng
70663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng/// \brief The result of comparing two source ranges.
71663860b1408516d02ebfcb3a9999a134e6cfb223Ben Chengenum RangeComparisonResult {
72663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng  /// \brief Either the ranges overlap or one of the ranges is invalid.
73663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng  RangeOverlap,
74663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng
75663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng  /// \brief The first range ends before the second range starts.
76663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng  RangeBefore,
77663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng
78663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng  /// \brief The first range starts after the second range ends.
79663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng  RangeAfter
80663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng};
81663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng
82663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng/// \brief Compare two source ranges to determine their relative position in
83663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng/// the translation unit.
84663860b1408516d02ebfcb3a9999a134e6cfb223Ben Chengstatic RangeComparisonResult RangeCompare(SourceManager &SM,
85663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng                                          SourceRange R1,
86663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng                                          SourceRange R2) {
87663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng  assert(R1.isValid() && "First range is invalid?");
88663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng  assert(R2.isValid() && "Second range is invalid?");
89663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng  if (R1.getEnd() != R2.getBegin() &&
90663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng      SM.isBeforeInTranslationUnit(R1.getEnd(), R2.getBegin()))
91663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng    return RangeBefore;
92663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng  if (R2.getEnd() != R1.getBegin() &&
93663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng      SM.isBeforeInTranslationUnit(R2.getEnd(), R1.getBegin()))
94663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng    return RangeAfter;
95663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng  return RangeOverlap;
96663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng}
97663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng
98663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng/// \brief Determine if a source location falls within, before, or after a
99663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng///   a given source range.
100663860b1408516d02ebfcb3a9999a134e6cfb223Ben Chengstatic RangeComparisonResult LocationCompare(SourceManager &SM,
101663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng                                             SourceLocation L, SourceRange R) {
102663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng  assert(R.isValid() && "First range is invalid?");
103663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng  assert(L.isValid() && "Second range is invalid?");
104663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng  if (L == R.getBegin() || L == R.getEnd())
105663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng    return RangeOverlap;
106663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng  if (SM.isBeforeInTranslationUnit(L, R.getBegin()))
107663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng    return RangeBefore;
108663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng  if (SM.isBeforeInTranslationUnit(R.getEnd(), L))
109663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng    return RangeAfter;
110663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng  return RangeOverlap;
111663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng}
112663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng
113663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng/// \brief Translate a Clang source range into a CIndex source range.
114663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng///
115663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng/// Clang internally represents ranges where the end location points to the
116663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng/// start of the token at the end. However, for external clients it is more
117663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng/// useful to have a CXSourceRange be a proper half-open interval. This routine
118663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng/// does the appropriate translation.
119663860b1408516d02ebfcb3a9999a134e6cfb223Ben ChengCXSourceRange cxloc::translateSourceRange(const SourceManager &SM,
120663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng                                          const LangOptions &LangOpts,
121663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng                                          const CharSourceRange &R) {
122663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng  // We want the last character in this location, so we will adjust the
123663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng  // location accordingly.
124663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng  SourceLocation EndLoc = R.getEnd();
125663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng  if (EndLoc.isValid() && EndLoc.isMacroID())
126663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng    EndLoc = SM.getExpansionRange(EndLoc).second;
127663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng  if (R.isTokenRange() && !EndLoc.isInvalid() && EndLoc.isFileID()) {
128663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng    unsigned Length = Lexer::MeasureTokenLength(EndLoc, SM, LangOpts);
129663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng    EndLoc = EndLoc.getLocWithOffset(Length);
130663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng  }
131663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng
132663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng  CXSourceRange Result = { { (void *)&SM, (void *)&LangOpts },
133663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng                           R.getBegin().getRawEncoding(),
134                           EndLoc.getRawEncoding() };
135  return Result;
136}
137
138//===----------------------------------------------------------------------===//
139// Cursor visitor.
140//===----------------------------------------------------------------------===//
141
142namespace {
143
144class VisitorJob {
145public:
146  enum Kind { DeclVisitKind, StmtVisitKind, MemberExprPartsKind,
147              TypeLocVisitKind, OverloadExprPartsKind,
148              DeclRefExprPartsKind, LabelRefVisitKind,
149              ExplicitTemplateArgsVisitKind,
150              NestedNameSpecifierLocVisitKind,
151              DeclarationNameInfoVisitKind,
152              MemberRefVisitKind, SizeOfPackExprPartsKind };
153protected:
154  void *data[3];
155  CXCursor parent;
156  Kind K;
157  VisitorJob(CXCursor C, Kind k, void *d1, void *d2 = 0, void *d3 = 0)
158    : parent(C), K(k) {
159    data[0] = d1;
160    data[1] = d2;
161    data[2] = d3;
162  }
163public:
164  Kind getKind() const { return K; }
165  const CXCursor &getParent() const { return parent; }
166  static bool classof(VisitorJob *VJ) { return true; }
167};
168
169typedef SmallVector<VisitorJob, 10> VisitorWorkList;
170
171// Cursor visitor.
172class CursorVisitor : public DeclVisitor<CursorVisitor, bool>,
173                      public TypeLocVisitor<CursorVisitor, bool>
174{
175  /// \brief The translation unit we are traversing.
176  CXTranslationUnit TU;
177  ASTUnit *AU;
178
179  /// \brief The parent cursor whose children we are traversing.
180  CXCursor Parent;
181
182  /// \brief The declaration that serves at the parent of any statement or
183  /// expression nodes.
184  Decl *StmtParent;
185
186  /// \brief The visitor function.
187  CXCursorVisitor Visitor;
188
189  /// \brief The opaque client data, to be passed along to the visitor.
190  CXClientData ClientData;
191
192  /// \brief Whether we should visit the preprocessing record entries last,
193  /// after visiting other declarations.
194  bool VisitPreprocessorLast;
195
196  /// \brief When valid, a source range to which the cursor should restrict
197  /// its search.
198  SourceRange RegionOfInterest;
199
200  // FIXME: Eventually remove.  This part of a hack to support proper
201  // iteration over all Decls contained lexically within an ObjC container.
202  DeclContext::decl_iterator *DI_current;
203  DeclContext::decl_iterator DE_current;
204
205  // Cache of pre-allocated worklists for data-recursion walk of Stmts.
206  SmallVector<VisitorWorkList*, 5> WorkListFreeList;
207  SmallVector<VisitorWorkList*, 5> WorkListCache;
208
209  using DeclVisitor<CursorVisitor, bool>::Visit;
210  using TypeLocVisitor<CursorVisitor, bool>::Visit;
211
212  /// \brief Determine whether this particular source range comes before, comes
213  /// after, or overlaps the region of interest.
214  ///
215  /// \param R a half-open source range retrieved from the abstract syntax tree.
216  RangeComparisonResult CompareRegionOfInterest(SourceRange R);
217
218  class SetParentRAII {
219    CXCursor &Parent;
220    Decl *&StmtParent;
221    CXCursor OldParent;
222
223  public:
224    SetParentRAII(CXCursor &Parent, Decl *&StmtParent, CXCursor NewParent)
225      : Parent(Parent), StmtParent(StmtParent), OldParent(Parent)
226    {
227      Parent = NewParent;
228      if (clang_isDeclaration(Parent.kind))
229        StmtParent = getCursorDecl(Parent);
230    }
231
232    ~SetParentRAII() {
233      Parent = OldParent;
234      if (clang_isDeclaration(Parent.kind))
235        StmtParent = getCursorDecl(Parent);
236    }
237  };
238
239public:
240  CursorVisitor(CXTranslationUnit TU, CXCursorVisitor Visitor,
241                CXClientData ClientData,
242                bool VisitPreprocessorLast,
243                SourceRange RegionOfInterest = SourceRange())
244    : TU(TU), AU(static_cast<ASTUnit*>(TU->TUData)),
245      Visitor(Visitor), ClientData(ClientData),
246      VisitPreprocessorLast(VisitPreprocessorLast),
247      RegionOfInterest(RegionOfInterest), DI_current(0)
248  {
249    Parent.kind = CXCursor_NoDeclFound;
250    Parent.data[0] = 0;
251    Parent.data[1] = 0;
252    Parent.data[2] = 0;
253    StmtParent = 0;
254  }
255
256  ~CursorVisitor() {
257    // Free the pre-allocated worklists for data-recursion.
258    for (SmallVectorImpl<VisitorWorkList*>::iterator
259          I = WorkListCache.begin(), E = WorkListCache.end(); I != E; ++I) {
260      delete *I;
261    }
262  }
263
264  ASTUnit *getASTUnit() const { return static_cast<ASTUnit*>(TU->TUData); }
265  CXTranslationUnit getTU() const { return TU; }
266
267  bool Visit(CXCursor Cursor, bool CheckedRegionOfInterest = false);
268
269  bool visitPreprocessedEntitiesInRegion();
270
271  template<typename InputIterator>
272  bool visitPreprocessedEntities(InputIterator First, InputIterator Last);
273
274  bool VisitChildren(CXCursor Parent);
275
276  // Declaration visitors
277  bool VisitTypeAliasDecl(TypeAliasDecl *D);
278  bool VisitAttributes(Decl *D);
279  bool VisitBlockDecl(BlockDecl *B);
280  bool VisitCXXRecordDecl(CXXRecordDecl *D);
281  llvm::Optional<bool> shouldVisitCursor(CXCursor C);
282  bool VisitDeclContext(DeclContext *DC);
283  bool VisitTranslationUnitDecl(TranslationUnitDecl *D);
284  bool VisitTypedefDecl(TypedefDecl *D);
285  bool VisitTagDecl(TagDecl *D);
286  bool VisitClassTemplateSpecializationDecl(ClassTemplateSpecializationDecl *D);
287  bool VisitClassTemplatePartialSpecializationDecl(
288                                     ClassTemplatePartialSpecializationDecl *D);
289  bool VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
290  bool VisitEnumConstantDecl(EnumConstantDecl *D);
291  bool VisitDeclaratorDecl(DeclaratorDecl *DD);
292  bool VisitFunctionDecl(FunctionDecl *ND);
293  bool VisitFieldDecl(FieldDecl *D);
294  bool VisitVarDecl(VarDecl *);
295  bool VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D);
296  bool VisitFunctionTemplateDecl(FunctionTemplateDecl *D);
297  bool VisitClassTemplateDecl(ClassTemplateDecl *D);
298  bool VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D);
299  bool VisitObjCMethodDecl(ObjCMethodDecl *ND);
300  bool VisitObjCContainerDecl(ObjCContainerDecl *D);
301  bool VisitObjCCategoryDecl(ObjCCategoryDecl *ND);
302  bool VisitObjCProtocolDecl(ObjCProtocolDecl *PID);
303  bool VisitObjCPropertyDecl(ObjCPropertyDecl *PD);
304  bool VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
305  bool VisitObjCImplDecl(ObjCImplDecl *D);
306  bool VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
307  bool VisitObjCImplementationDecl(ObjCImplementationDecl *D);
308  // FIXME: ObjCCompatibleAliasDecl requires aliased-class locations.
309  bool VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D);
310  bool VisitObjCClassDecl(ObjCClassDecl *D);
311  bool VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *PD);
312  bool VisitLinkageSpecDecl(LinkageSpecDecl *D);
313  bool VisitNamespaceDecl(NamespaceDecl *D);
314  bool VisitNamespaceAliasDecl(NamespaceAliasDecl *D);
315  bool VisitUsingDirectiveDecl(UsingDirectiveDecl *D);
316  bool VisitUsingDecl(UsingDecl *D);
317  bool VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D);
318  bool VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D);
319
320  // Name visitor
321  bool VisitDeclarationNameInfo(DeclarationNameInfo Name);
322  bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS, SourceRange Range);
323  bool VisitNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS);
324
325  // Template visitors
326  bool VisitTemplateParameters(const TemplateParameterList *Params);
327  bool VisitTemplateName(TemplateName Name, SourceLocation Loc);
328  bool VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL);
329
330  // Type visitors
331#define ABSTRACT_TYPELOC(CLASS, PARENT)
332#define TYPELOC(CLASS, PARENT) \
333  bool Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
334#include "clang/AST/TypeLocNodes.def"
335
336  bool VisitTagTypeLoc(TagTypeLoc TL);
337  bool VisitArrayTypeLoc(ArrayTypeLoc TL);
338  bool VisitFunctionTypeLoc(FunctionTypeLoc TL, bool SkipResultType = false);
339
340  // Data-recursive visitor functions.
341  bool IsInRegionOfInterest(CXCursor C);
342  bool RunVisitorWorkList(VisitorWorkList &WL);
343  void EnqueueWorkList(VisitorWorkList &WL, Stmt *S);
344  LLVM_ATTRIBUTE_NOINLINE bool Visit(Stmt *S);
345};
346
347} // end anonymous namespace
348
349static SourceRange getRawCursorExtent(CXCursor C);
350static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr);
351
352
353RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
354  return RangeCompare(AU->getSourceManager(), R, RegionOfInterest);
355}
356
357/// \brief Visit the given cursor and, if requested by the visitor,
358/// its children.
359///
360/// \param Cursor the cursor to visit.
361///
362/// \param CheckRegionOfInterest if true, then the caller already checked that
363/// this cursor is within the region of interest.
364///
365/// \returns true if the visitation should be aborted, false if it
366/// should continue.
367bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
368  if (clang_isInvalid(Cursor.kind))
369    return false;
370
371  if (clang_isDeclaration(Cursor.kind)) {
372    Decl *D = getCursorDecl(Cursor);
373    assert(D && "Invalid declaration cursor");
374    // Ignore implicit declarations, unless it's an objc method because
375    // currently we should report implicit methods for properties when indexing.
376    if (D->isImplicit() && !isa<ObjCMethodDecl>(D))
377      return false;
378  }
379
380  // If we have a range of interest, and this cursor doesn't intersect with it,
381  // we're done.
382  if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
383    SourceRange Range = getRawCursorExtent(Cursor);
384    if (Range.isInvalid() || CompareRegionOfInterest(Range))
385      return false;
386  }
387
388  switch (Visitor(Cursor, Parent, ClientData)) {
389  case CXChildVisit_Break:
390    return true;
391
392  case CXChildVisit_Continue:
393    return false;
394
395  case CXChildVisit_Recurse:
396    return VisitChildren(Cursor);
397  }
398
399  return false;
400}
401
402bool CursorVisitor::visitPreprocessedEntitiesInRegion() {
403  PreprocessingRecord &PPRec
404    = *AU->getPreprocessor().getPreprocessingRecord();
405
406  if (RegionOfInterest.isValid()) {
407    SourceRange MappedRange = AU->mapRangeToPreamble(RegionOfInterest);
408    std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
409      Entities = PPRec.getPreprocessedEntitiesInRange(MappedRange);
410    return visitPreprocessedEntities(Entities.first, Entities.second);
411  }
412
413  bool OnlyLocalDecls
414    = !AU->isMainFileAST() && AU->getOnlyLocalDecls();
415
416  if (OnlyLocalDecls)
417    return visitPreprocessedEntities(PPRec.local_begin(), PPRec.local_end());
418
419  return visitPreprocessedEntities(PPRec.begin(), PPRec.end());
420}
421
422template<typename InputIterator>
423bool CursorVisitor::visitPreprocessedEntities(InputIterator First,
424                                              InputIterator Last) {
425  for (; First != Last; ++First) {
426    if (MacroExpansion *ME = dyn_cast<MacroExpansion>(*First)) {
427      if (Visit(MakeMacroExpansionCursor(ME, TU)))
428        return true;
429
430      continue;
431    }
432
433    if (MacroDefinition *MD = dyn_cast<MacroDefinition>(*First)) {
434      if (Visit(MakeMacroDefinitionCursor(MD, TU)))
435        return true;
436
437      continue;
438    }
439
440    if (InclusionDirective *ID = dyn_cast<InclusionDirective>(*First)) {
441      if (Visit(MakeInclusionDirectiveCursor(ID, TU)))
442        return true;
443
444      continue;
445    }
446  }
447
448  return false;
449}
450
451/// \brief Visit the children of the given cursor.
452///
453/// \returns true if the visitation should be aborted, false if it
454/// should continue.
455bool CursorVisitor::VisitChildren(CXCursor Cursor) {
456  if (clang_isReference(Cursor.kind) &&
457      Cursor.kind != CXCursor_CXXBaseSpecifier) {
458    // By definition, references have no children.
459    return false;
460  }
461
462  // Set the Parent field to Cursor, then back to its old value once we're
463  // done.
464  SetParentRAII SetParent(Parent, StmtParent, Cursor);
465
466  if (clang_isDeclaration(Cursor.kind)) {
467    Decl *D = getCursorDecl(Cursor);
468    if (!D)
469      return false;
470
471    return VisitAttributes(D) || Visit(D);
472  }
473
474  if (clang_isStatement(Cursor.kind)) {
475    if (Stmt *S = getCursorStmt(Cursor))
476      return Visit(S);
477
478    return false;
479  }
480
481  if (clang_isExpression(Cursor.kind)) {
482    if (Expr *E = getCursorExpr(Cursor))
483      return Visit(E);
484
485    return false;
486  }
487
488  if (clang_isTranslationUnit(Cursor.kind)) {
489    CXTranslationUnit tu = getCursorTU(Cursor);
490    ASTUnit *CXXUnit = static_cast<ASTUnit*>(tu->TUData);
491
492    int VisitOrder[2] = { VisitPreprocessorLast, !VisitPreprocessorLast };
493    for (unsigned I = 0; I != 2; ++I) {
494      if (VisitOrder[I]) {
495        if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
496            RegionOfInterest.isInvalid()) {
497          for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(),
498                                        TLEnd = CXXUnit->top_level_end();
499               TL != TLEnd; ++TL) {
500            if (Visit(MakeCXCursor(*TL, tu, RegionOfInterest), true))
501              return true;
502          }
503        } else if (VisitDeclContext(
504                                CXXUnit->getASTContext().getTranslationUnitDecl()))
505          return true;
506        continue;
507      }
508
509      // Walk the preprocessing record.
510      if (CXXUnit->getPreprocessor().getPreprocessingRecord())
511        visitPreprocessedEntitiesInRegion();
512    }
513
514    return false;
515  }
516
517  if (Cursor.kind == CXCursor_CXXBaseSpecifier) {
518    if (CXXBaseSpecifier *Base = getCursorCXXBaseSpecifier(Cursor)) {
519      if (TypeSourceInfo *BaseTSInfo = Base->getTypeSourceInfo()) {
520        return Visit(BaseTSInfo->getTypeLoc());
521      }
522    }
523  }
524
525  if (Cursor.kind == CXCursor_IBOutletCollectionAttr) {
526    IBOutletCollectionAttr *A =
527      cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(Cursor));
528    if (const ObjCInterfaceType *InterT = A->getInterface()->getAs<ObjCInterfaceType>())
529      return Visit(cxcursor::MakeCursorObjCClassRef(InterT->getInterface(),
530                                                    A->getInterfaceLoc(), TU));
531  }
532
533  // Nothing to visit at the moment.
534  return false;
535}
536
537bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
538  if (TypeSourceInfo *TSInfo = B->getSignatureAsWritten())
539    if (Visit(TSInfo->getTypeLoc()))
540        return true;
541
542  if (Stmt *Body = B->getBody())
543    return Visit(MakeCXCursor(Body, StmtParent, TU, RegionOfInterest));
544
545  return false;
546}
547
548llvm::Optional<bool> CursorVisitor::shouldVisitCursor(CXCursor Cursor) {
549  if (RegionOfInterest.isValid()) {
550    SourceRange Range = getFullCursorExtent(Cursor, AU->getSourceManager());
551    if (Range.isInvalid())
552      return llvm::Optional<bool>();
553
554    switch (CompareRegionOfInterest(Range)) {
555    case RangeBefore:
556      // This declaration comes before the region of interest; skip it.
557      return llvm::Optional<bool>();
558
559    case RangeAfter:
560      // This declaration comes after the region of interest; we're done.
561      return false;
562
563    case RangeOverlap:
564      // This declaration overlaps the region of interest; visit it.
565      break;
566    }
567  }
568  return true;
569}
570
571bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
572  DeclContext::decl_iterator I = DC->decls_begin(), E = DC->decls_end();
573
574  // FIXME: Eventually remove.  This part of a hack to support proper
575  // iteration over all Decls contained lexically within an ObjC container.
576  SaveAndRestore<DeclContext::decl_iterator*> DI_saved(DI_current, &I);
577  SaveAndRestore<DeclContext::decl_iterator> DE_saved(DE_current, E);
578
579  for ( ; I != E; ++I) {
580    Decl *D = *I;
581    if (D->getLexicalDeclContext() != DC)
582      continue;
583    CXCursor Cursor = MakeCXCursor(D, TU, RegionOfInterest);
584    const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
585    if (!V.hasValue())
586      continue;
587    if (!V.getValue())
588      return false;
589    if (Visit(Cursor, true))
590      return true;
591  }
592  return false;
593}
594
595bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
596  llvm_unreachable("Translation units are visited directly by Visit()");
597  return false;
598}
599
600bool CursorVisitor::VisitTypeAliasDecl(TypeAliasDecl *D) {
601  if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
602    return Visit(TSInfo->getTypeLoc());
603
604  return false;
605}
606
607bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
608  if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
609    return Visit(TSInfo->getTypeLoc());
610
611  return false;
612}
613
614bool CursorVisitor::VisitTagDecl(TagDecl *D) {
615  return VisitDeclContext(D);
616}
617
618bool CursorVisitor::VisitClassTemplateSpecializationDecl(
619                                          ClassTemplateSpecializationDecl *D) {
620  bool ShouldVisitBody = false;
621  switch (D->getSpecializationKind()) {
622  case TSK_Undeclared:
623  case TSK_ImplicitInstantiation:
624    // Nothing to visit
625    return false;
626
627  case TSK_ExplicitInstantiationDeclaration:
628  case TSK_ExplicitInstantiationDefinition:
629    break;
630
631  case TSK_ExplicitSpecialization:
632    ShouldVisitBody = true;
633    break;
634  }
635
636  // Visit the template arguments used in the specialization.
637  if (TypeSourceInfo *SpecType = D->getTypeAsWritten()) {
638    TypeLoc TL = SpecType->getTypeLoc();
639    if (TemplateSpecializationTypeLoc *TSTLoc
640          = dyn_cast<TemplateSpecializationTypeLoc>(&TL)) {
641      for (unsigned I = 0, N = TSTLoc->getNumArgs(); I != N; ++I)
642        if (VisitTemplateArgumentLoc(TSTLoc->getArgLoc(I)))
643          return true;
644    }
645  }
646
647  if (ShouldVisitBody && VisitCXXRecordDecl(D))
648    return true;
649
650  return false;
651}
652
653bool CursorVisitor::VisitClassTemplatePartialSpecializationDecl(
654                                   ClassTemplatePartialSpecializationDecl *D) {
655  // FIXME: Visit the "outer" template parameter lists on the TagDecl
656  // before visiting these template parameters.
657  if (VisitTemplateParameters(D->getTemplateParameters()))
658    return true;
659
660  // Visit the partial specialization arguments.
661  const TemplateArgumentLoc *TemplateArgs = D->getTemplateArgsAsWritten();
662  for (unsigned I = 0, N = D->getNumTemplateArgsAsWritten(); I != N; ++I)
663    if (VisitTemplateArgumentLoc(TemplateArgs[I]))
664      return true;
665
666  return VisitCXXRecordDecl(D);
667}
668
669bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
670  // Visit the default argument.
671  if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
672    if (TypeSourceInfo *DefArg = D->getDefaultArgumentInfo())
673      if (Visit(DefArg->getTypeLoc()))
674        return true;
675
676  return false;
677}
678
679bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
680  if (Expr *Init = D->getInitExpr())
681    return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
682  return false;
683}
684
685bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
686  if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
687    if (Visit(TSInfo->getTypeLoc()))
688      return true;
689
690  // Visit the nested-name-specifier, if present.
691  if (NestedNameSpecifierLoc QualifierLoc = DD->getQualifierLoc())
692    if (VisitNestedNameSpecifierLoc(QualifierLoc))
693      return true;
694
695  return false;
696}
697
698/// \brief Compare two base or member initializers based on their source order.
699static int CompareCXXCtorInitializers(const void* Xp, const void *Yp) {
700  CXXCtorInitializer const * const *X
701    = static_cast<CXXCtorInitializer const * const *>(Xp);
702  CXXCtorInitializer const * const *Y
703    = static_cast<CXXCtorInitializer const * const *>(Yp);
704
705  if ((*X)->getSourceOrder() < (*Y)->getSourceOrder())
706    return -1;
707  else if ((*X)->getSourceOrder() > (*Y)->getSourceOrder())
708    return 1;
709  else
710    return 0;
711}
712
713bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
714  if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) {
715    // Visit the function declaration's syntactic components in the order
716    // written. This requires a bit of work.
717    TypeLoc TL = TSInfo->getTypeLoc().IgnoreParens();
718    FunctionTypeLoc *FTL = dyn_cast<FunctionTypeLoc>(&TL);
719
720    // If we have a function declared directly (without the use of a typedef),
721    // visit just the return type. Otherwise, just visit the function's type
722    // now.
723    if ((FTL && !isa<CXXConversionDecl>(ND) && Visit(FTL->getResultLoc())) ||
724        (!FTL && Visit(TL)))
725      return true;
726
727    // Visit the nested-name-specifier, if present.
728    if (NestedNameSpecifierLoc QualifierLoc = ND->getQualifierLoc())
729      if (VisitNestedNameSpecifierLoc(QualifierLoc))
730        return true;
731
732    // Visit the declaration name.
733    if (VisitDeclarationNameInfo(ND->getNameInfo()))
734      return true;
735
736    // FIXME: Visit explicitly-specified template arguments!
737
738    // Visit the function parameters, if we have a function type.
739    if (FTL && VisitFunctionTypeLoc(*FTL, true))
740      return true;
741
742    // FIXME: Attributes?
743  }
744
745  if (ND->doesThisDeclarationHaveABody() && !ND->isLateTemplateParsed()) {
746    if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ND)) {
747      // Find the initializers that were written in the source.
748      SmallVector<CXXCtorInitializer *, 4> WrittenInits;
749      for (CXXConstructorDecl::init_iterator I = Constructor->init_begin(),
750                                          IEnd = Constructor->init_end();
751           I != IEnd; ++I) {
752        if (!(*I)->isWritten())
753          continue;
754
755        WrittenInits.push_back(*I);
756      }
757
758      // Sort the initializers in source order
759      llvm::array_pod_sort(WrittenInits.begin(), WrittenInits.end(),
760                           &CompareCXXCtorInitializers);
761
762      // Visit the initializers in source order
763      for (unsigned I = 0, N = WrittenInits.size(); I != N; ++I) {
764        CXXCtorInitializer *Init = WrittenInits[I];
765        if (Init->isAnyMemberInitializer()) {
766          if (Visit(MakeCursorMemberRef(Init->getAnyMember(),
767                                        Init->getMemberLocation(), TU)))
768            return true;
769        } else if (TypeSourceInfo *BaseInfo = Init->getBaseClassInfo()) {
770          if (Visit(BaseInfo->getTypeLoc()))
771            return true;
772        }
773
774        // Visit the initializer value.
775        if (Expr *Initializer = Init->getInit())
776          if (Visit(MakeCXCursor(Initializer, ND, TU, RegionOfInterest)))
777            return true;
778      }
779    }
780
781    if (Visit(MakeCXCursor(ND->getBody(), StmtParent, TU, RegionOfInterest)))
782      return true;
783  }
784
785  return false;
786}
787
788bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
789  if (VisitDeclaratorDecl(D))
790    return true;
791
792  if (Expr *BitWidth = D->getBitWidth())
793    return Visit(MakeCXCursor(BitWidth, StmtParent, TU, RegionOfInterest));
794
795  return false;
796}
797
798bool CursorVisitor::VisitVarDecl(VarDecl *D) {
799  if (VisitDeclaratorDecl(D))
800    return true;
801
802  if (Expr *Init = D->getInit())
803    return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
804
805  return false;
806}
807
808bool CursorVisitor::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
809  if (VisitDeclaratorDecl(D))
810    return true;
811
812  if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
813    if (Expr *DefArg = D->getDefaultArgument())
814      return Visit(MakeCXCursor(DefArg, StmtParent, TU, RegionOfInterest));
815
816  return false;
817}
818
819bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
820  // FIXME: Visit the "outer" template parameter lists on the FunctionDecl
821  // before visiting these template parameters.
822  if (VisitTemplateParameters(D->getTemplateParameters()))
823    return true;
824
825  return VisitFunctionDecl(D->getTemplatedDecl());
826}
827
828bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) {
829  // FIXME: Visit the "outer" template parameter lists on the TagDecl
830  // before visiting these template parameters.
831  if (VisitTemplateParameters(D->getTemplateParameters()))
832    return true;
833
834  return VisitCXXRecordDecl(D->getTemplatedDecl());
835}
836
837bool CursorVisitor::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
838  if (VisitTemplateParameters(D->getTemplateParameters()))
839    return true;
840
841  if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited() &&
842      VisitTemplateArgumentLoc(D->getDefaultArgument()))
843    return true;
844
845  return false;
846}
847
848bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
849  if (TypeSourceInfo *TSInfo = ND->getResultTypeSourceInfo())
850    if (Visit(TSInfo->getTypeLoc()))
851      return true;
852
853  for (ObjCMethodDecl::param_iterator P = ND->param_begin(),
854       PEnd = ND->param_end();
855       P != PEnd; ++P) {
856    if (Visit(MakeCXCursor(*P, TU, RegionOfInterest)))
857      return true;
858  }
859
860  if (ND->isThisDeclarationADefinition() &&
861      Visit(MakeCXCursor(ND->getBody(), StmtParent, TU, RegionOfInterest)))
862    return true;
863
864  return false;
865}
866
867namespace {
868  struct ContainerDeclsSort {
869    SourceManager &SM;
870    ContainerDeclsSort(SourceManager &sm) : SM(sm) {}
871    bool operator()(Decl *A, Decl *B) {
872      SourceLocation L_A = A->getLocStart();
873      SourceLocation L_B = B->getLocStart();
874      assert(L_A.isValid() && L_B.isValid());
875      return SM.isBeforeInTranslationUnit(L_A, L_B);
876    }
877  };
878}
879
880bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
881  // FIXME: Eventually convert back to just 'VisitDeclContext()'.  Essentially
882  // an @implementation can lexically contain Decls that are not properly
883  // nested in the AST.  When we identify such cases, we need to retrofit
884  // this nesting here.
885  if (!DI_current)
886    return VisitDeclContext(D);
887
888  // Scan the Decls that immediately come after the container
889  // in the current DeclContext.  If any fall within the
890  // container's lexical region, stash them into a vector
891  // for later processing.
892  SmallVector<Decl *, 24> DeclsInContainer;
893  SourceLocation EndLoc = D->getSourceRange().getEnd();
894  SourceManager &SM = AU->getSourceManager();
895  if (EndLoc.isValid()) {
896    DeclContext::decl_iterator next = *DI_current;
897    while (++next != DE_current) {
898      Decl *D_next = *next;
899      if (!D_next)
900        break;
901      SourceLocation L = D_next->getLocStart();
902      if (!L.isValid())
903        break;
904      if (SM.isBeforeInTranslationUnit(L, EndLoc)) {
905        *DI_current = next;
906        DeclsInContainer.push_back(D_next);
907        continue;
908      }
909      break;
910    }
911  }
912
913  // The common case.
914  if (DeclsInContainer.empty())
915    return VisitDeclContext(D);
916
917  // Get all the Decls in the DeclContext, and sort them with the
918  // additional ones we've collected.  Then visit them.
919  for (DeclContext::decl_iterator I = D->decls_begin(), E = D->decls_end();
920       I!=E; ++I) {
921    Decl *subDecl = *I;
922    if (!subDecl || subDecl->getLexicalDeclContext() != D ||
923        subDecl->getLocStart().isInvalid())
924      continue;
925    DeclsInContainer.push_back(subDecl);
926  }
927
928  // Now sort the Decls so that they appear in lexical order.
929  std::sort(DeclsInContainer.begin(), DeclsInContainer.end(),
930            ContainerDeclsSort(SM));
931
932  // Now visit the decls.
933  for (SmallVectorImpl<Decl*>::iterator I = DeclsInContainer.begin(),
934         E = DeclsInContainer.end(); I != E; ++I) {
935    CXCursor Cursor = MakeCXCursor(*I, TU, RegionOfInterest);
936    const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
937    if (!V.hasValue())
938      continue;
939    if (!V.getValue())
940      return false;
941    if (Visit(Cursor, true))
942      return true;
943  }
944  return false;
945}
946
947bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
948  if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
949                                   TU)))
950    return true;
951
952  ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
953  for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
954         E = ND->protocol_end(); I != E; ++I, ++PL)
955    if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
956      return true;
957
958  return VisitObjCContainerDecl(ND);
959}
960
961bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
962  ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
963  for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
964       E = PID->protocol_end(); I != E; ++I, ++PL)
965    if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
966      return true;
967
968  return VisitObjCContainerDecl(PID);
969}
970
971bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
972  if (PD->getTypeSourceInfo() && Visit(PD->getTypeSourceInfo()->getTypeLoc()))
973    return true;
974
975  // FIXME: This implements a workaround with @property declarations also being
976  // installed in the DeclContext for the @interface.  Eventually this code
977  // should be removed.
978  ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
979  if (!CDecl || !CDecl->IsClassExtension())
980    return false;
981
982  ObjCInterfaceDecl *ID = CDecl->getClassInterface();
983  if (!ID)
984    return false;
985
986  IdentifierInfo *PropertyId = PD->getIdentifier();
987  ObjCPropertyDecl *prevDecl =
988    ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId);
989
990  if (!prevDecl)
991    return false;
992
993  // Visit synthesized methods since they will be skipped when visiting
994  // the @interface.
995  if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
996    if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
997      if (Visit(MakeCXCursor(MD, TU, RegionOfInterest)))
998        return true;
999
1000  if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
1001    if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
1002      if (Visit(MakeCXCursor(MD, TU, RegionOfInterest)))
1003        return true;
1004
1005  return false;
1006}
1007
1008bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
1009  // Issue callbacks for super class.
1010  if (D->getSuperClass() &&
1011      Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
1012                                        D->getSuperClassLoc(),
1013                                        TU)))
1014    return true;
1015
1016  ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1017  for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
1018         E = D->protocol_end(); I != E; ++I, ++PL)
1019    if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
1020      return true;
1021
1022  return VisitObjCContainerDecl(D);
1023}
1024
1025bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
1026  return VisitObjCContainerDecl(D);
1027}
1028
1029bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
1030  // 'ID' could be null when dealing with invalid code.
1031  if (ObjCInterfaceDecl *ID = D->getClassInterface())
1032    if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
1033      return true;
1034
1035  return VisitObjCImplDecl(D);
1036}
1037
1038bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
1039#if 0
1040  // Issue callbacks for super class.
1041  // FIXME: No source location information!
1042  if (D->getSuperClass() &&
1043      Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
1044                                        D->getSuperClassLoc(),
1045                                        TU)))
1046    return true;
1047#endif
1048
1049  return VisitObjCImplDecl(D);
1050}
1051
1052bool CursorVisitor::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D) {
1053  ObjCForwardProtocolDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1054  for (ObjCForwardProtocolDecl::protocol_iterator I = D->protocol_begin(),
1055                                                  E = D->protocol_end();
1056       I != E; ++I, ++PL)
1057    if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
1058      return true;
1059
1060  return false;
1061}
1062
1063bool CursorVisitor::VisitObjCClassDecl(ObjCClassDecl *D) {
1064  if (Visit(MakeCursorObjCClassRef(D->getForwardInterfaceDecl(),
1065                                   D->getForwardDecl()->getLocation(), TU)))
1066      return true;
1067  return false;
1068}
1069
1070bool CursorVisitor::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *PD) {
1071  if (ObjCIvarDecl *Ivar = PD->getPropertyIvarDecl())
1072    return Visit(MakeCursorMemberRef(Ivar, PD->getPropertyIvarDeclLoc(), TU));
1073
1074  return false;
1075}
1076
1077bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
1078  return VisitDeclContext(D);
1079}
1080
1081bool CursorVisitor::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
1082  // Visit nested-name-specifier.
1083  if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1084    if (VisitNestedNameSpecifierLoc(QualifierLoc))
1085      return true;
1086
1087  return Visit(MakeCursorNamespaceRef(D->getAliasedNamespace(),
1088                                      D->getTargetNameLoc(), TU));
1089}
1090
1091bool CursorVisitor::VisitUsingDecl(UsingDecl *D) {
1092  // Visit nested-name-specifier.
1093  if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1094    if (VisitNestedNameSpecifierLoc(QualifierLoc))
1095      return true;
1096  }
1097
1098  if (Visit(MakeCursorOverloadedDeclRef(D, D->getLocation(), TU)))
1099    return true;
1100
1101  return VisitDeclarationNameInfo(D->getNameInfo());
1102}
1103
1104bool CursorVisitor::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
1105  // Visit nested-name-specifier.
1106  if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1107    if (VisitNestedNameSpecifierLoc(QualifierLoc))
1108      return true;
1109
1110  return Visit(MakeCursorNamespaceRef(D->getNominatedNamespaceAsWritten(),
1111                                      D->getIdentLocation(), TU));
1112}
1113
1114bool CursorVisitor::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
1115  // Visit nested-name-specifier.
1116  if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1117    if (VisitNestedNameSpecifierLoc(QualifierLoc))
1118      return true;
1119  }
1120
1121  return VisitDeclarationNameInfo(D->getNameInfo());
1122}
1123
1124bool CursorVisitor::VisitUnresolvedUsingTypenameDecl(
1125                                               UnresolvedUsingTypenameDecl *D) {
1126  // Visit nested-name-specifier.
1127  if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1128    if (VisitNestedNameSpecifierLoc(QualifierLoc))
1129      return true;
1130
1131  return false;
1132}
1133
1134bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) {
1135  switch (Name.getName().getNameKind()) {
1136  case clang::DeclarationName::Identifier:
1137  case clang::DeclarationName::CXXLiteralOperatorName:
1138  case clang::DeclarationName::CXXOperatorName:
1139  case clang::DeclarationName::CXXUsingDirective:
1140    return false;
1141
1142  case clang::DeclarationName::CXXConstructorName:
1143  case clang::DeclarationName::CXXDestructorName:
1144  case clang::DeclarationName::CXXConversionFunctionName:
1145    if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo())
1146      return Visit(TSInfo->getTypeLoc());
1147    return false;
1148
1149  case clang::DeclarationName::ObjCZeroArgSelector:
1150  case clang::DeclarationName::ObjCOneArgSelector:
1151  case clang::DeclarationName::ObjCMultiArgSelector:
1152    // FIXME: Per-identifier location info?
1153    return false;
1154  }
1155
1156  return false;
1157}
1158
1159bool CursorVisitor::VisitNestedNameSpecifier(NestedNameSpecifier *NNS,
1160                                             SourceRange Range) {
1161  // FIXME: This whole routine is a hack to work around the lack of proper
1162  // source information in nested-name-specifiers (PR5791). Since we do have
1163  // a beginning source location, we can visit the first component of the
1164  // nested-name-specifier, if it's a single-token component.
1165  if (!NNS)
1166    return false;
1167
1168  // Get the first component in the nested-name-specifier.
1169  while (NestedNameSpecifier *Prefix = NNS->getPrefix())
1170    NNS = Prefix;
1171
1172  switch (NNS->getKind()) {
1173  case NestedNameSpecifier::Namespace:
1174    return Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(), Range.getBegin(),
1175                                        TU));
1176
1177  case NestedNameSpecifier::NamespaceAlias:
1178    return Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
1179                                        Range.getBegin(), TU));
1180
1181  case NestedNameSpecifier::TypeSpec: {
1182    // If the type has a form where we know that the beginning of the source
1183    // range matches up with a reference cursor. Visit the appropriate reference
1184    // cursor.
1185    const Type *T = NNS->getAsType();
1186    if (const TypedefType *Typedef = dyn_cast<TypedefType>(T))
1187      return Visit(MakeCursorTypeRef(Typedef->getDecl(), Range.getBegin(), TU));
1188    if (const TagType *Tag = dyn_cast<TagType>(T))
1189      return Visit(MakeCursorTypeRef(Tag->getDecl(), Range.getBegin(), TU));
1190    if (const TemplateSpecializationType *TST
1191                                      = dyn_cast<TemplateSpecializationType>(T))
1192      return VisitTemplateName(TST->getTemplateName(), Range.getBegin());
1193    break;
1194  }
1195
1196  case NestedNameSpecifier::TypeSpecWithTemplate:
1197  case NestedNameSpecifier::Global:
1198  case NestedNameSpecifier::Identifier:
1199    break;
1200  }
1201
1202  return false;
1203}
1204
1205bool
1206CursorVisitor::VisitNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
1207  SmallVector<NestedNameSpecifierLoc, 4> Qualifiers;
1208  for (; Qualifier; Qualifier = Qualifier.getPrefix())
1209    Qualifiers.push_back(Qualifier);
1210
1211  while (!Qualifiers.empty()) {
1212    NestedNameSpecifierLoc Q = Qualifiers.pop_back_val();
1213    NestedNameSpecifier *NNS = Q.getNestedNameSpecifier();
1214    switch (NNS->getKind()) {
1215    case NestedNameSpecifier::Namespace:
1216      if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(),
1217                                       Q.getLocalBeginLoc(),
1218                                       TU)))
1219        return true;
1220
1221      break;
1222
1223    case NestedNameSpecifier::NamespaceAlias:
1224      if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
1225                                       Q.getLocalBeginLoc(),
1226                                       TU)))
1227        return true;
1228
1229      break;
1230
1231    case NestedNameSpecifier::TypeSpec:
1232    case NestedNameSpecifier::TypeSpecWithTemplate:
1233      if (Visit(Q.getTypeLoc()))
1234        return true;
1235
1236      break;
1237
1238    case NestedNameSpecifier::Global:
1239    case NestedNameSpecifier::Identifier:
1240      break;
1241    }
1242  }
1243
1244  return false;
1245}
1246
1247bool CursorVisitor::VisitTemplateParameters(
1248                                          const TemplateParameterList *Params) {
1249  if (!Params)
1250    return false;
1251
1252  for (TemplateParameterList::const_iterator P = Params->begin(),
1253                                          PEnd = Params->end();
1254       P != PEnd; ++P) {
1255    if (Visit(MakeCXCursor(*P, TU, RegionOfInterest)))
1256      return true;
1257  }
1258
1259  return false;
1260}
1261
1262bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) {
1263  switch (Name.getKind()) {
1264  case TemplateName::Template:
1265    return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU));
1266
1267  case TemplateName::OverloadedTemplate:
1268    // Visit the overloaded template set.
1269    if (Visit(MakeCursorOverloadedDeclRef(Name, Loc, TU)))
1270      return true;
1271
1272    return false;
1273
1274  case TemplateName::DependentTemplate:
1275    // FIXME: Visit nested-name-specifier.
1276    return false;
1277
1278  case TemplateName::QualifiedTemplate:
1279    // FIXME: Visit nested-name-specifier.
1280    return Visit(MakeCursorTemplateRef(
1281                                  Name.getAsQualifiedTemplateName()->getDecl(),
1282                                       Loc, TU));
1283
1284  case TemplateName::SubstTemplateTemplateParm:
1285    return Visit(MakeCursorTemplateRef(
1286                         Name.getAsSubstTemplateTemplateParm()->getParameter(),
1287                                       Loc, TU));
1288
1289  case TemplateName::SubstTemplateTemplateParmPack:
1290    return Visit(MakeCursorTemplateRef(
1291                  Name.getAsSubstTemplateTemplateParmPack()->getParameterPack(),
1292                                       Loc, TU));
1293  }
1294
1295  return false;
1296}
1297
1298bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) {
1299  switch (TAL.getArgument().getKind()) {
1300  case TemplateArgument::Null:
1301  case TemplateArgument::Integral:
1302  case TemplateArgument::Pack:
1303    return false;
1304
1305  case TemplateArgument::Type:
1306    if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo())
1307      return Visit(TSInfo->getTypeLoc());
1308    return false;
1309
1310  case TemplateArgument::Declaration:
1311    if (Expr *E = TAL.getSourceDeclExpression())
1312      return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
1313    return false;
1314
1315  case TemplateArgument::Expression:
1316    if (Expr *E = TAL.getSourceExpression())
1317      return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
1318    return false;
1319
1320  case TemplateArgument::Template:
1321  case TemplateArgument::TemplateExpansion:
1322    if (VisitNestedNameSpecifierLoc(TAL.getTemplateQualifierLoc()))
1323      return true;
1324
1325    return VisitTemplateName(TAL.getArgument().getAsTemplateOrTemplatePattern(),
1326                             TAL.getTemplateNameLoc());
1327  }
1328
1329  return false;
1330}
1331
1332bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1333  return VisitDeclContext(D);
1334}
1335
1336bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1337  return Visit(TL.getUnqualifiedLoc());
1338}
1339
1340bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
1341  ASTContext &Context = AU->getASTContext();
1342
1343  // Some builtin types (such as Objective-C's "id", "sel", and
1344  // "Class") have associated declarations. Create cursors for those.
1345  QualType VisitType;
1346  switch (TL.getTypePtr()->getKind()) {
1347  case BuiltinType::Void:
1348  case BuiltinType::Bool:
1349  case BuiltinType::Char_U:
1350  case BuiltinType::UChar:
1351  case BuiltinType::Char16:
1352  case BuiltinType::Char32:
1353  case BuiltinType::UShort:
1354  case BuiltinType::UInt:
1355  case BuiltinType::ULong:
1356  case BuiltinType::ULongLong:
1357  case BuiltinType::UInt128:
1358  case BuiltinType::Char_S:
1359  case BuiltinType::SChar:
1360  case BuiltinType::WChar_U:
1361  case BuiltinType::WChar_S:
1362  case BuiltinType::Short:
1363  case BuiltinType::Int:
1364  case BuiltinType::Long:
1365  case BuiltinType::LongLong:
1366  case BuiltinType::Int128:
1367  case BuiltinType::Half:
1368  case BuiltinType::Float:
1369  case BuiltinType::Double:
1370  case BuiltinType::LongDouble:
1371  case BuiltinType::NullPtr:
1372  case BuiltinType::Overload:
1373  case BuiltinType::BoundMember:
1374  case BuiltinType::Dependent:
1375  case BuiltinType::UnknownAny:
1376  case BuiltinType::ARCUnbridgedCast:
1377    break;
1378
1379  case BuiltinType::ObjCId:
1380    VisitType = Context.getObjCIdType();
1381    break;
1382
1383  case BuiltinType::ObjCClass:
1384    VisitType = Context.getObjCClassType();
1385    break;
1386
1387  case BuiltinType::ObjCSel:
1388    VisitType = Context.getObjCSelType();
1389    break;
1390  }
1391
1392  if (!VisitType.isNull()) {
1393    if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
1394      return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
1395                                     TU));
1396  }
1397
1398  return false;
1399}
1400
1401bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
1402  return Visit(MakeCursorTypeRef(TL.getTypedefNameDecl(), TL.getNameLoc(), TU));
1403}
1404
1405bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
1406  return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1407}
1408
1409bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
1410  if (TL.isDefinition())
1411    return Visit(MakeCXCursor(TL.getDecl(), TU, RegionOfInterest));
1412
1413  return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1414}
1415
1416bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
1417  return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1418}
1419
1420bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
1421  if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
1422    return true;
1423
1424  return false;
1425}
1426
1427bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
1428  if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
1429    return true;
1430
1431  for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1432    if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1433                                        TU)))
1434      return true;
1435  }
1436
1437  return false;
1438}
1439
1440bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
1441  return Visit(TL.getPointeeLoc());
1442}
1443
1444bool CursorVisitor::VisitParenTypeLoc(ParenTypeLoc TL) {
1445  return Visit(TL.getInnerLoc());
1446}
1447
1448bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
1449  return Visit(TL.getPointeeLoc());
1450}
1451
1452bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1453  return Visit(TL.getPointeeLoc());
1454}
1455
1456bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1457  return Visit(TL.getPointeeLoc());
1458}
1459
1460bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
1461  return Visit(TL.getPointeeLoc());
1462}
1463
1464bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
1465  return Visit(TL.getPointeeLoc());
1466}
1467
1468bool CursorVisitor::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
1469  return Visit(TL.getModifiedLoc());
1470}
1471
1472bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL,
1473                                         bool SkipResultType) {
1474  if (!SkipResultType && Visit(TL.getResultLoc()))
1475    return true;
1476
1477  for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1478    if (Decl *D = TL.getArg(I))
1479      if (Visit(MakeCXCursor(D, TU, RegionOfInterest)))
1480        return true;
1481
1482  return false;
1483}
1484
1485bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
1486  if (Visit(TL.getElementLoc()))
1487    return true;
1488
1489  if (Expr *Size = TL.getSizeExpr())
1490    return Visit(MakeCXCursor(Size, StmtParent, TU, RegionOfInterest));
1491
1492  return false;
1493}
1494
1495bool CursorVisitor::VisitTemplateSpecializationTypeLoc(
1496                                             TemplateSpecializationTypeLoc TL) {
1497  // Visit the template name.
1498  if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1499                        TL.getTemplateNameLoc()))
1500    return true;
1501
1502  // Visit the template arguments.
1503  for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1504    if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1505      return true;
1506
1507  return false;
1508}
1509
1510bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
1511  return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
1512}
1513
1514bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
1515  if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1516    return Visit(TSInfo->getTypeLoc());
1517
1518  return false;
1519}
1520
1521bool CursorVisitor::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
1522  if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1523    return Visit(TSInfo->getTypeLoc());
1524
1525  return false;
1526}
1527
1528bool CursorVisitor::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
1529  if (VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1530    return true;
1531
1532  return false;
1533}
1534
1535bool CursorVisitor::VisitDependentTemplateSpecializationTypeLoc(
1536                                    DependentTemplateSpecializationTypeLoc TL) {
1537  // Visit the nested-name-specifier, if there is one.
1538  if (TL.getQualifierLoc() &&
1539      VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1540    return true;
1541
1542  // Visit the template arguments.
1543  for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1544    if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1545      return true;
1546
1547  return false;
1548}
1549
1550bool CursorVisitor::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
1551  if (VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1552    return true;
1553
1554  return Visit(TL.getNamedTypeLoc());
1555}
1556
1557bool CursorVisitor::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
1558  return Visit(TL.getPatternLoc());
1559}
1560
1561bool CursorVisitor::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
1562  if (Expr *E = TL.getUnderlyingExpr())
1563    return Visit(MakeCXCursor(E, StmtParent, TU));
1564
1565  return false;
1566}
1567
1568bool CursorVisitor::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
1569  return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1570}
1571
1572bool CursorVisitor::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
1573  return Visit(TL.getValueLoc());
1574}
1575
1576#define DEFAULT_TYPELOC_IMPL(CLASS, PARENT) \
1577bool CursorVisitor::Visit##CLASS##TypeLoc(CLASS##TypeLoc TL) { \
1578  return Visit##PARENT##Loc(TL); \
1579}
1580
1581DEFAULT_TYPELOC_IMPL(Complex, Type)
1582DEFAULT_TYPELOC_IMPL(ConstantArray, ArrayType)
1583DEFAULT_TYPELOC_IMPL(IncompleteArray, ArrayType)
1584DEFAULT_TYPELOC_IMPL(VariableArray, ArrayType)
1585DEFAULT_TYPELOC_IMPL(DependentSizedArray, ArrayType)
1586DEFAULT_TYPELOC_IMPL(DependentSizedExtVector, Type)
1587DEFAULT_TYPELOC_IMPL(Vector, Type)
1588DEFAULT_TYPELOC_IMPL(ExtVector, VectorType)
1589DEFAULT_TYPELOC_IMPL(FunctionProto, FunctionType)
1590DEFAULT_TYPELOC_IMPL(FunctionNoProto, FunctionType)
1591DEFAULT_TYPELOC_IMPL(Record, TagType)
1592DEFAULT_TYPELOC_IMPL(Enum, TagType)
1593DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParm, Type)
1594DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParmPack, Type)
1595DEFAULT_TYPELOC_IMPL(Auto, Type)
1596
1597bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
1598  // Visit the nested-name-specifier, if present.
1599  if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1600    if (VisitNestedNameSpecifierLoc(QualifierLoc))
1601      return true;
1602
1603  if (D->isCompleteDefinition()) {
1604    for (CXXRecordDecl::base_class_iterator I = D->bases_begin(),
1605         E = D->bases_end(); I != E; ++I) {
1606      if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(I, TU)))
1607        return true;
1608    }
1609  }
1610
1611  return VisitTagDecl(D);
1612}
1613
1614bool CursorVisitor::VisitAttributes(Decl *D) {
1615  for (AttrVec::const_iterator i = D->attr_begin(), e = D->attr_end();
1616       i != e; ++i)
1617    if (Visit(MakeCXCursor(*i, D, TU)))
1618        return true;
1619
1620  return false;
1621}
1622
1623//===----------------------------------------------------------------------===//
1624// Data-recursive visitor methods.
1625//===----------------------------------------------------------------------===//
1626
1627namespace {
1628#define DEF_JOB(NAME, DATA, KIND)\
1629class NAME : public VisitorJob {\
1630public:\
1631  NAME(DATA *d, CXCursor parent) : VisitorJob(parent, VisitorJob::KIND, d) {} \
1632  static bool classof(const VisitorJob *VJ) { return VJ->getKind() == KIND; }\
1633  DATA *get() const { return static_cast<DATA*>(data[0]); }\
1634};
1635
1636DEF_JOB(StmtVisit, Stmt, StmtVisitKind)
1637DEF_JOB(MemberExprParts, MemberExpr, MemberExprPartsKind)
1638DEF_JOB(DeclRefExprParts, DeclRefExpr, DeclRefExprPartsKind)
1639DEF_JOB(OverloadExprParts, OverloadExpr, OverloadExprPartsKind)
1640DEF_JOB(ExplicitTemplateArgsVisit, ASTTemplateArgumentListInfo,
1641        ExplicitTemplateArgsVisitKind)
1642DEF_JOB(SizeOfPackExprParts, SizeOfPackExpr, SizeOfPackExprPartsKind)
1643#undef DEF_JOB
1644
1645class DeclVisit : public VisitorJob {
1646public:
1647  DeclVisit(Decl *d, CXCursor parent, bool isFirst) :
1648    VisitorJob(parent, VisitorJob::DeclVisitKind,
1649               d, isFirst ? (void*) 1 : (void*) 0) {}
1650  static bool classof(const VisitorJob *VJ) {
1651    return VJ->getKind() == DeclVisitKind;
1652  }
1653  Decl *get() const { return static_cast<Decl*>(data[0]); }
1654  bool isFirst() const { return data[1] ? true : false; }
1655};
1656class TypeLocVisit : public VisitorJob {
1657public:
1658  TypeLocVisit(TypeLoc tl, CXCursor parent) :
1659    VisitorJob(parent, VisitorJob::TypeLocVisitKind,
1660               tl.getType().getAsOpaquePtr(), tl.getOpaqueData()) {}
1661
1662  static bool classof(const VisitorJob *VJ) {
1663    return VJ->getKind() == TypeLocVisitKind;
1664  }
1665
1666  TypeLoc get() const {
1667    QualType T = QualType::getFromOpaquePtr(data[0]);
1668    return TypeLoc(T, data[1]);
1669  }
1670};
1671
1672class LabelRefVisit : public VisitorJob {
1673public:
1674  LabelRefVisit(LabelDecl *LD, SourceLocation labelLoc, CXCursor parent)
1675    : VisitorJob(parent, VisitorJob::LabelRefVisitKind, LD,
1676                 labelLoc.getPtrEncoding()) {}
1677
1678  static bool classof(const VisitorJob *VJ) {
1679    return VJ->getKind() == VisitorJob::LabelRefVisitKind;
1680  }
1681  LabelDecl *get() const { return static_cast<LabelDecl*>(data[0]); }
1682  SourceLocation getLoc() const {
1683    return SourceLocation::getFromPtrEncoding(data[1]); }
1684};
1685
1686class NestedNameSpecifierLocVisit : public VisitorJob {
1687public:
1688  NestedNameSpecifierLocVisit(NestedNameSpecifierLoc Qualifier, CXCursor parent)
1689    : VisitorJob(parent, VisitorJob::NestedNameSpecifierLocVisitKind,
1690                 Qualifier.getNestedNameSpecifier(),
1691                 Qualifier.getOpaqueData()) { }
1692
1693  static bool classof(const VisitorJob *VJ) {
1694    return VJ->getKind() == VisitorJob::NestedNameSpecifierLocVisitKind;
1695  }
1696
1697  NestedNameSpecifierLoc get() const {
1698    return NestedNameSpecifierLoc(static_cast<NestedNameSpecifier*>(data[0]),
1699                                  data[1]);
1700  }
1701};
1702
1703class DeclarationNameInfoVisit : public VisitorJob {
1704public:
1705  DeclarationNameInfoVisit(Stmt *S, CXCursor parent)
1706    : VisitorJob(parent, VisitorJob::DeclarationNameInfoVisitKind, S) {}
1707  static bool classof(const VisitorJob *VJ) {
1708    return VJ->getKind() == VisitorJob::DeclarationNameInfoVisitKind;
1709  }
1710  DeclarationNameInfo get() const {
1711    Stmt *S = static_cast<Stmt*>(data[0]);
1712    switch (S->getStmtClass()) {
1713    default:
1714      llvm_unreachable("Unhandled Stmt");
1715    case Stmt::CXXDependentScopeMemberExprClass:
1716      return cast<CXXDependentScopeMemberExpr>(S)->getMemberNameInfo();
1717    case Stmt::DependentScopeDeclRefExprClass:
1718      return cast<DependentScopeDeclRefExpr>(S)->getNameInfo();
1719    }
1720  }
1721};
1722class MemberRefVisit : public VisitorJob {
1723public:
1724  MemberRefVisit(FieldDecl *D, SourceLocation L, CXCursor parent)
1725    : VisitorJob(parent, VisitorJob::MemberRefVisitKind, D,
1726                 L.getPtrEncoding()) {}
1727  static bool classof(const VisitorJob *VJ) {
1728    return VJ->getKind() == VisitorJob::MemberRefVisitKind;
1729  }
1730  FieldDecl *get() const {
1731    return static_cast<FieldDecl*>(data[0]);
1732  }
1733  SourceLocation getLoc() const {
1734    return SourceLocation::getFromRawEncoding((unsigned)(uintptr_t) data[1]);
1735  }
1736};
1737class EnqueueVisitor : public StmtVisitor<EnqueueVisitor, void> {
1738  VisitorWorkList &WL;
1739  CXCursor Parent;
1740public:
1741  EnqueueVisitor(VisitorWorkList &wl, CXCursor parent)
1742    : WL(wl), Parent(parent) {}
1743
1744  void VisitAddrLabelExpr(AddrLabelExpr *E);
1745  void VisitBlockExpr(BlockExpr *B);
1746  void VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
1747  void VisitCompoundStmt(CompoundStmt *S);
1748  void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { /* Do nothing. */ }
1749  void VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E);
1750  void VisitCXXNewExpr(CXXNewExpr *E);
1751  void VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
1752  void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E);
1753  void VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E);
1754  void VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E);
1755  void VisitCXXTypeidExpr(CXXTypeidExpr *E);
1756  void VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr *E);
1757  void VisitCXXUuidofExpr(CXXUuidofExpr *E);
1758  void VisitDeclRefExpr(DeclRefExpr *D);
1759  void VisitDeclStmt(DeclStmt *S);
1760  void VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E);
1761  void VisitDesignatedInitExpr(DesignatedInitExpr *E);
1762  void VisitExplicitCastExpr(ExplicitCastExpr *E);
1763  void VisitForStmt(ForStmt *FS);
1764  void VisitGotoStmt(GotoStmt *GS);
1765  void VisitIfStmt(IfStmt *If);
1766  void VisitInitListExpr(InitListExpr *IE);
1767  void VisitMemberExpr(MemberExpr *M);
1768  void VisitOffsetOfExpr(OffsetOfExpr *E);
1769  void VisitObjCEncodeExpr(ObjCEncodeExpr *E);
1770  void VisitObjCMessageExpr(ObjCMessageExpr *M);
1771  void VisitOverloadExpr(OverloadExpr *E);
1772  void VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E);
1773  void VisitStmt(Stmt *S);
1774  void VisitSwitchStmt(SwitchStmt *S);
1775  void VisitWhileStmt(WhileStmt *W);
1776  void VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E);
1777  void VisitBinaryTypeTraitExpr(BinaryTypeTraitExpr *E);
1778  void VisitArrayTypeTraitExpr(ArrayTypeTraitExpr *E);
1779  void VisitExpressionTraitExpr(ExpressionTraitExpr *E);
1780  void VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U);
1781  void VisitVAArgExpr(VAArgExpr *E);
1782  void VisitSizeOfPackExpr(SizeOfPackExpr *E);
1783
1784private:
1785  void AddDeclarationNameInfo(Stmt *S);
1786  void AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier);
1787  void AddExplicitTemplateArgs(const ASTTemplateArgumentListInfo *A);
1788  void AddMemberRef(FieldDecl *D, SourceLocation L);
1789  void AddStmt(Stmt *S);
1790  void AddDecl(Decl *D, bool isFirst = true);
1791  void AddTypeLoc(TypeSourceInfo *TI);
1792  void EnqueueChildren(Stmt *S);
1793};
1794} // end anonyous namespace
1795
1796void EnqueueVisitor::AddDeclarationNameInfo(Stmt *S) {
1797  // 'S' should always be non-null, since it comes from the
1798  // statement we are visiting.
1799  WL.push_back(DeclarationNameInfoVisit(S, Parent));
1800}
1801
1802void
1803EnqueueVisitor::AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
1804  if (Qualifier)
1805    WL.push_back(NestedNameSpecifierLocVisit(Qualifier, Parent));
1806}
1807
1808void EnqueueVisitor::AddStmt(Stmt *S) {
1809  if (S)
1810    WL.push_back(StmtVisit(S, Parent));
1811}
1812void EnqueueVisitor::AddDecl(Decl *D, bool isFirst) {
1813  if (D)
1814    WL.push_back(DeclVisit(D, Parent, isFirst));
1815}
1816void EnqueueVisitor::
1817  AddExplicitTemplateArgs(const ASTTemplateArgumentListInfo *A) {
1818  if (A)
1819    WL.push_back(ExplicitTemplateArgsVisit(
1820                        const_cast<ASTTemplateArgumentListInfo*>(A), Parent));
1821}
1822void EnqueueVisitor::AddMemberRef(FieldDecl *D, SourceLocation L) {
1823  if (D)
1824    WL.push_back(MemberRefVisit(D, L, Parent));
1825}
1826void EnqueueVisitor::AddTypeLoc(TypeSourceInfo *TI) {
1827  if (TI)
1828    WL.push_back(TypeLocVisit(TI->getTypeLoc(), Parent));
1829 }
1830void EnqueueVisitor::EnqueueChildren(Stmt *S) {
1831  unsigned size = WL.size();
1832  for (Stmt::child_range Child = S->children(); Child; ++Child) {
1833    AddStmt(*Child);
1834  }
1835  if (size == WL.size())
1836    return;
1837  // Now reverse the entries we just added.  This will match the DFS
1838  // ordering performed by the worklist.
1839  VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1840  std::reverse(I, E);
1841}
1842void EnqueueVisitor::VisitAddrLabelExpr(AddrLabelExpr *E) {
1843  WL.push_back(LabelRefVisit(E->getLabel(), E->getLabelLoc(), Parent));
1844}
1845void EnqueueVisitor::VisitBlockExpr(BlockExpr *B) {
1846  AddDecl(B->getBlockDecl());
1847}
1848void EnqueueVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
1849  EnqueueChildren(E);
1850  AddTypeLoc(E->getTypeSourceInfo());
1851}
1852void EnqueueVisitor::VisitCompoundStmt(CompoundStmt *S) {
1853  for (CompoundStmt::reverse_body_iterator I = S->body_rbegin(),
1854        E = S->body_rend(); I != E; ++I) {
1855    AddStmt(*I);
1856  }
1857}
1858void EnqueueVisitor::
1859VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E) {
1860  AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
1861  AddDeclarationNameInfo(E);
1862  if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
1863    AddNestedNameSpecifierLoc(QualifierLoc);
1864  if (!E->isImplicitAccess())
1865    AddStmt(E->getBase());
1866}
1867void EnqueueVisitor::VisitCXXNewExpr(CXXNewExpr *E) {
1868  // Enqueue the initializer or constructor arguments.
1869  for (unsigned I = E->getNumConstructorArgs(); I > 0; --I)
1870    AddStmt(E->getConstructorArg(I-1));
1871  // Enqueue the array size, if any.
1872  AddStmt(E->getArraySize());
1873  // Enqueue the allocated type.
1874  AddTypeLoc(E->getAllocatedTypeSourceInfo());
1875  // Enqueue the placement arguments.
1876  for (unsigned I = E->getNumPlacementArgs(); I > 0; --I)
1877    AddStmt(E->getPlacementArg(I-1));
1878}
1879void EnqueueVisitor::VisitCXXOperatorCallExpr(CXXOperatorCallExpr *CE) {
1880  for (unsigned I = CE->getNumArgs(); I > 1 /* Yes, this is 1 */; --I)
1881    AddStmt(CE->getArg(I-1));
1882  AddStmt(CE->getCallee());
1883  AddStmt(CE->getArg(0));
1884}
1885void EnqueueVisitor::VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E) {
1886  // Visit the name of the type being destroyed.
1887  AddTypeLoc(E->getDestroyedTypeInfo());
1888  // Visit the scope type that looks disturbingly like the nested-name-specifier
1889  // but isn't.
1890  AddTypeLoc(E->getScopeTypeInfo());
1891  // Visit the nested-name-specifier.
1892  if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
1893    AddNestedNameSpecifierLoc(QualifierLoc);
1894  // Visit base expression.
1895  AddStmt(E->getBase());
1896}
1897void EnqueueVisitor::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
1898  AddTypeLoc(E->getTypeSourceInfo());
1899}
1900void EnqueueVisitor::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E) {
1901  EnqueueChildren(E);
1902  AddTypeLoc(E->getTypeSourceInfo());
1903}
1904void EnqueueVisitor::VisitCXXTypeidExpr(CXXTypeidExpr *E) {
1905  EnqueueChildren(E);
1906  if (E->isTypeOperand())
1907    AddTypeLoc(E->getTypeOperandSourceInfo());
1908}
1909
1910void EnqueueVisitor::VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr
1911                                                     *E) {
1912  EnqueueChildren(E);
1913  AddTypeLoc(E->getTypeSourceInfo());
1914}
1915void EnqueueVisitor::VisitCXXUuidofExpr(CXXUuidofExpr *E) {
1916  EnqueueChildren(E);
1917  if (E->isTypeOperand())
1918    AddTypeLoc(E->getTypeOperandSourceInfo());
1919}
1920void EnqueueVisitor::VisitDeclRefExpr(DeclRefExpr *DR) {
1921  if (DR->hasExplicitTemplateArgs()) {
1922    AddExplicitTemplateArgs(&DR->getExplicitTemplateArgs());
1923  }
1924  WL.push_back(DeclRefExprParts(DR, Parent));
1925}
1926void EnqueueVisitor::VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E) {
1927  AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
1928  AddDeclarationNameInfo(E);
1929  AddNestedNameSpecifierLoc(E->getQualifierLoc());
1930}
1931void EnqueueVisitor::VisitDeclStmt(DeclStmt *S) {
1932  unsigned size = WL.size();
1933  bool isFirst = true;
1934  for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
1935       D != DEnd; ++D) {
1936    AddDecl(*D, isFirst);
1937    isFirst = false;
1938  }
1939  if (size == WL.size())
1940    return;
1941  // Now reverse the entries we just added.  This will match the DFS
1942  // ordering performed by the worklist.
1943  VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1944  std::reverse(I, E);
1945}
1946void EnqueueVisitor::VisitDesignatedInitExpr(DesignatedInitExpr *E) {
1947  AddStmt(E->getInit());
1948  typedef DesignatedInitExpr::Designator Designator;
1949  for (DesignatedInitExpr::reverse_designators_iterator
1950         D = E->designators_rbegin(), DEnd = E->designators_rend();
1951         D != DEnd; ++D) {
1952    if (D->isFieldDesignator()) {
1953      if (FieldDecl *Field = D->getField())
1954        AddMemberRef(Field, D->getFieldLoc());
1955      continue;
1956    }
1957    if (D->isArrayDesignator()) {
1958      AddStmt(E->getArrayIndex(*D));
1959      continue;
1960    }
1961    assert(D->isArrayRangeDesignator() && "Unknown designator kind");
1962    AddStmt(E->getArrayRangeEnd(*D));
1963    AddStmt(E->getArrayRangeStart(*D));
1964  }
1965}
1966void EnqueueVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
1967  EnqueueChildren(E);
1968  AddTypeLoc(E->getTypeInfoAsWritten());
1969}
1970void EnqueueVisitor::VisitForStmt(ForStmt *FS) {
1971  AddStmt(FS->getBody());
1972  AddStmt(FS->getInc());
1973  AddStmt(FS->getCond());
1974  AddDecl(FS->getConditionVariable());
1975  AddStmt(FS->getInit());
1976}
1977void EnqueueVisitor::VisitGotoStmt(GotoStmt *GS) {
1978  WL.push_back(LabelRefVisit(GS->getLabel(), GS->getLabelLoc(), Parent));
1979}
1980void EnqueueVisitor::VisitIfStmt(IfStmt *If) {
1981  AddStmt(If->getElse());
1982  AddStmt(If->getThen());
1983  AddStmt(If->getCond());
1984  AddDecl(If->getConditionVariable());
1985}
1986void EnqueueVisitor::VisitInitListExpr(InitListExpr *IE) {
1987  // We care about the syntactic form of the initializer list, only.
1988  if (InitListExpr *Syntactic = IE->getSyntacticForm())
1989    IE = Syntactic;
1990  EnqueueChildren(IE);
1991}
1992void EnqueueVisitor::VisitMemberExpr(MemberExpr *M) {
1993  WL.push_back(MemberExprParts(M, Parent));
1994
1995  // If the base of the member access expression is an implicit 'this', don't
1996  // visit it.
1997  // FIXME: If we ever want to show these implicit accesses, this will be
1998  // unfortunate. However, clang_getCursor() relies on this behavior.
1999  if (!M->isImplicitAccess())
2000    AddStmt(M->getBase());
2001}
2002void EnqueueVisitor::VisitObjCEncodeExpr(ObjCEncodeExpr *E) {
2003  AddTypeLoc(E->getEncodedTypeSourceInfo());
2004}
2005void EnqueueVisitor::VisitObjCMessageExpr(ObjCMessageExpr *M) {
2006  EnqueueChildren(M);
2007  AddTypeLoc(M->getClassReceiverTypeInfo());
2008}
2009void EnqueueVisitor::VisitOffsetOfExpr(OffsetOfExpr *E) {
2010  // Visit the components of the offsetof expression.
2011  for (unsigned N = E->getNumComponents(), I = N; I > 0; --I) {
2012    typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
2013    const OffsetOfNode &Node = E->getComponent(I-1);
2014    switch (Node.getKind()) {
2015    case OffsetOfNode::Array:
2016      AddStmt(E->getIndexExpr(Node.getArrayExprIndex()));
2017      break;
2018    case OffsetOfNode::Field:
2019      AddMemberRef(Node.getField(), Node.getSourceRange().getEnd());
2020      break;
2021    case OffsetOfNode::Identifier:
2022    case OffsetOfNode::Base:
2023      continue;
2024    }
2025  }
2026  // Visit the type into which we're computing the offset.
2027  AddTypeLoc(E->getTypeSourceInfo());
2028}
2029void EnqueueVisitor::VisitOverloadExpr(OverloadExpr *E) {
2030  AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
2031  WL.push_back(OverloadExprParts(E, Parent));
2032}
2033void EnqueueVisitor::VisitUnaryExprOrTypeTraitExpr(
2034                                              UnaryExprOrTypeTraitExpr *E) {
2035  EnqueueChildren(E);
2036  if (E->isArgumentType())
2037    AddTypeLoc(E->getArgumentTypeInfo());
2038}
2039void EnqueueVisitor::VisitStmt(Stmt *S) {
2040  EnqueueChildren(S);
2041}
2042void EnqueueVisitor::VisitSwitchStmt(SwitchStmt *S) {
2043  AddStmt(S->getBody());
2044  AddStmt(S->getCond());
2045  AddDecl(S->getConditionVariable());
2046}
2047
2048void EnqueueVisitor::VisitWhileStmt(WhileStmt *W) {
2049  AddStmt(W->getBody());
2050  AddStmt(W->getCond());
2051  AddDecl(W->getConditionVariable());
2052}
2053
2054void EnqueueVisitor::VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E) {
2055  AddTypeLoc(E->getQueriedTypeSourceInfo());
2056}
2057
2058void EnqueueVisitor::VisitBinaryTypeTraitExpr(BinaryTypeTraitExpr *E) {
2059  AddTypeLoc(E->getRhsTypeSourceInfo());
2060  AddTypeLoc(E->getLhsTypeSourceInfo());
2061}
2062
2063void EnqueueVisitor::VisitArrayTypeTraitExpr(ArrayTypeTraitExpr *E) {
2064  AddTypeLoc(E->getQueriedTypeSourceInfo());
2065}
2066
2067void EnqueueVisitor::VisitExpressionTraitExpr(ExpressionTraitExpr *E) {
2068  EnqueueChildren(E);
2069}
2070
2071void EnqueueVisitor::VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U) {
2072  VisitOverloadExpr(U);
2073  if (!U->isImplicitAccess())
2074    AddStmt(U->getBase());
2075}
2076void EnqueueVisitor::VisitVAArgExpr(VAArgExpr *E) {
2077  AddStmt(E->getSubExpr());
2078  AddTypeLoc(E->getWrittenTypeInfo());
2079}
2080void EnqueueVisitor::VisitSizeOfPackExpr(SizeOfPackExpr *E) {
2081  WL.push_back(SizeOfPackExprParts(E, Parent));
2082}
2083
2084void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, Stmt *S) {
2085  EnqueueVisitor(WL, MakeCXCursor(S, StmtParent, TU,RegionOfInterest)).Visit(S);
2086}
2087
2088bool CursorVisitor::IsInRegionOfInterest(CXCursor C) {
2089  if (RegionOfInterest.isValid()) {
2090    SourceRange Range = getRawCursorExtent(C);
2091    if (Range.isInvalid() || CompareRegionOfInterest(Range))
2092      return false;
2093  }
2094  return true;
2095}
2096
2097bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) {
2098  while (!WL.empty()) {
2099    // Dequeue the worklist item.
2100    VisitorJob LI = WL.back();
2101    WL.pop_back();
2102
2103    // Set the Parent field, then back to its old value once we're done.
2104    SetParentRAII SetParent(Parent, StmtParent, LI.getParent());
2105
2106    switch (LI.getKind()) {
2107      case VisitorJob::DeclVisitKind: {
2108        Decl *D = cast<DeclVisit>(&LI)->get();
2109        if (!D)
2110          continue;
2111
2112        // For now, perform default visitation for Decls.
2113        if (Visit(MakeCXCursor(D, TU, RegionOfInterest,
2114                               cast<DeclVisit>(&LI)->isFirst())))
2115            return true;
2116
2117        continue;
2118      }
2119      case VisitorJob::ExplicitTemplateArgsVisitKind: {
2120        const ASTTemplateArgumentListInfo *ArgList =
2121          cast<ExplicitTemplateArgsVisit>(&LI)->get();
2122        for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
2123               *ArgEnd = Arg + ArgList->NumTemplateArgs;
2124               Arg != ArgEnd; ++Arg) {
2125          if (VisitTemplateArgumentLoc(*Arg))
2126            return true;
2127        }
2128        continue;
2129      }
2130      case VisitorJob::TypeLocVisitKind: {
2131        // Perform default visitation for TypeLocs.
2132        if (Visit(cast<TypeLocVisit>(&LI)->get()))
2133          return true;
2134        continue;
2135      }
2136      case VisitorJob::LabelRefVisitKind: {
2137        LabelDecl *LS = cast<LabelRefVisit>(&LI)->get();
2138        if (LabelStmt *stmt = LS->getStmt()) {
2139          if (Visit(MakeCursorLabelRef(stmt, cast<LabelRefVisit>(&LI)->getLoc(),
2140                                       TU))) {
2141            return true;
2142          }
2143        }
2144        continue;
2145      }
2146
2147      case VisitorJob::NestedNameSpecifierLocVisitKind: {
2148        NestedNameSpecifierLocVisit *V = cast<NestedNameSpecifierLocVisit>(&LI);
2149        if (VisitNestedNameSpecifierLoc(V->get()))
2150          return true;
2151        continue;
2152      }
2153
2154      case VisitorJob::DeclarationNameInfoVisitKind: {
2155        if (VisitDeclarationNameInfo(cast<DeclarationNameInfoVisit>(&LI)
2156                                     ->get()))
2157          return true;
2158        continue;
2159      }
2160      case VisitorJob::MemberRefVisitKind: {
2161        MemberRefVisit *V = cast<MemberRefVisit>(&LI);
2162        if (Visit(MakeCursorMemberRef(V->get(), V->getLoc(), TU)))
2163          return true;
2164        continue;
2165      }
2166      case VisitorJob::StmtVisitKind: {
2167        Stmt *S = cast<StmtVisit>(&LI)->get();
2168        if (!S)
2169          continue;
2170
2171        // Update the current cursor.
2172        CXCursor Cursor = MakeCXCursor(S, StmtParent, TU, RegionOfInterest);
2173        if (!IsInRegionOfInterest(Cursor))
2174          continue;
2175        switch (Visitor(Cursor, Parent, ClientData)) {
2176          case CXChildVisit_Break: return true;
2177          case CXChildVisit_Continue: break;
2178          case CXChildVisit_Recurse:
2179            EnqueueWorkList(WL, S);
2180            break;
2181        }
2182        continue;
2183      }
2184      case VisitorJob::MemberExprPartsKind: {
2185        // Handle the other pieces in the MemberExpr besides the base.
2186        MemberExpr *M = cast<MemberExprParts>(&LI)->get();
2187
2188        // Visit the nested-name-specifier
2189        if (NestedNameSpecifierLoc QualifierLoc = M->getQualifierLoc())
2190          if (VisitNestedNameSpecifierLoc(QualifierLoc))
2191            return true;
2192
2193        // Visit the declaration name.
2194        if (VisitDeclarationNameInfo(M->getMemberNameInfo()))
2195          return true;
2196
2197        // Visit the explicitly-specified template arguments, if any.
2198        if (M->hasExplicitTemplateArgs()) {
2199          for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(),
2200               *ArgEnd = Arg + M->getNumTemplateArgs();
2201               Arg != ArgEnd; ++Arg) {
2202            if (VisitTemplateArgumentLoc(*Arg))
2203              return true;
2204          }
2205        }
2206        continue;
2207      }
2208      case VisitorJob::DeclRefExprPartsKind: {
2209        DeclRefExpr *DR = cast<DeclRefExprParts>(&LI)->get();
2210        // Visit nested-name-specifier, if present.
2211        if (NestedNameSpecifierLoc QualifierLoc = DR->getQualifierLoc())
2212          if (VisitNestedNameSpecifierLoc(QualifierLoc))
2213            return true;
2214        // Visit declaration name.
2215        if (VisitDeclarationNameInfo(DR->getNameInfo()))
2216          return true;
2217        continue;
2218      }
2219      case VisitorJob::OverloadExprPartsKind: {
2220        OverloadExpr *O = cast<OverloadExprParts>(&LI)->get();
2221        // Visit the nested-name-specifier.
2222        if (NestedNameSpecifierLoc QualifierLoc = O->getQualifierLoc())
2223          if (VisitNestedNameSpecifierLoc(QualifierLoc))
2224            return true;
2225        // Visit the declaration name.
2226        if (VisitDeclarationNameInfo(O->getNameInfo()))
2227          return true;
2228        // Visit the overloaded declaration reference.
2229        if (Visit(MakeCursorOverloadedDeclRef(O, TU)))
2230          return true;
2231        continue;
2232      }
2233      case VisitorJob::SizeOfPackExprPartsKind: {
2234        SizeOfPackExpr *E = cast<SizeOfPackExprParts>(&LI)->get();
2235        NamedDecl *Pack = E->getPack();
2236        if (isa<TemplateTypeParmDecl>(Pack)) {
2237          if (Visit(MakeCursorTypeRef(cast<TemplateTypeParmDecl>(Pack),
2238                                      E->getPackLoc(), TU)))
2239            return true;
2240
2241          continue;
2242        }
2243
2244        if (isa<TemplateTemplateParmDecl>(Pack)) {
2245          if (Visit(MakeCursorTemplateRef(cast<TemplateTemplateParmDecl>(Pack),
2246                                          E->getPackLoc(), TU)))
2247            return true;
2248
2249          continue;
2250        }
2251
2252        // Non-type template parameter packs and function parameter packs are
2253        // treated like DeclRefExpr cursors.
2254        continue;
2255      }
2256    }
2257  }
2258  return false;
2259}
2260
2261bool CursorVisitor::Visit(Stmt *S) {
2262  VisitorWorkList *WL = 0;
2263  if (!WorkListFreeList.empty()) {
2264    WL = WorkListFreeList.back();
2265    WL->clear();
2266    WorkListFreeList.pop_back();
2267  }
2268  else {
2269    WL = new VisitorWorkList();
2270    WorkListCache.push_back(WL);
2271  }
2272  EnqueueWorkList(*WL, S);
2273  bool result = RunVisitorWorkList(*WL);
2274  WorkListFreeList.push_back(WL);
2275  return result;
2276}
2277
2278namespace {
2279typedef llvm::SmallVector<SourceRange, 4> RefNamePieces;
2280RefNamePieces buildPieces(unsigned NameFlags, bool IsMemberRefExpr,
2281                          const DeclarationNameInfo &NI,
2282                          const SourceRange &QLoc,
2283                          const ASTTemplateArgumentListInfo *TemplateArgs = 0){
2284  const bool WantQualifier = NameFlags & CXNameRange_WantQualifier;
2285  const bool WantTemplateArgs = NameFlags & CXNameRange_WantTemplateArgs;
2286  const bool WantSinglePiece = NameFlags & CXNameRange_WantSinglePiece;
2287
2288  const DeclarationName::NameKind Kind = NI.getName().getNameKind();
2289
2290  RefNamePieces Pieces;
2291
2292  if (WantQualifier && QLoc.isValid())
2293    Pieces.push_back(QLoc);
2294
2295  if (Kind != DeclarationName::CXXOperatorName || IsMemberRefExpr)
2296    Pieces.push_back(NI.getLoc());
2297
2298  if (WantTemplateArgs && TemplateArgs)
2299    Pieces.push_back(SourceRange(TemplateArgs->LAngleLoc,
2300                                 TemplateArgs->RAngleLoc));
2301
2302  if (Kind == DeclarationName::CXXOperatorName) {
2303    Pieces.push_back(SourceLocation::getFromRawEncoding(
2304                       NI.getInfo().CXXOperatorName.BeginOpNameLoc));
2305    Pieces.push_back(SourceLocation::getFromRawEncoding(
2306                       NI.getInfo().CXXOperatorName.EndOpNameLoc));
2307  }
2308
2309  if (WantSinglePiece) {
2310    SourceRange R(Pieces.front().getBegin(), Pieces.back().getEnd());
2311    Pieces.clear();
2312    Pieces.push_back(R);
2313  }
2314
2315  return Pieces;
2316}
2317}
2318
2319//===----------------------------------------------------------------------===//
2320// Misc. API hooks.
2321//===----------------------------------------------------------------------===//
2322
2323static llvm::sys::Mutex EnableMultithreadingMutex;
2324static bool EnabledMultithreading;
2325
2326extern "C" {
2327CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
2328                          int displayDiagnostics) {
2329  // Disable pretty stack trace functionality, which will otherwise be a very
2330  // poor citizen of the world and set up all sorts of signal handlers.
2331  llvm::DisablePrettyStackTrace = true;
2332
2333  // We use crash recovery to make some of our APIs more reliable, implicitly
2334  // enable it.
2335  llvm::CrashRecoveryContext::Enable();
2336
2337  // Enable support for multithreading in LLVM.
2338  {
2339    llvm::sys::ScopedLock L(EnableMultithreadingMutex);
2340    if (!EnabledMultithreading) {
2341      llvm::llvm_start_multithreaded();
2342      EnabledMultithreading = true;
2343    }
2344  }
2345
2346  CIndexer *CIdxr = new CIndexer();
2347  if (excludeDeclarationsFromPCH)
2348    CIdxr->setOnlyLocalDecls();
2349  if (displayDiagnostics)
2350    CIdxr->setDisplayDiagnostics();
2351  return CIdxr;
2352}
2353
2354void clang_disposeIndex(CXIndex CIdx) {
2355  if (CIdx)
2356    delete static_cast<CIndexer *>(CIdx);
2357}
2358
2359void clang_toggleCrashRecovery(unsigned isEnabled) {
2360  if (isEnabled)
2361    llvm::CrashRecoveryContext::Enable();
2362  else
2363    llvm::CrashRecoveryContext::Disable();
2364}
2365
2366CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
2367                                              const char *ast_filename) {
2368  if (!CIdx)
2369    return 0;
2370
2371  CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
2372  FileSystemOptions FileSystemOpts;
2373  FileSystemOpts.WorkingDir = CXXIdx->getWorkingDirectory();
2374
2375  llvm::IntrusiveRefCntPtr<DiagnosticsEngine> Diags;
2376  ASTUnit *TU = ASTUnit::LoadFromASTFile(ast_filename, Diags, FileSystemOpts,
2377                                  CXXIdx->getOnlyLocalDecls(),
2378                                  0, 0, true);
2379  return MakeCXTranslationUnit(TU);
2380}
2381
2382unsigned clang_defaultEditingTranslationUnitOptions() {
2383  return CXTranslationUnit_PrecompiledPreamble |
2384         CXTranslationUnit_CacheCompletionResults;
2385}
2386
2387CXTranslationUnit
2388clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
2389                                          const char *source_filename,
2390                                          int num_command_line_args,
2391                                          const char * const *command_line_args,
2392                                          unsigned num_unsaved_files,
2393                                          struct CXUnsavedFile *unsaved_files) {
2394  unsigned Options = CXTranslationUnit_DetailedPreprocessingRecord |
2395                     CXTranslationUnit_NestedMacroExpansions;
2396  return clang_parseTranslationUnit(CIdx, source_filename,
2397                                    command_line_args, num_command_line_args,
2398                                    unsaved_files, num_unsaved_files,
2399                                    Options);
2400}
2401
2402struct ParseTranslationUnitInfo {
2403  CXIndex CIdx;
2404  const char *source_filename;
2405  const char *const *command_line_args;
2406  int num_command_line_args;
2407  struct CXUnsavedFile *unsaved_files;
2408  unsigned num_unsaved_files;
2409  unsigned options;
2410  CXTranslationUnit result;
2411};
2412static void clang_parseTranslationUnit_Impl(void *UserData) {
2413  ParseTranslationUnitInfo *PTUI =
2414    static_cast<ParseTranslationUnitInfo*>(UserData);
2415  CXIndex CIdx = PTUI->CIdx;
2416  const char *source_filename = PTUI->source_filename;
2417  const char * const *command_line_args = PTUI->command_line_args;
2418  int num_command_line_args = PTUI->num_command_line_args;
2419  struct CXUnsavedFile *unsaved_files = PTUI->unsaved_files;
2420  unsigned num_unsaved_files = PTUI->num_unsaved_files;
2421  unsigned options = PTUI->options;
2422  PTUI->result = 0;
2423
2424  if (!CIdx)
2425    return;
2426
2427  CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
2428
2429  bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
2430  // FIXME: Add a flag for modules.
2431  TranslationUnitKind TUKind
2432    = (options & CXTranslationUnit_Incomplete)? TU_Prefix : TU_Complete;
2433  bool CacheCodeCompetionResults
2434    = options & CXTranslationUnit_CacheCompletionResults;
2435
2436  // Configure the diagnostics.
2437  DiagnosticOptions DiagOpts;
2438  llvm::IntrusiveRefCntPtr<DiagnosticsEngine>
2439    Diags(CompilerInstance::createDiagnostics(DiagOpts, num_command_line_args,
2440                                                command_line_args));
2441
2442  // Recover resources if we crash before exiting this function.
2443  llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
2444    llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
2445    DiagCleanup(Diags.getPtr());
2446
2447  llvm::OwningPtr<std::vector<ASTUnit::RemappedFile> >
2448    RemappedFiles(new std::vector<ASTUnit::RemappedFile>());
2449
2450  // Recover resources if we crash before exiting this function.
2451  llvm::CrashRecoveryContextCleanupRegistrar<
2452    std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
2453
2454  for (unsigned I = 0; I != num_unsaved_files; ++I) {
2455    StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
2456    const llvm::MemoryBuffer *Buffer
2457      = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
2458    RemappedFiles->push_back(std::make_pair(unsaved_files[I].Filename,
2459                                            Buffer));
2460  }
2461
2462  llvm::OwningPtr<std::vector<const char *> >
2463    Args(new std::vector<const char*>());
2464
2465  // Recover resources if we crash before exiting this method.
2466  llvm::CrashRecoveryContextCleanupRegistrar<std::vector<const char*> >
2467    ArgsCleanup(Args.get());
2468
2469  // Since the Clang C library is primarily used by batch tools dealing with
2470  // (often very broken) source code, where spell-checking can have a
2471  // significant negative impact on performance (particularly when
2472  // precompiled headers are involved), we disable it by default.
2473  // Only do this if we haven't found a spell-checking-related argument.
2474  bool FoundSpellCheckingArgument = false;
2475  for (int I = 0; I != num_command_line_args; ++I) {
2476    if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
2477        strcmp(command_line_args[I], "-fspell-checking") == 0) {
2478      FoundSpellCheckingArgument = true;
2479      break;
2480    }
2481  }
2482  if (!FoundSpellCheckingArgument)
2483    Args->push_back("-fno-spell-checking");
2484
2485  Args->insert(Args->end(), command_line_args,
2486               command_line_args + num_command_line_args);
2487
2488  // The 'source_filename' argument is optional.  If the caller does not
2489  // specify it then it is assumed that the source file is specified
2490  // in the actual argument list.
2491  // Put the source file after command_line_args otherwise if '-x' flag is
2492  // present it will be unused.
2493  if (source_filename)
2494    Args->push_back(source_filename);
2495
2496  // Do we need the detailed preprocessing record?
2497  bool NestedMacroExpansions = false;
2498  if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
2499    Args->push_back("-Xclang");
2500    Args->push_back("-detailed-preprocessing-record");
2501    NestedMacroExpansions
2502      = (options & CXTranslationUnit_NestedMacroExpansions);
2503  }
2504
2505  unsigned NumErrors = Diags->getClient()->getNumErrors();
2506  llvm::OwningPtr<ASTUnit> Unit(
2507    ASTUnit::LoadFromCommandLine(Args->size() ? &(*Args)[0] : 0
2508                                 /* vector::data() not portable */,
2509                                 Args->size() ? (&(*Args)[0] + Args->size()) :0,
2510                                 Diags,
2511                                 CXXIdx->getClangResourcesPath(),
2512                                 CXXIdx->getOnlyLocalDecls(),
2513                                 /*CaptureDiagnostics=*/true,
2514                                 RemappedFiles->size() ? &(*RemappedFiles)[0]:0,
2515                                 RemappedFiles->size(),
2516                                 /*RemappedFilesKeepOriginalName=*/true,
2517                                 PrecompilePreamble,
2518                                 TUKind,
2519                                 CacheCodeCompetionResults,
2520                                 NestedMacroExpansions));
2521
2522  if (NumErrors != Diags->getClient()->getNumErrors()) {
2523    // Make sure to check that 'Unit' is non-NULL.
2524    if (CXXIdx->getDisplayDiagnostics() && Unit.get()) {
2525      for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
2526                                      DEnd = Unit->stored_diag_end();
2527           D != DEnd; ++D) {
2528        CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOptions());
2529        CXString Msg = clang_formatDiagnostic(&Diag,
2530                                    clang_defaultDiagnosticDisplayOptions());
2531        fprintf(stderr, "%s\n", clang_getCString(Msg));
2532        clang_disposeString(Msg);
2533      }
2534#ifdef LLVM_ON_WIN32
2535      // On Windows, force a flush, since there may be multiple copies of
2536      // stderr and stdout in the file system, all with different buffers
2537      // but writing to the same device.
2538      fflush(stderr);
2539#endif
2540    }
2541  }
2542
2543  PTUI->result = MakeCXTranslationUnit(Unit.take());
2544}
2545CXTranslationUnit clang_parseTranslationUnit(CXIndex CIdx,
2546                                             const char *source_filename,
2547                                         const char * const *command_line_args,
2548                                             int num_command_line_args,
2549                                            struct CXUnsavedFile *unsaved_files,
2550                                             unsigned num_unsaved_files,
2551                                             unsigned options) {
2552  ParseTranslationUnitInfo PTUI = { CIdx, source_filename, command_line_args,
2553                                    num_command_line_args, unsaved_files,
2554                                    num_unsaved_files, options, 0 };
2555  llvm::CrashRecoveryContext CRC;
2556
2557  if (!RunSafely(CRC, clang_parseTranslationUnit_Impl, &PTUI)) {
2558    fprintf(stderr, "libclang: crash detected during parsing: {\n");
2559    fprintf(stderr, "  'source_filename' : '%s'\n", source_filename);
2560    fprintf(stderr, "  'command_line_args' : [");
2561    for (int i = 0; i != num_command_line_args; ++i) {
2562      if (i)
2563        fprintf(stderr, ", ");
2564      fprintf(stderr, "'%s'", command_line_args[i]);
2565    }
2566    fprintf(stderr, "],\n");
2567    fprintf(stderr, "  'unsaved_files' : [");
2568    for (unsigned i = 0; i != num_unsaved_files; ++i) {
2569      if (i)
2570        fprintf(stderr, ", ");
2571      fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
2572              unsaved_files[i].Length);
2573    }
2574    fprintf(stderr, "],\n");
2575    fprintf(stderr, "  'options' : %d,\n", options);
2576    fprintf(stderr, "}\n");
2577
2578    return 0;
2579  } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
2580    PrintLibclangResourceUsage(PTUI.result);
2581  }
2582
2583  return PTUI.result;
2584}
2585
2586unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
2587  return CXSaveTranslationUnit_None;
2588}
2589
2590int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
2591                              unsigned options) {
2592  if (!TU)
2593    return CXSaveError_InvalidTU;
2594
2595  CXSaveError result = static_cast<ASTUnit *>(TU->TUData)->Save(FileName);
2596  if (getenv("LIBCLANG_RESOURCE_USAGE"))
2597    PrintLibclangResourceUsage(TU);
2598  return result;
2599}
2600
2601void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
2602  if (CTUnit) {
2603    // If the translation unit has been marked as unsafe to free, just discard
2604    // it.
2605    if (static_cast<ASTUnit *>(CTUnit->TUData)->isUnsafeToFree())
2606      return;
2607
2608    delete static_cast<ASTUnit *>(CTUnit->TUData);
2609    disposeCXStringPool(CTUnit->StringPool);
2610    delete CTUnit;
2611  }
2612}
2613
2614unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
2615  return CXReparse_None;
2616}
2617
2618struct ReparseTranslationUnitInfo {
2619  CXTranslationUnit TU;
2620  unsigned num_unsaved_files;
2621  struct CXUnsavedFile *unsaved_files;
2622  unsigned options;
2623  int result;
2624};
2625
2626static void clang_reparseTranslationUnit_Impl(void *UserData) {
2627  ReparseTranslationUnitInfo *RTUI =
2628    static_cast<ReparseTranslationUnitInfo*>(UserData);
2629  CXTranslationUnit TU = RTUI->TU;
2630  unsigned num_unsaved_files = RTUI->num_unsaved_files;
2631  struct CXUnsavedFile *unsaved_files = RTUI->unsaved_files;
2632  unsigned options = RTUI->options;
2633  (void) options;
2634  RTUI->result = 1;
2635
2636  if (!TU)
2637    return;
2638
2639  ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
2640  ASTUnit::ConcurrencyCheck Check(*CXXUnit);
2641
2642  llvm::OwningPtr<std::vector<ASTUnit::RemappedFile> >
2643    RemappedFiles(new std::vector<ASTUnit::RemappedFile>());
2644
2645  // Recover resources if we crash before exiting this function.
2646  llvm::CrashRecoveryContextCleanupRegistrar<
2647    std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
2648
2649  for (unsigned I = 0; I != num_unsaved_files; ++I) {
2650    StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
2651    const llvm::MemoryBuffer *Buffer
2652      = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
2653    RemappedFiles->push_back(std::make_pair(unsaved_files[I].Filename,
2654                                            Buffer));
2655  }
2656
2657  if (!CXXUnit->Reparse(RemappedFiles->size() ? &(*RemappedFiles)[0] : 0,
2658                        RemappedFiles->size()))
2659    RTUI->result = 0;
2660}
2661
2662int clang_reparseTranslationUnit(CXTranslationUnit TU,
2663                                 unsigned num_unsaved_files,
2664                                 struct CXUnsavedFile *unsaved_files,
2665                                 unsigned options) {
2666  ReparseTranslationUnitInfo RTUI = { TU, num_unsaved_files, unsaved_files,
2667                                      options, 0 };
2668  llvm::CrashRecoveryContext CRC;
2669
2670  if (!RunSafely(CRC, clang_reparseTranslationUnit_Impl, &RTUI)) {
2671    fprintf(stderr, "libclang: crash detected during reparsing\n");
2672    static_cast<ASTUnit *>(TU->TUData)->setUnsafeToFree(true);
2673    return 1;
2674  } else if (getenv("LIBCLANG_RESOURCE_USAGE"))
2675    PrintLibclangResourceUsage(TU);
2676
2677  return RTUI.result;
2678}
2679
2680
2681CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
2682  if (!CTUnit)
2683    return createCXString("");
2684
2685  ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit->TUData);
2686  return createCXString(CXXUnit->getOriginalSourceFileName(), true);
2687}
2688
2689CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
2690  CXCursor Result = { CXCursor_TranslationUnit, 0, { 0, 0, TU } };
2691  return Result;
2692}
2693
2694} // end: extern "C"
2695
2696//===----------------------------------------------------------------------===//
2697// CXSourceLocation and CXSourceRange Operations.
2698//===----------------------------------------------------------------------===//
2699
2700extern "C" {
2701CXSourceLocation clang_getNullLocation() {
2702  CXSourceLocation Result = { { 0, 0 }, 0 };
2703  return Result;
2704}
2705
2706unsigned clang_equalLocations(CXSourceLocation loc1, CXSourceLocation loc2) {
2707  return (loc1.ptr_data[0] == loc2.ptr_data[0] &&
2708          loc1.ptr_data[1] == loc2.ptr_data[1] &&
2709          loc1.int_data == loc2.int_data);
2710}
2711
2712CXSourceLocation clang_getLocation(CXTranslationUnit tu,
2713                                   CXFile file,
2714                                   unsigned line,
2715                                   unsigned column) {
2716  if (!tu || !file)
2717    return clang_getNullLocation();
2718
2719  bool Logging = ::getenv("LIBCLANG_LOGGING");
2720  ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
2721  ASTUnit::ConcurrencyCheck Check(*CXXUnit);
2722  const FileEntry *File = static_cast<const FileEntry *>(file);
2723  SourceLocation SLoc = CXXUnit->getLocation(File, line, column);
2724  if (SLoc.isInvalid()) {
2725    if (Logging)
2726      llvm::errs() << "clang_getLocation(\"" << File->getName()
2727                   << "\", " << line << ", " << column << ") = invalid\n";
2728    return clang_getNullLocation();
2729  }
2730
2731  if (Logging)
2732    llvm::errs() << "clang_getLocation(\"" << File->getName()
2733                 << "\", " << line << ", " << column << ") = "
2734                 << SLoc.getRawEncoding() << "\n";
2735
2736  return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
2737}
2738
2739CXSourceLocation clang_getLocationForOffset(CXTranslationUnit tu,
2740                                            CXFile file,
2741                                            unsigned offset) {
2742  if (!tu || !file)
2743    return clang_getNullLocation();
2744
2745  ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
2746  SourceLocation SLoc
2747    = CXXUnit->getLocation(static_cast<const FileEntry *>(file), offset);
2748  if (SLoc.isInvalid()) return clang_getNullLocation();
2749
2750  return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
2751}
2752
2753CXSourceRange clang_getNullRange() {
2754  CXSourceRange Result = { { 0, 0 }, 0, 0 };
2755  return Result;
2756}
2757
2758CXSourceRange clang_getRange(CXSourceLocation begin, CXSourceLocation end) {
2759  if (begin.ptr_data[0] != end.ptr_data[0] ||
2760      begin.ptr_data[1] != end.ptr_data[1])
2761    return clang_getNullRange();
2762
2763  CXSourceRange Result = { { begin.ptr_data[0], begin.ptr_data[1] },
2764                           begin.int_data, end.int_data };
2765  return Result;
2766}
2767
2768unsigned clang_equalRanges(CXSourceRange range1, CXSourceRange range2)
2769{
2770  return range1.ptr_data[0] == range2.ptr_data[0]
2771      && range1.ptr_data[1] == range2.ptr_data[1]
2772      && range1.begin_int_data == range2.begin_int_data
2773      && range1.end_int_data == range2.end_int_data;
2774}
2775
2776int clang_Range_isNull(CXSourceRange range) {
2777  return clang_equalRanges(range, clang_getNullRange());
2778}
2779
2780} // end: extern "C"
2781
2782static void createNullLocation(CXFile *file, unsigned *line,
2783                               unsigned *column, unsigned *offset) {
2784  if (file)
2785   *file = 0;
2786  if (line)
2787   *line = 0;
2788  if (column)
2789   *column = 0;
2790  if (offset)
2791   *offset = 0;
2792  return;
2793}
2794
2795extern "C" {
2796void clang_getExpansionLocation(CXSourceLocation location,
2797                                CXFile *file,
2798                                unsigned *line,
2799                                unsigned *column,
2800                                unsigned *offset) {
2801  SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2802
2803  if (!location.ptr_data[0] || Loc.isInvalid()) {
2804    createNullLocation(file, line, column, offset);
2805    return;
2806  }
2807
2808  const SourceManager &SM =
2809    *static_cast<const SourceManager*>(location.ptr_data[0]);
2810  SourceLocation ExpansionLoc = SM.getExpansionLoc(Loc);
2811
2812  // Check that the FileID is invalid on the expansion location.
2813  // This can manifest in invalid code.
2814  FileID fileID = SM.getFileID(ExpansionLoc);
2815  bool Invalid = false;
2816  const SrcMgr::SLocEntry &sloc = SM.getSLocEntry(fileID, &Invalid);
2817  if (!sloc.isFile() || Invalid) {
2818    createNullLocation(file, line, column, offset);
2819    return;
2820  }
2821
2822  if (file)
2823    *file = (void *)SM.getFileEntryForSLocEntry(sloc);
2824  if (line)
2825    *line = SM.getExpansionLineNumber(ExpansionLoc);
2826  if (column)
2827    *column = SM.getExpansionColumnNumber(ExpansionLoc);
2828  if (offset)
2829    *offset = SM.getDecomposedLoc(ExpansionLoc).second;
2830}
2831
2832void clang_getPresumedLocation(CXSourceLocation location,
2833                               CXString *filename,
2834                               unsigned *line,
2835                               unsigned *column) {
2836  SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2837
2838  if (!location.ptr_data[0] || Loc.isInvalid()) {
2839    if (filename)
2840      *filename = createCXString("");
2841    if (line)
2842      *line = 0;
2843    if (column)
2844      *column = 0;
2845  }
2846  else {
2847	const SourceManager &SM =
2848        *static_cast<const SourceManager*>(location.ptr_data[0]);
2849    PresumedLoc PreLoc = SM.getPresumedLoc(Loc);
2850
2851    if (filename)
2852      *filename = createCXString(PreLoc.getFilename());
2853    if (line)
2854      *line = PreLoc.getLine();
2855    if (column)
2856      *column = PreLoc.getColumn();
2857  }
2858}
2859
2860void clang_getInstantiationLocation(CXSourceLocation location,
2861                                    CXFile *file,
2862                                    unsigned *line,
2863                                    unsigned *column,
2864                                    unsigned *offset) {
2865  // Redirect to new API.
2866  clang_getExpansionLocation(location, file, line, column, offset);
2867}
2868
2869void clang_getSpellingLocation(CXSourceLocation location,
2870                               CXFile *file,
2871                               unsigned *line,
2872                               unsigned *column,
2873                               unsigned *offset) {
2874  SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2875
2876  if (!location.ptr_data[0] || Loc.isInvalid())
2877    return createNullLocation(file, line, column, offset);
2878
2879  const SourceManager &SM =
2880    *static_cast<const SourceManager*>(location.ptr_data[0]);
2881  SourceLocation SpellLoc = Loc;
2882  if (SpellLoc.isMacroID()) {
2883    SourceLocation SimpleSpellingLoc = SM.getImmediateSpellingLoc(SpellLoc);
2884    if (SimpleSpellingLoc.isFileID() &&
2885        SM.getFileEntryForID(SM.getDecomposedLoc(SimpleSpellingLoc).first))
2886      SpellLoc = SimpleSpellingLoc;
2887    else
2888      SpellLoc = SM.getExpansionLoc(SpellLoc);
2889  }
2890
2891  std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(SpellLoc);
2892  FileID FID = LocInfo.first;
2893  unsigned FileOffset = LocInfo.second;
2894
2895  if (FID.isInvalid())
2896    return createNullLocation(file, line, column, offset);
2897
2898  if (file)
2899    *file = (void *)SM.getFileEntryForID(FID);
2900  if (line)
2901    *line = SM.getLineNumber(FID, FileOffset);
2902  if (column)
2903    *column = SM.getColumnNumber(FID, FileOffset);
2904  if (offset)
2905    *offset = FileOffset;
2906}
2907
2908CXSourceLocation clang_getRangeStart(CXSourceRange range) {
2909  CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
2910                              range.begin_int_data };
2911  return Result;
2912}
2913
2914CXSourceLocation clang_getRangeEnd(CXSourceRange range) {
2915  CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
2916                              range.end_int_data };
2917  return Result;
2918}
2919
2920} // end: extern "C"
2921
2922//===----------------------------------------------------------------------===//
2923// CXFile Operations.
2924//===----------------------------------------------------------------------===//
2925
2926extern "C" {
2927CXString clang_getFileName(CXFile SFile) {
2928  if (!SFile)
2929    return createCXString((const char*)NULL);
2930
2931  FileEntry *FEnt = static_cast<FileEntry *>(SFile);
2932  return createCXString(FEnt->getName());
2933}
2934
2935time_t clang_getFileTime(CXFile SFile) {
2936  if (!SFile)
2937    return 0;
2938
2939  FileEntry *FEnt = static_cast<FileEntry *>(SFile);
2940  return FEnt->getModificationTime();
2941}
2942
2943CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
2944  if (!tu)
2945    return 0;
2946
2947  ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
2948
2949  FileManager &FMgr = CXXUnit->getFileManager();
2950  return const_cast<FileEntry *>(FMgr.getFile(file_name));
2951}
2952
2953unsigned clang_isFileMultipleIncludeGuarded(CXTranslationUnit tu, CXFile file) {
2954  if (!tu || !file)
2955    return 0;
2956
2957  ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
2958  FileEntry *FEnt = static_cast<FileEntry *>(file);
2959  return CXXUnit->getPreprocessor().getHeaderSearchInfo()
2960                                          .isFileMultipleIncludeGuarded(FEnt);
2961}
2962
2963} // end: extern "C"
2964
2965//===----------------------------------------------------------------------===//
2966// CXCursor Operations.
2967//===----------------------------------------------------------------------===//
2968
2969static Decl *getDeclFromExpr(Stmt *E) {
2970  if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
2971    return getDeclFromExpr(CE->getSubExpr());
2972
2973  if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
2974    return RefExpr->getDecl();
2975  if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2976    return RefExpr->getDecl();
2977  if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
2978    return ME->getMemberDecl();
2979  if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
2980    return RE->getDecl();
2981  if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E))
2982    return PRE->isExplicitProperty() ? PRE->getExplicitProperty() : 0;
2983
2984  if (CallExpr *CE = dyn_cast<CallExpr>(E))
2985    return getDeclFromExpr(CE->getCallee());
2986  if (CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(E))
2987    if (!CE->isElidable())
2988    return CE->getConstructor();
2989  if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
2990    return OME->getMethodDecl();
2991
2992  if (ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
2993    return PE->getProtocol();
2994  if (SubstNonTypeTemplateParmPackExpr *NTTP
2995                              = dyn_cast<SubstNonTypeTemplateParmPackExpr>(E))
2996    return NTTP->getParameterPack();
2997  if (SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
2998    if (isa<NonTypeTemplateParmDecl>(SizeOfPack->getPack()) ||
2999        isa<ParmVarDecl>(SizeOfPack->getPack()))
3000      return SizeOfPack->getPack();
3001
3002  return 0;
3003}
3004
3005static SourceLocation getLocationFromExpr(Expr *E) {
3006  if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
3007    return getLocationFromExpr(CE->getSubExpr());
3008
3009  if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
3010    return /*FIXME:*/Msg->getLeftLoc();
3011  if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
3012    return DRE->getLocation();
3013  if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
3014    return RefExpr->getLocation();
3015  if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
3016    return Member->getMemberLoc();
3017  if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
3018    return Ivar->getLocation();
3019  if (SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
3020    return SizeOfPack->getPackLoc();
3021
3022  return E->getLocStart();
3023}
3024
3025extern "C" {
3026
3027unsigned clang_visitChildren(CXCursor parent,
3028                             CXCursorVisitor visitor,
3029                             CXClientData client_data) {
3030  CursorVisitor CursorVis(getCursorTU(parent), visitor, client_data,
3031                          false);
3032  return CursorVis.VisitChildren(parent);
3033}
3034
3035#ifndef __has_feature
3036#define __has_feature(x) 0
3037#endif
3038#if __has_feature(blocks)
3039typedef enum CXChildVisitResult
3040     (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent);
3041
3042static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
3043    CXClientData client_data) {
3044  CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
3045  return block(cursor, parent);
3046}
3047#else
3048// If we are compiled with a compiler that doesn't have native blocks support,
3049// define and call the block manually, so the
3050typedef struct _CXChildVisitResult
3051{
3052	void *isa;
3053	int flags;
3054	int reserved;
3055	enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor,
3056                                         CXCursor);
3057} *CXCursorVisitorBlock;
3058
3059static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
3060    CXClientData client_data) {
3061  CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
3062  return block->invoke(block, cursor, parent);
3063}
3064#endif
3065
3066
3067unsigned clang_visitChildrenWithBlock(CXCursor parent,
3068                                      CXCursorVisitorBlock block) {
3069  return clang_visitChildren(parent, visitWithBlock, block);
3070}
3071
3072static CXString getDeclSpelling(Decl *D) {
3073  NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
3074  if (!ND) {
3075    if (ObjCPropertyImplDecl *PropImpl =dyn_cast<ObjCPropertyImplDecl>(D))
3076      if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
3077        return createCXString(Property->getIdentifier()->getName());
3078
3079    return createCXString("");
3080  }
3081
3082  if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
3083    return createCXString(OMD->getSelector().getAsString());
3084
3085  if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
3086    // No, this isn't the same as the code below. getIdentifier() is non-virtual
3087    // and returns different names. NamedDecl returns the class name and
3088    // ObjCCategoryImplDecl returns the category name.
3089    return createCXString(CIMP->getIdentifier()->getNameStart());
3090
3091  if (isa<UsingDirectiveDecl>(D))
3092    return createCXString("");
3093
3094  llvm::SmallString<1024> S;
3095  llvm::raw_svector_ostream os(S);
3096  ND->printName(os);
3097
3098  return createCXString(os.str());
3099}
3100
3101CXString clang_getCursorSpelling(CXCursor C) {
3102  if (clang_isTranslationUnit(C.kind))
3103    return clang_getTranslationUnitSpelling(
3104                            static_cast<CXTranslationUnit>(C.data[2]));
3105
3106  if (clang_isReference(C.kind)) {
3107    switch (C.kind) {
3108    case CXCursor_ObjCSuperClassRef: {
3109      ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
3110      return createCXString(Super->getIdentifier()->getNameStart());
3111    }
3112    case CXCursor_ObjCClassRef: {
3113      ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
3114      return createCXString(Class->getIdentifier()->getNameStart());
3115    }
3116    case CXCursor_ObjCProtocolRef: {
3117      ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
3118      assert(OID && "getCursorSpelling(): Missing protocol decl");
3119      return createCXString(OID->getIdentifier()->getNameStart());
3120    }
3121    case CXCursor_CXXBaseSpecifier: {
3122      CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
3123      return createCXString(B->getType().getAsString());
3124    }
3125    case CXCursor_TypeRef: {
3126      TypeDecl *Type = getCursorTypeRef(C).first;
3127      assert(Type && "Missing type decl");
3128
3129      return createCXString(getCursorContext(C).getTypeDeclType(Type).
3130                              getAsString());
3131    }
3132    case CXCursor_TemplateRef: {
3133      TemplateDecl *Template = getCursorTemplateRef(C).first;
3134      assert(Template && "Missing template decl");
3135
3136      return createCXString(Template->getNameAsString());
3137    }
3138
3139    case CXCursor_NamespaceRef: {
3140      NamedDecl *NS = getCursorNamespaceRef(C).first;
3141      assert(NS && "Missing namespace decl");
3142
3143      return createCXString(NS->getNameAsString());
3144    }
3145
3146    case CXCursor_MemberRef: {
3147      FieldDecl *Field = getCursorMemberRef(C).first;
3148      assert(Field && "Missing member decl");
3149
3150      return createCXString(Field->getNameAsString());
3151    }
3152
3153    case CXCursor_LabelRef: {
3154      LabelStmt *Label = getCursorLabelRef(C).first;
3155      assert(Label && "Missing label");
3156
3157      return createCXString(Label->getName());
3158    }
3159
3160    case CXCursor_OverloadedDeclRef: {
3161      OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
3162      if (Decl *D = Storage.dyn_cast<Decl *>()) {
3163        if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
3164          return createCXString(ND->getNameAsString());
3165        return createCXString("");
3166      }
3167      if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
3168        return createCXString(E->getName().getAsString());
3169      OverloadedTemplateStorage *Ovl
3170        = Storage.get<OverloadedTemplateStorage*>();
3171      if (Ovl->size() == 0)
3172        return createCXString("");
3173      return createCXString((*Ovl->begin())->getNameAsString());
3174    }
3175
3176    default:
3177      return createCXString("<not implemented>");
3178    }
3179  }
3180
3181  if (clang_isExpression(C.kind)) {
3182    Decl *D = getDeclFromExpr(getCursorExpr(C));
3183    if (D)
3184      return getDeclSpelling(D);
3185    return createCXString("");
3186  }
3187
3188  if (clang_isStatement(C.kind)) {
3189    Stmt *S = getCursorStmt(C);
3190    if (LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
3191      return createCXString(Label->getName());
3192
3193    return createCXString("");
3194  }
3195
3196  if (C.kind == CXCursor_MacroExpansion)
3197    return createCXString(getCursorMacroExpansion(C)->getName()
3198                                                           ->getNameStart());
3199
3200  if (C.kind == CXCursor_MacroDefinition)
3201    return createCXString(getCursorMacroDefinition(C)->getName()
3202                                                           ->getNameStart());
3203
3204  if (C.kind == CXCursor_InclusionDirective)
3205    return createCXString(getCursorInclusionDirective(C)->getFileName());
3206
3207  if (clang_isDeclaration(C.kind))
3208    return getDeclSpelling(getCursorDecl(C));
3209
3210  if (C.kind == CXCursor_AnnotateAttr) {
3211    AnnotateAttr *AA = cast<AnnotateAttr>(cxcursor::getCursorAttr(C));
3212    return createCXString(AA->getAnnotation());
3213  }
3214
3215  return createCXString("");
3216}
3217
3218CXString clang_getCursorDisplayName(CXCursor C) {
3219  if (!clang_isDeclaration(C.kind))
3220    return clang_getCursorSpelling(C);
3221
3222  Decl *D = getCursorDecl(C);
3223  if (!D)
3224    return createCXString("");
3225
3226  PrintingPolicy Policy = getCursorContext(C).getPrintingPolicy();
3227  if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
3228    D = FunTmpl->getTemplatedDecl();
3229
3230  if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
3231    llvm::SmallString<64> Str;
3232    llvm::raw_svector_ostream OS(Str);
3233    OS << Function->getNameAsString();
3234    if (Function->getPrimaryTemplate())
3235      OS << "<>";
3236    OS << "(";
3237    for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
3238      if (I)
3239        OS << ", ";
3240      OS << Function->getParamDecl(I)->getType().getAsString(Policy);
3241    }
3242
3243    if (Function->isVariadic()) {
3244      if (Function->getNumParams())
3245        OS << ", ";
3246      OS << "...";
3247    }
3248    OS << ")";
3249    return createCXString(OS.str());
3250  }
3251
3252  if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
3253    llvm::SmallString<64> Str;
3254    llvm::raw_svector_ostream OS(Str);
3255    OS << ClassTemplate->getNameAsString();
3256    OS << "<";
3257    TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
3258    for (unsigned I = 0, N = Params->size(); I != N; ++I) {
3259      if (I)
3260        OS << ", ";
3261
3262      NamedDecl *Param = Params->getParam(I);
3263      if (Param->getIdentifier()) {
3264        OS << Param->getIdentifier()->getName();
3265        continue;
3266      }
3267
3268      // There is no parameter name, which makes this tricky. Try to come up
3269      // with something useful that isn't too long.
3270      if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
3271        OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
3272      else if (NonTypeTemplateParmDecl *NTTP
3273                                    = dyn_cast<NonTypeTemplateParmDecl>(Param))
3274        OS << NTTP->getType().getAsString(Policy);
3275      else
3276        OS << "template<...> class";
3277    }
3278
3279    OS << ">";
3280    return createCXString(OS.str());
3281  }
3282
3283  if (ClassTemplateSpecializationDecl *ClassSpec
3284                              = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
3285    // If the type was explicitly written, use that.
3286    if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
3287      return createCXString(TSInfo->getType().getAsString(Policy));
3288
3289    llvm::SmallString<64> Str;
3290    llvm::raw_svector_ostream OS(Str);
3291    OS << ClassSpec->getNameAsString();
3292    OS << TemplateSpecializationType::PrintTemplateArgumentList(
3293                                      ClassSpec->getTemplateArgs().data(),
3294                                      ClassSpec->getTemplateArgs().size(),
3295                                                                Policy);
3296    return createCXString(OS.str());
3297  }
3298
3299  return clang_getCursorSpelling(C);
3300}
3301
3302CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
3303  switch (Kind) {
3304  case CXCursor_FunctionDecl:
3305      return createCXString("FunctionDecl");
3306  case CXCursor_TypedefDecl:
3307      return createCXString("TypedefDecl");
3308  case CXCursor_EnumDecl:
3309      return createCXString("EnumDecl");
3310  case CXCursor_EnumConstantDecl:
3311      return createCXString("EnumConstantDecl");
3312  case CXCursor_StructDecl:
3313      return createCXString("StructDecl");
3314  case CXCursor_UnionDecl:
3315      return createCXString("UnionDecl");
3316  case CXCursor_ClassDecl:
3317      return createCXString("ClassDecl");
3318  case CXCursor_FieldDecl:
3319      return createCXString("FieldDecl");
3320  case CXCursor_VarDecl:
3321      return createCXString("VarDecl");
3322  case CXCursor_ParmDecl:
3323      return createCXString("ParmDecl");
3324  case CXCursor_ObjCInterfaceDecl:
3325      return createCXString("ObjCInterfaceDecl");
3326  case CXCursor_ObjCCategoryDecl:
3327      return createCXString("ObjCCategoryDecl");
3328  case CXCursor_ObjCProtocolDecl:
3329      return createCXString("ObjCProtocolDecl");
3330  case CXCursor_ObjCPropertyDecl:
3331      return createCXString("ObjCPropertyDecl");
3332  case CXCursor_ObjCIvarDecl:
3333      return createCXString("ObjCIvarDecl");
3334  case CXCursor_ObjCInstanceMethodDecl:
3335      return createCXString("ObjCInstanceMethodDecl");
3336  case CXCursor_ObjCClassMethodDecl:
3337      return createCXString("ObjCClassMethodDecl");
3338  case CXCursor_ObjCImplementationDecl:
3339      return createCXString("ObjCImplementationDecl");
3340  case CXCursor_ObjCCategoryImplDecl:
3341      return createCXString("ObjCCategoryImplDecl");
3342  case CXCursor_CXXMethod:
3343      return createCXString("CXXMethod");
3344  case CXCursor_UnexposedDecl:
3345      return createCXString("UnexposedDecl");
3346  case CXCursor_ObjCSuperClassRef:
3347      return createCXString("ObjCSuperClassRef");
3348  case CXCursor_ObjCProtocolRef:
3349      return createCXString("ObjCProtocolRef");
3350  case CXCursor_ObjCClassRef:
3351      return createCXString("ObjCClassRef");
3352  case CXCursor_TypeRef:
3353      return createCXString("TypeRef");
3354  case CXCursor_TemplateRef:
3355      return createCXString("TemplateRef");
3356  case CXCursor_NamespaceRef:
3357    return createCXString("NamespaceRef");
3358  case CXCursor_MemberRef:
3359    return createCXString("MemberRef");
3360  case CXCursor_LabelRef:
3361    return createCXString("LabelRef");
3362  case CXCursor_OverloadedDeclRef:
3363    return createCXString("OverloadedDeclRef");
3364  case CXCursor_IntegerLiteral:
3365      return createCXString("IntegerLiteral");
3366  case CXCursor_FloatingLiteral:
3367      return createCXString("FloatingLiteral");
3368  case CXCursor_ImaginaryLiteral:
3369      return createCXString("ImaginaryLiteral");
3370  case CXCursor_StringLiteral:
3371      return createCXString("StringLiteral");
3372  case CXCursor_CharacterLiteral:
3373      return createCXString("CharacterLiteral");
3374  case CXCursor_ParenExpr:
3375      return createCXString("ParenExpr");
3376  case CXCursor_UnaryOperator:
3377      return createCXString("UnaryOperator");
3378  case CXCursor_ArraySubscriptExpr:
3379      return createCXString("ArraySubscriptExpr");
3380  case CXCursor_BinaryOperator:
3381      return createCXString("BinaryOperator");
3382  case CXCursor_CompoundAssignOperator:
3383      return createCXString("CompoundAssignOperator");
3384  case CXCursor_ConditionalOperator:
3385      return createCXString("ConditionalOperator");
3386  case CXCursor_CStyleCastExpr:
3387      return createCXString("CStyleCastExpr");
3388  case CXCursor_CompoundLiteralExpr:
3389      return createCXString("CompoundLiteralExpr");
3390  case CXCursor_InitListExpr:
3391      return createCXString("InitListExpr");
3392  case CXCursor_AddrLabelExpr:
3393      return createCXString("AddrLabelExpr");
3394  case CXCursor_StmtExpr:
3395      return createCXString("StmtExpr");
3396  case CXCursor_GenericSelectionExpr:
3397      return createCXString("GenericSelectionExpr");
3398  case CXCursor_GNUNullExpr:
3399      return createCXString("GNUNullExpr");
3400  case CXCursor_CXXStaticCastExpr:
3401      return createCXString("CXXStaticCastExpr");
3402  case CXCursor_CXXDynamicCastExpr:
3403      return createCXString("CXXDynamicCastExpr");
3404  case CXCursor_CXXReinterpretCastExpr:
3405      return createCXString("CXXReinterpretCastExpr");
3406  case CXCursor_CXXConstCastExpr:
3407      return createCXString("CXXConstCastExpr");
3408  case CXCursor_CXXFunctionalCastExpr:
3409      return createCXString("CXXFunctionalCastExpr");
3410  case CXCursor_CXXTypeidExpr:
3411      return createCXString("CXXTypeidExpr");
3412  case CXCursor_CXXBoolLiteralExpr:
3413      return createCXString("CXXBoolLiteralExpr");
3414  case CXCursor_CXXNullPtrLiteralExpr:
3415      return createCXString("CXXNullPtrLiteralExpr");
3416  case CXCursor_CXXThisExpr:
3417      return createCXString("CXXThisExpr");
3418  case CXCursor_CXXThrowExpr:
3419      return createCXString("CXXThrowExpr");
3420  case CXCursor_CXXNewExpr:
3421      return createCXString("CXXNewExpr");
3422  case CXCursor_CXXDeleteExpr:
3423      return createCXString("CXXDeleteExpr");
3424  case CXCursor_UnaryExpr:
3425      return createCXString("UnaryExpr");
3426  case CXCursor_ObjCStringLiteral:
3427      return createCXString("ObjCStringLiteral");
3428  case CXCursor_ObjCEncodeExpr:
3429      return createCXString("ObjCEncodeExpr");
3430  case CXCursor_ObjCSelectorExpr:
3431      return createCXString("ObjCSelectorExpr");
3432  case CXCursor_ObjCProtocolExpr:
3433      return createCXString("ObjCProtocolExpr");
3434  case CXCursor_ObjCBridgedCastExpr:
3435      return createCXString("ObjCBridgedCastExpr");
3436  case CXCursor_BlockExpr:
3437      return createCXString("BlockExpr");
3438  case CXCursor_PackExpansionExpr:
3439      return createCXString("PackExpansionExpr");
3440  case CXCursor_SizeOfPackExpr:
3441      return createCXString("SizeOfPackExpr");
3442  case CXCursor_UnexposedExpr:
3443      return createCXString("UnexposedExpr");
3444  case CXCursor_DeclRefExpr:
3445      return createCXString("DeclRefExpr");
3446  case CXCursor_MemberRefExpr:
3447      return createCXString("MemberRefExpr");
3448  case CXCursor_CallExpr:
3449      return createCXString("CallExpr");
3450  case CXCursor_ObjCMessageExpr:
3451      return createCXString("ObjCMessageExpr");
3452  case CXCursor_UnexposedStmt:
3453      return createCXString("UnexposedStmt");
3454  case CXCursor_DeclStmt:
3455      return createCXString("DeclStmt");
3456  case CXCursor_LabelStmt:
3457      return createCXString("LabelStmt");
3458  case CXCursor_CompoundStmt:
3459      return createCXString("CompoundStmt");
3460  case CXCursor_CaseStmt:
3461      return createCXString("CaseStmt");
3462  case CXCursor_DefaultStmt:
3463      return createCXString("DefaultStmt");
3464  case CXCursor_IfStmt:
3465      return createCXString("IfStmt");
3466  case CXCursor_SwitchStmt:
3467      return createCXString("SwitchStmt");
3468  case CXCursor_WhileStmt:
3469      return createCXString("WhileStmt");
3470  case CXCursor_DoStmt:
3471      return createCXString("DoStmt");
3472  case CXCursor_ForStmt:
3473      return createCXString("ForStmt");
3474  case CXCursor_GotoStmt:
3475      return createCXString("GotoStmt");
3476  case CXCursor_IndirectGotoStmt:
3477      return createCXString("IndirectGotoStmt");
3478  case CXCursor_ContinueStmt:
3479      return createCXString("ContinueStmt");
3480  case CXCursor_BreakStmt:
3481      return createCXString("BreakStmt");
3482  case CXCursor_ReturnStmt:
3483      return createCXString("ReturnStmt");
3484  case CXCursor_AsmStmt:
3485      return createCXString("AsmStmt");
3486  case CXCursor_ObjCAtTryStmt:
3487      return createCXString("ObjCAtTryStmt");
3488  case CXCursor_ObjCAtCatchStmt:
3489      return createCXString("ObjCAtCatchStmt");
3490  case CXCursor_ObjCAtFinallyStmt:
3491      return createCXString("ObjCAtFinallyStmt");
3492  case CXCursor_ObjCAtThrowStmt:
3493      return createCXString("ObjCAtThrowStmt");
3494  case CXCursor_ObjCAtSynchronizedStmt:
3495      return createCXString("ObjCAtSynchronizedStmt");
3496  case CXCursor_ObjCAutoreleasePoolStmt:
3497      return createCXString("ObjCAutoreleasePoolStmt");
3498  case CXCursor_ObjCForCollectionStmt:
3499      return createCXString("ObjCForCollectionStmt");
3500  case CXCursor_CXXCatchStmt:
3501      return createCXString("CXXCatchStmt");
3502  case CXCursor_CXXTryStmt:
3503      return createCXString("CXXTryStmt");
3504  case CXCursor_CXXForRangeStmt:
3505      return createCXString("CXXForRangeStmt");
3506  case CXCursor_SEHTryStmt:
3507      return createCXString("SEHTryStmt");
3508  case CXCursor_SEHExceptStmt:
3509      return createCXString("SEHExceptStmt");
3510  case CXCursor_SEHFinallyStmt:
3511      return createCXString("SEHFinallyStmt");
3512  case CXCursor_NullStmt:
3513      return createCXString("NullStmt");
3514  case CXCursor_InvalidFile:
3515      return createCXString("InvalidFile");
3516  case CXCursor_InvalidCode:
3517    return createCXString("InvalidCode");
3518  case CXCursor_NoDeclFound:
3519      return createCXString("NoDeclFound");
3520  case CXCursor_NotImplemented:
3521      return createCXString("NotImplemented");
3522  case CXCursor_TranslationUnit:
3523      return createCXString("TranslationUnit");
3524  case CXCursor_UnexposedAttr:
3525      return createCXString("UnexposedAttr");
3526  case CXCursor_IBActionAttr:
3527      return createCXString("attribute(ibaction)");
3528  case CXCursor_IBOutletAttr:
3529     return createCXString("attribute(iboutlet)");
3530  case CXCursor_IBOutletCollectionAttr:
3531      return createCXString("attribute(iboutletcollection)");
3532  case CXCursor_CXXFinalAttr:
3533      return createCXString("attribute(final)");
3534  case CXCursor_CXXOverrideAttr:
3535      return createCXString("attribute(override)");
3536  case CXCursor_AnnotateAttr:
3537    return createCXString("attribute(annotate)");
3538  case CXCursor_PreprocessingDirective:
3539    return createCXString("preprocessing directive");
3540  case CXCursor_MacroDefinition:
3541    return createCXString("macro definition");
3542  case CXCursor_MacroExpansion:
3543    return createCXString("macro expansion");
3544  case CXCursor_InclusionDirective:
3545    return createCXString("inclusion directive");
3546  case CXCursor_Namespace:
3547    return createCXString("Namespace");
3548  case CXCursor_LinkageSpec:
3549    return createCXString("LinkageSpec");
3550  case CXCursor_CXXBaseSpecifier:
3551    return createCXString("C++ base class specifier");
3552  case CXCursor_Constructor:
3553    return createCXString("CXXConstructor");
3554  case CXCursor_Destructor:
3555    return createCXString("CXXDestructor");
3556  case CXCursor_ConversionFunction:
3557    return createCXString("CXXConversion");
3558  case CXCursor_TemplateTypeParameter:
3559    return createCXString("TemplateTypeParameter");
3560  case CXCursor_NonTypeTemplateParameter:
3561    return createCXString("NonTypeTemplateParameter");
3562  case CXCursor_TemplateTemplateParameter:
3563    return createCXString("TemplateTemplateParameter");
3564  case CXCursor_FunctionTemplate:
3565    return createCXString("FunctionTemplate");
3566  case CXCursor_ClassTemplate:
3567    return createCXString("ClassTemplate");
3568  case CXCursor_ClassTemplatePartialSpecialization:
3569    return createCXString("ClassTemplatePartialSpecialization");
3570  case CXCursor_NamespaceAlias:
3571    return createCXString("NamespaceAlias");
3572  case CXCursor_UsingDirective:
3573    return createCXString("UsingDirective");
3574  case CXCursor_UsingDeclaration:
3575    return createCXString("UsingDeclaration");
3576  case CXCursor_TypeAliasDecl:
3577    return createCXString("TypeAliasDecl");
3578  case CXCursor_ObjCSynthesizeDecl:
3579    return createCXString("ObjCSynthesizeDecl");
3580  case CXCursor_ObjCDynamicDecl:
3581    return createCXString("ObjCDynamicDecl");
3582  case CXCursor_CXXAccessSpecifier:
3583    return createCXString("CXXAccessSpecifier");
3584  }
3585
3586  llvm_unreachable("Unhandled CXCursorKind");
3587  return createCXString((const char*) 0);
3588}
3589
3590struct GetCursorData {
3591  SourceLocation TokenBeginLoc;
3592  bool PointsAtMacroArgExpansion;
3593  CXCursor &BestCursor;
3594
3595  GetCursorData(SourceManager &SM,
3596                SourceLocation tokenBegin, CXCursor &outputCursor)
3597    : TokenBeginLoc(tokenBegin), BestCursor(outputCursor) {
3598    PointsAtMacroArgExpansion = SM.isMacroArgExpansion(tokenBegin);
3599  }
3600};
3601
3602static enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
3603                                                CXCursor parent,
3604                                                CXClientData client_data) {
3605  GetCursorData *Data = static_cast<GetCursorData *>(client_data);
3606  CXCursor *BestCursor = &Data->BestCursor;
3607
3608  // If we point inside a macro argument we should provide info of what the
3609  // token is so use the actual cursor, don't replace it with a macro expansion
3610  // cursor.
3611  if (cursor.kind == CXCursor_MacroExpansion && Data->PointsAtMacroArgExpansion)
3612    return CXChildVisit_Recurse;
3613
3614  if (clang_isDeclaration(cursor.kind)) {
3615    // Avoid having the implicit methods override the property decls.
3616    if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(getCursorDecl(cursor)))
3617      if (MD->isImplicit())
3618        return CXChildVisit_Break;
3619  }
3620
3621  if (clang_isExpression(cursor.kind) &&
3622      clang_isDeclaration(BestCursor->kind)) {
3623    Decl *D = getCursorDecl(*BestCursor);
3624
3625    // Avoid having the cursor of an expression replace the declaration cursor
3626    // when the expression source range overlaps the declaration range.
3627    // This can happen for C++ constructor expressions whose range generally
3628    // include the variable declaration, e.g.:
3629    //  MyCXXClass foo; // Make sure pointing at 'foo' returns a VarDecl cursor.
3630    if (D->getLocation().isValid() && Data->TokenBeginLoc.isValid() &&
3631        D->getLocation() == Data->TokenBeginLoc)
3632      return CXChildVisit_Break;
3633  }
3634
3635  // If our current best cursor is the construction of a temporary object,
3636  // don't replace that cursor with a type reference, because we want
3637  // clang_getCursor() to point at the constructor.
3638  if (clang_isExpression(BestCursor->kind) &&
3639      isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
3640      cursor.kind == CXCursor_TypeRef) {
3641    // Keep the cursor pointing at CXXTemporaryObjectExpr but also mark it
3642    // as having the actual point on the type reference.
3643    *BestCursor = getTypeRefedCallExprCursor(*BestCursor);
3644    return CXChildVisit_Recurse;
3645  }
3646
3647  *BestCursor = cursor;
3648  return CXChildVisit_Recurse;
3649}
3650
3651CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
3652  if (!TU)
3653    return clang_getNullCursor();
3654
3655  ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
3656  ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3657
3658  SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
3659  CXCursor Result = cxcursor::getCursor(TU, SLoc);
3660
3661  bool Logging = getenv("LIBCLANG_LOGGING");
3662  if (Logging) {
3663    CXFile SearchFile;
3664    unsigned SearchLine, SearchColumn;
3665    CXFile ResultFile;
3666    unsigned ResultLine, ResultColumn;
3667    CXString SearchFileName, ResultFileName, KindSpelling, USR;
3668    const char *IsDef = clang_isCursorDefinition(Result)? " (Definition)" : "";
3669    CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
3670
3671    clang_getExpansionLocation(Loc, &SearchFile, &SearchLine, &SearchColumn, 0);
3672    clang_getExpansionLocation(ResultLoc, &ResultFile, &ResultLine,
3673                               &ResultColumn, 0);
3674    SearchFileName = clang_getFileName(SearchFile);
3675    ResultFileName = clang_getFileName(ResultFile);
3676    KindSpelling = clang_getCursorKindSpelling(Result.kind);
3677    USR = clang_getCursorUSR(Result);
3678    fprintf(stderr, "clang_getCursor(%s:%d:%d) = %s(%s:%d:%d):%s%s\n",
3679            clang_getCString(SearchFileName), SearchLine, SearchColumn,
3680            clang_getCString(KindSpelling),
3681            clang_getCString(ResultFileName), ResultLine, ResultColumn,
3682            clang_getCString(USR), IsDef);
3683    clang_disposeString(SearchFileName);
3684    clang_disposeString(ResultFileName);
3685    clang_disposeString(KindSpelling);
3686    clang_disposeString(USR);
3687
3688    CXCursor Definition = clang_getCursorDefinition(Result);
3689    if (!clang_equalCursors(Definition, clang_getNullCursor())) {
3690      CXSourceLocation DefinitionLoc = clang_getCursorLocation(Definition);
3691      CXString DefinitionKindSpelling
3692                                = clang_getCursorKindSpelling(Definition.kind);
3693      CXFile DefinitionFile;
3694      unsigned DefinitionLine, DefinitionColumn;
3695      clang_getExpansionLocation(DefinitionLoc, &DefinitionFile,
3696                                 &DefinitionLine, &DefinitionColumn, 0);
3697      CXString DefinitionFileName = clang_getFileName(DefinitionFile);
3698      fprintf(stderr, "  -> %s(%s:%d:%d)\n",
3699              clang_getCString(DefinitionKindSpelling),
3700              clang_getCString(DefinitionFileName),
3701              DefinitionLine, DefinitionColumn);
3702      clang_disposeString(DefinitionFileName);
3703      clang_disposeString(DefinitionKindSpelling);
3704    }
3705  }
3706
3707  return Result;
3708}
3709
3710CXCursor clang_getNullCursor(void) {
3711  return MakeCXCursorInvalid(CXCursor_InvalidFile);
3712}
3713
3714unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
3715  return X == Y;
3716}
3717
3718unsigned clang_hashCursor(CXCursor C) {
3719  unsigned Index = 0;
3720  if (clang_isExpression(C.kind) || clang_isStatement(C.kind))
3721    Index = 1;
3722
3723  return llvm::DenseMapInfo<std::pair<unsigned, void*> >::getHashValue(
3724                                        std::make_pair(C.kind, C.data[Index]));
3725}
3726
3727unsigned clang_isInvalid(enum CXCursorKind K) {
3728  return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
3729}
3730
3731unsigned clang_isDeclaration(enum CXCursorKind K) {
3732  return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
3733}
3734
3735unsigned clang_isReference(enum CXCursorKind K) {
3736  return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
3737}
3738
3739unsigned clang_isExpression(enum CXCursorKind K) {
3740  return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
3741}
3742
3743unsigned clang_isStatement(enum CXCursorKind K) {
3744  return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
3745}
3746
3747unsigned clang_isAttribute(enum CXCursorKind K) {
3748    return K >= CXCursor_FirstAttr && K <= CXCursor_LastAttr;
3749}
3750
3751unsigned clang_isTranslationUnit(enum CXCursorKind K) {
3752  return K == CXCursor_TranslationUnit;
3753}
3754
3755unsigned clang_isPreprocessing(enum CXCursorKind K) {
3756  return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
3757}
3758
3759unsigned clang_isUnexposed(enum CXCursorKind K) {
3760  switch (K) {
3761    case CXCursor_UnexposedDecl:
3762    case CXCursor_UnexposedExpr:
3763    case CXCursor_UnexposedStmt:
3764    case CXCursor_UnexposedAttr:
3765      return true;
3766    default:
3767      return false;
3768  }
3769}
3770
3771CXCursorKind clang_getCursorKind(CXCursor C) {
3772  return C.kind;
3773}
3774
3775CXSourceLocation clang_getCursorLocation(CXCursor C) {
3776  if (clang_isReference(C.kind)) {
3777    switch (C.kind) {
3778    case CXCursor_ObjCSuperClassRef: {
3779      std::pair<ObjCInterfaceDecl *, SourceLocation> P
3780        = getCursorObjCSuperClassRef(C);
3781      return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3782    }
3783
3784    case CXCursor_ObjCProtocolRef: {
3785      std::pair<ObjCProtocolDecl *, SourceLocation> P
3786        = getCursorObjCProtocolRef(C);
3787      return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3788    }
3789
3790    case CXCursor_ObjCClassRef: {
3791      std::pair<ObjCInterfaceDecl *, SourceLocation> P
3792        = getCursorObjCClassRef(C);
3793      return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3794    }
3795
3796    case CXCursor_TypeRef: {
3797      std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
3798      return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3799    }
3800
3801    case CXCursor_TemplateRef: {
3802      std::pair<TemplateDecl *, SourceLocation> P = getCursorTemplateRef(C);
3803      return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3804    }
3805
3806    case CXCursor_NamespaceRef: {
3807      std::pair<NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
3808      return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3809    }
3810
3811    case CXCursor_MemberRef: {
3812      std::pair<FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
3813      return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3814    }
3815
3816    case CXCursor_CXXBaseSpecifier: {
3817      CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
3818      if (!BaseSpec)
3819        return clang_getNullLocation();
3820
3821      if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
3822        return cxloc::translateSourceLocation(getCursorContext(C),
3823                                            TSInfo->getTypeLoc().getBeginLoc());
3824
3825      return cxloc::translateSourceLocation(getCursorContext(C),
3826                                        BaseSpec->getSourceRange().getBegin());
3827    }
3828
3829    case CXCursor_LabelRef: {
3830      std::pair<LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
3831      return cxloc::translateSourceLocation(getCursorContext(C), P.second);
3832    }
3833
3834    case CXCursor_OverloadedDeclRef:
3835      return cxloc::translateSourceLocation(getCursorContext(C),
3836                                          getCursorOverloadedDeclRef(C).second);
3837
3838    default:
3839      // FIXME: Need a way to enumerate all non-reference cases.
3840      llvm_unreachable("Missed a reference kind");
3841    }
3842  }
3843
3844  if (clang_isExpression(C.kind))
3845    return cxloc::translateSourceLocation(getCursorContext(C),
3846                                   getLocationFromExpr(getCursorExpr(C)));
3847
3848  if (clang_isStatement(C.kind))
3849    return cxloc::translateSourceLocation(getCursorContext(C),
3850                                          getCursorStmt(C)->getLocStart());
3851
3852  if (C.kind == CXCursor_PreprocessingDirective) {
3853    SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
3854    return cxloc::translateSourceLocation(getCursorContext(C), L);
3855  }
3856
3857  if (C.kind == CXCursor_MacroExpansion) {
3858    SourceLocation L
3859      = cxcursor::getCursorMacroExpansion(C)->getSourceRange().getBegin();
3860    return cxloc::translateSourceLocation(getCursorContext(C), L);
3861  }
3862
3863  if (C.kind == CXCursor_MacroDefinition) {
3864    SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
3865    return cxloc::translateSourceLocation(getCursorContext(C), L);
3866  }
3867
3868  if (C.kind == CXCursor_InclusionDirective) {
3869    SourceLocation L
3870      = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
3871    return cxloc::translateSourceLocation(getCursorContext(C), L);
3872  }
3873
3874  if (C.kind < CXCursor_FirstDecl || C.kind > CXCursor_LastDecl)
3875    return clang_getNullLocation();
3876
3877  Decl *D = getCursorDecl(C);
3878  SourceLocation Loc = D->getLocation();
3879  // FIXME: Multiple variables declared in a single declaration
3880  // currently lack the information needed to correctly determine their
3881  // ranges when accounting for the type-specifier.  We use context
3882  // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3883  // and if so, whether it is the first decl.
3884  if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3885    if (!cxcursor::isFirstInDeclGroup(C))
3886      Loc = VD->getLocation();
3887  }
3888
3889  return cxloc::translateSourceLocation(getCursorContext(C), Loc);
3890}
3891
3892} // end extern "C"
3893
3894CXCursor cxcursor::getCursor(CXTranslationUnit TU, SourceLocation SLoc) {
3895  assert(TU);
3896
3897  // Guard against an invalid SourceLocation, or we may assert in one
3898  // of the following calls.
3899  if (SLoc.isInvalid())
3900    return clang_getNullCursor();
3901
3902  ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
3903
3904  // Translate the given source location to make it point at the beginning of
3905  // the token under the cursor.
3906  SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
3907                                    CXXUnit->getASTContext().getLangOptions());
3908
3909  CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
3910  if (SLoc.isValid()) {
3911    // FIXME: Would be great to have a "hint" cursor, then walk from that
3912    // hint cursor upward until we find a cursor whose source range encloses
3913    // the region of interest, rather than starting from the translation unit.
3914    GetCursorData ResultData(CXXUnit->getSourceManager(), SLoc, Result);
3915    CXCursor Parent = clang_getTranslationUnitCursor(TU);
3916    CursorVisitor CursorVis(TU, GetCursorVisitor, &ResultData,
3917                            /*VisitPreprocessorLast=*/true,
3918                            SourceLocation(SLoc));
3919    CursorVis.VisitChildren(Parent);
3920  }
3921
3922  return Result;
3923}
3924
3925static SourceRange getRawCursorExtent(CXCursor C) {
3926  if (clang_isReference(C.kind)) {
3927    switch (C.kind) {
3928    case CXCursor_ObjCSuperClassRef:
3929      return  getCursorObjCSuperClassRef(C).second;
3930
3931    case CXCursor_ObjCProtocolRef:
3932      return getCursorObjCProtocolRef(C).second;
3933
3934    case CXCursor_ObjCClassRef:
3935      return getCursorObjCClassRef(C).second;
3936
3937    case CXCursor_TypeRef:
3938      return getCursorTypeRef(C).second;
3939
3940    case CXCursor_TemplateRef:
3941      return getCursorTemplateRef(C).second;
3942
3943    case CXCursor_NamespaceRef:
3944      return getCursorNamespaceRef(C).second;
3945
3946    case CXCursor_MemberRef:
3947      return getCursorMemberRef(C).second;
3948
3949    case CXCursor_CXXBaseSpecifier:
3950      return getCursorCXXBaseSpecifier(C)->getSourceRange();
3951
3952    case CXCursor_LabelRef:
3953      return getCursorLabelRef(C).second;
3954
3955    case CXCursor_OverloadedDeclRef:
3956      return getCursorOverloadedDeclRef(C).second;
3957
3958    default:
3959      // FIXME: Need a way to enumerate all non-reference cases.
3960      llvm_unreachable("Missed a reference kind");
3961    }
3962  }
3963
3964  if (clang_isExpression(C.kind))
3965    return getCursorExpr(C)->getSourceRange();
3966
3967  if (clang_isStatement(C.kind))
3968    return getCursorStmt(C)->getSourceRange();
3969
3970  if (clang_isAttribute(C.kind))
3971    return getCursorAttr(C)->getRange();
3972
3973  if (C.kind == CXCursor_PreprocessingDirective)
3974    return cxcursor::getCursorPreprocessingDirective(C);
3975
3976  if (C.kind == CXCursor_MacroExpansion) {
3977    ASTUnit *TU = getCursorASTUnit(C);
3978    SourceRange Range = cxcursor::getCursorMacroExpansion(C)->getSourceRange();
3979    return TU->mapRangeFromPreamble(Range);
3980  }
3981
3982  if (C.kind == CXCursor_MacroDefinition) {
3983    ASTUnit *TU = getCursorASTUnit(C);
3984    SourceRange Range = cxcursor::getCursorMacroDefinition(C)->getSourceRange();
3985    return TU->mapRangeFromPreamble(Range);
3986  }
3987
3988  if (C.kind == CXCursor_InclusionDirective) {
3989    ASTUnit *TU = getCursorASTUnit(C);
3990    SourceRange Range = cxcursor::getCursorInclusionDirective(C)->getSourceRange();
3991    return TU->mapRangeFromPreamble(Range);
3992  }
3993
3994  if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
3995    Decl *D = cxcursor::getCursorDecl(C);
3996    SourceRange R = D->getSourceRange();
3997    // FIXME: Multiple variables declared in a single declaration
3998    // currently lack the information needed to correctly determine their
3999    // ranges when accounting for the type-specifier.  We use context
4000    // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
4001    // and if so, whether it is the first decl.
4002    if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
4003      if (!cxcursor::isFirstInDeclGroup(C))
4004        R.setBegin(VD->getLocation());
4005    }
4006    return R;
4007  }
4008  return SourceRange();
4009}
4010
4011/// \brief Retrieves the "raw" cursor extent, which is then extended to include
4012/// the decl-specifier-seq for declarations.
4013static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr) {
4014  if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
4015    Decl *D = cxcursor::getCursorDecl(C);
4016    SourceRange R = D->getSourceRange();
4017
4018    // Adjust the start of the location for declarations preceded by
4019    // declaration specifiers.
4020    SourceLocation StartLoc;
4021    if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
4022      if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
4023        StartLoc = TI->getTypeLoc().getSourceRange().getBegin();
4024    } else if (TypedefDecl *Typedef = dyn_cast<TypedefDecl>(D)) {
4025      if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
4026        StartLoc = TI->getTypeLoc().getSourceRange().getBegin();
4027    }
4028
4029    if (StartLoc.isValid() && R.getBegin().isValid() &&
4030        SrcMgr.isBeforeInTranslationUnit(StartLoc, R.getBegin()))
4031      R.setBegin(StartLoc);
4032
4033    // FIXME: Multiple variables declared in a single declaration
4034    // currently lack the information needed to correctly determine their
4035    // ranges when accounting for the type-specifier.  We use context
4036    // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
4037    // and if so, whether it is the first decl.
4038    if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
4039      if (!cxcursor::isFirstInDeclGroup(C))
4040        R.setBegin(VD->getLocation());
4041    }
4042
4043    return R;
4044  }
4045
4046  return getRawCursorExtent(C);
4047}
4048
4049extern "C" {
4050
4051CXSourceRange clang_getCursorExtent(CXCursor C) {
4052  SourceRange R = getRawCursorExtent(C);
4053  if (R.isInvalid())
4054    return clang_getNullRange();
4055
4056  return cxloc::translateSourceRange(getCursorContext(C), R);
4057}
4058
4059CXCursor clang_getCursorReferenced(CXCursor C) {
4060  if (clang_isInvalid(C.kind))
4061    return clang_getNullCursor();
4062
4063  CXTranslationUnit tu = getCursorTU(C);
4064  if (clang_isDeclaration(C.kind)) {
4065    Decl *D = getCursorDecl(C);
4066    if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
4067      return MakeCursorOverloadedDeclRef(Using, D->getLocation(), tu);
4068    if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
4069      return MakeCursorOverloadedDeclRef(Classes, D->getLocation(), tu);
4070    if (ObjCForwardProtocolDecl *Protocols
4071                                        = dyn_cast<ObjCForwardProtocolDecl>(D))
4072      return MakeCursorOverloadedDeclRef(Protocols, D->getLocation(), tu);
4073    if (ObjCPropertyImplDecl *PropImpl =dyn_cast<ObjCPropertyImplDecl>(D))
4074      if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
4075        return MakeCXCursor(Property, tu);
4076
4077    return C;
4078  }
4079
4080  if (clang_isExpression(C.kind)) {
4081    Expr *E = getCursorExpr(C);
4082    Decl *D = getDeclFromExpr(E);
4083    if (D) {
4084      CXCursor declCursor = MakeCXCursor(D, tu);
4085      declCursor = getSelectorIdentifierCursor(getSelectorIdentifierIndex(C),
4086                                               declCursor);
4087      return declCursor;
4088    }
4089
4090    if (OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
4091      return MakeCursorOverloadedDeclRef(Ovl, tu);
4092
4093    return clang_getNullCursor();
4094  }
4095
4096  if (clang_isStatement(C.kind)) {
4097    Stmt *S = getCursorStmt(C);
4098    if (GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
4099      if (LabelDecl *label = Goto->getLabel())
4100        if (LabelStmt *labelS = label->getStmt())
4101        return MakeCXCursor(labelS, getCursorDecl(C), tu);
4102
4103    return clang_getNullCursor();
4104  }
4105
4106  if (C.kind == CXCursor_MacroExpansion) {
4107    if (MacroDefinition *Def = getCursorMacroExpansion(C)->getDefinition())
4108      return MakeMacroDefinitionCursor(Def, tu);
4109  }
4110
4111  if (!clang_isReference(C.kind))
4112    return clang_getNullCursor();
4113
4114  switch (C.kind) {
4115    case CXCursor_ObjCSuperClassRef:
4116      return MakeCXCursor(getCursorObjCSuperClassRef(C).first, tu);
4117
4118    case CXCursor_ObjCProtocolRef: {
4119      return MakeCXCursor(getCursorObjCProtocolRef(C).first, tu);
4120
4121    case CXCursor_ObjCClassRef:
4122      return MakeCXCursor(getCursorObjCClassRef(C).first, tu );
4123
4124    case CXCursor_TypeRef:
4125      return MakeCXCursor(getCursorTypeRef(C).first, tu );
4126
4127    case CXCursor_TemplateRef:
4128      return MakeCXCursor(getCursorTemplateRef(C).first, tu );
4129
4130    case CXCursor_NamespaceRef:
4131      return MakeCXCursor(getCursorNamespaceRef(C).first, tu );
4132
4133    case CXCursor_MemberRef:
4134      return MakeCXCursor(getCursorMemberRef(C).first, tu );
4135
4136    case CXCursor_CXXBaseSpecifier: {
4137      CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
4138      return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
4139                                                         tu ));
4140    }
4141
4142    case CXCursor_LabelRef:
4143      // FIXME: We end up faking the "parent" declaration here because we
4144      // don't want to make CXCursor larger.
4145      return MakeCXCursor(getCursorLabelRef(C).first,
4146               static_cast<ASTUnit*>(tu->TUData)->getASTContext()
4147                          .getTranslationUnitDecl(),
4148                          tu);
4149
4150    case CXCursor_OverloadedDeclRef:
4151      return C;
4152
4153    default:
4154      // We would prefer to enumerate all non-reference cursor kinds here.
4155      llvm_unreachable("Unhandled reference cursor kind");
4156      break;
4157    }
4158  }
4159
4160  return clang_getNullCursor();
4161}
4162
4163CXCursor clang_getCursorDefinition(CXCursor C) {
4164  if (clang_isInvalid(C.kind))
4165    return clang_getNullCursor();
4166
4167  CXTranslationUnit TU = getCursorTU(C);
4168
4169  bool WasReference = false;
4170  if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
4171    C = clang_getCursorReferenced(C);
4172    WasReference = true;
4173  }
4174
4175  if (C.kind == CXCursor_MacroExpansion)
4176    return clang_getCursorReferenced(C);
4177
4178  if (!clang_isDeclaration(C.kind))
4179    return clang_getNullCursor();
4180
4181  Decl *D = getCursorDecl(C);
4182  if (!D)
4183    return clang_getNullCursor();
4184
4185  switch (D->getKind()) {
4186  // Declaration kinds that don't really separate the notions of
4187  // declaration and definition.
4188  case Decl::Namespace:
4189  case Decl::Typedef:
4190  case Decl::TypeAlias:
4191  case Decl::TypeAliasTemplate:
4192  case Decl::TemplateTypeParm:
4193  case Decl::EnumConstant:
4194  case Decl::Field:
4195  case Decl::IndirectField:
4196  case Decl::ObjCIvar:
4197  case Decl::ObjCAtDefsField:
4198  case Decl::ImplicitParam:
4199  case Decl::ParmVar:
4200  case Decl::NonTypeTemplateParm:
4201  case Decl::TemplateTemplateParm:
4202  case Decl::ObjCCategoryImpl:
4203  case Decl::ObjCImplementation:
4204  case Decl::AccessSpec:
4205  case Decl::LinkageSpec:
4206  case Decl::ObjCPropertyImpl:
4207  case Decl::FileScopeAsm:
4208  case Decl::StaticAssert:
4209  case Decl::Block:
4210  case Decl::Label:  // FIXME: Is this right??
4211  case Decl::ClassScopeFunctionSpecialization:
4212    return C;
4213
4214  // Declaration kinds that don't make any sense here, but are
4215  // nonetheless harmless.
4216  case Decl::TranslationUnit:
4217    break;
4218
4219  // Declaration kinds for which the definition is not resolvable.
4220  case Decl::UnresolvedUsingTypename:
4221  case Decl::UnresolvedUsingValue:
4222    break;
4223
4224  case Decl::UsingDirective:
4225    return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
4226                        TU);
4227
4228  case Decl::NamespaceAlias:
4229    return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), TU);
4230
4231  case Decl::Enum:
4232  case Decl::Record:
4233  case Decl::CXXRecord:
4234  case Decl::ClassTemplateSpecialization:
4235  case Decl::ClassTemplatePartialSpecialization:
4236    if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
4237      return MakeCXCursor(Def, TU);
4238    return clang_getNullCursor();
4239
4240  case Decl::Function:
4241  case Decl::CXXMethod:
4242  case Decl::CXXConstructor:
4243  case Decl::CXXDestructor:
4244  case Decl::CXXConversion: {
4245    const FunctionDecl *Def = 0;
4246    if (cast<FunctionDecl>(D)->getBody(Def))
4247      return MakeCXCursor(const_cast<FunctionDecl *>(Def), TU);
4248    return clang_getNullCursor();
4249  }
4250
4251  case Decl::Var: {
4252    // Ask the variable if it has a definition.
4253    if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
4254      return MakeCXCursor(Def, TU);
4255    return clang_getNullCursor();
4256  }
4257
4258  case Decl::FunctionTemplate: {
4259    const FunctionDecl *Def = 0;
4260    if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
4261      return MakeCXCursor(Def->getDescribedFunctionTemplate(), TU);
4262    return clang_getNullCursor();
4263  }
4264
4265  case Decl::ClassTemplate: {
4266    if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
4267                                                            ->getDefinition())
4268      return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
4269                          TU);
4270    return clang_getNullCursor();
4271  }
4272
4273  case Decl::Using:
4274    return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
4275                                       D->getLocation(), TU);
4276
4277  case Decl::UsingShadow:
4278    return clang_getCursorDefinition(
4279                       MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
4280                                    TU));
4281
4282  case Decl::ObjCMethod: {
4283    ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
4284    if (Method->isThisDeclarationADefinition())
4285      return C;
4286
4287    // Dig out the method definition in the associated
4288    // @implementation, if we have it.
4289    // FIXME: The ASTs should make finding the definition easier.
4290    if (ObjCInterfaceDecl *Class
4291                       = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
4292      if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
4293        if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
4294                                                  Method->isInstanceMethod()))
4295          if (Def->isThisDeclarationADefinition())
4296            return MakeCXCursor(Def, TU);
4297
4298    return clang_getNullCursor();
4299  }
4300
4301  case Decl::ObjCCategory:
4302    if (ObjCCategoryImplDecl *Impl
4303                               = cast<ObjCCategoryDecl>(D)->getImplementation())
4304      return MakeCXCursor(Impl, TU);
4305    return clang_getNullCursor();
4306
4307  case Decl::ObjCProtocol:
4308    if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
4309      return C;
4310    return clang_getNullCursor();
4311
4312  case Decl::ObjCInterface:
4313    // There are two notions of a "definition" for an Objective-C
4314    // class: the interface and its implementation. When we resolved a
4315    // reference to an Objective-C class, produce the @interface as
4316    // the definition; when we were provided with the interface,
4317    // produce the @implementation as the definition.
4318    if (WasReference) {
4319      if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
4320        return C;
4321    } else if (ObjCImplementationDecl *Impl
4322                              = cast<ObjCInterfaceDecl>(D)->getImplementation())
4323      return MakeCXCursor(Impl, TU);
4324    return clang_getNullCursor();
4325
4326  case Decl::ObjCProperty:
4327    // FIXME: We don't really know where to find the
4328    // ObjCPropertyImplDecls that implement this property.
4329    return clang_getNullCursor();
4330
4331  case Decl::ObjCCompatibleAlias:
4332    if (ObjCInterfaceDecl *Class
4333          = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
4334      if (!Class->isForwardDecl())
4335        return MakeCXCursor(Class, TU);
4336
4337    return clang_getNullCursor();
4338
4339  case Decl::ObjCForwardProtocol:
4340    return MakeCursorOverloadedDeclRef(cast<ObjCForwardProtocolDecl>(D),
4341                                       D->getLocation(), TU);
4342
4343  case Decl::ObjCClass:
4344    return MakeCursorOverloadedDeclRef(cast<ObjCClassDecl>(D), D->getLocation(),
4345                                       TU);
4346
4347  case Decl::Friend:
4348    if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
4349      return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
4350    return clang_getNullCursor();
4351
4352  case Decl::FriendTemplate:
4353    if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
4354      return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
4355    return clang_getNullCursor();
4356  }
4357
4358  return clang_getNullCursor();
4359}
4360
4361unsigned clang_isCursorDefinition(CXCursor C) {
4362  if (!clang_isDeclaration(C.kind))
4363    return 0;
4364
4365  return clang_getCursorDefinition(C) == C;
4366}
4367
4368CXCursor clang_getCanonicalCursor(CXCursor C) {
4369  if (!clang_isDeclaration(C.kind))
4370    return C;
4371
4372  if (Decl *D = getCursorDecl(C)) {
4373    if (ObjCCategoryImplDecl *CatImplD = dyn_cast<ObjCCategoryImplDecl>(D))
4374      if (ObjCCategoryDecl *CatD = CatImplD->getCategoryDecl())
4375        return MakeCXCursor(CatD, getCursorTU(C));
4376
4377    if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
4378      if (ObjCInterfaceDecl *IFD = ImplD->getClassInterface())
4379        return MakeCXCursor(IFD, getCursorTU(C));
4380
4381    return MakeCXCursor(D->getCanonicalDecl(), getCursorTU(C));
4382  }
4383
4384  return C;
4385}
4386
4387unsigned clang_getNumOverloadedDecls(CXCursor C) {
4388  if (C.kind != CXCursor_OverloadedDeclRef)
4389    return 0;
4390
4391  OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
4392  if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
4393    return E->getNumDecls();
4394
4395  if (OverloadedTemplateStorage *S
4396                              = Storage.dyn_cast<OverloadedTemplateStorage*>())
4397    return S->size();
4398
4399  Decl *D = Storage.get<Decl*>();
4400  if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
4401    return Using->shadow_size();
4402  if (isa<ObjCClassDecl>(D))
4403    return 1;
4404  if (ObjCForwardProtocolDecl *Protocols =dyn_cast<ObjCForwardProtocolDecl>(D))
4405    return Protocols->protocol_size();
4406
4407  return 0;
4408}
4409
4410CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
4411  if (cursor.kind != CXCursor_OverloadedDeclRef)
4412    return clang_getNullCursor();
4413
4414  if (index >= clang_getNumOverloadedDecls(cursor))
4415    return clang_getNullCursor();
4416
4417  CXTranslationUnit TU = getCursorTU(cursor);
4418  OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
4419  if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
4420    return MakeCXCursor(E->decls_begin()[index], TU);
4421
4422  if (OverloadedTemplateStorage *S
4423                              = Storage.dyn_cast<OverloadedTemplateStorage*>())
4424    return MakeCXCursor(S->begin()[index], TU);
4425
4426  Decl *D = Storage.get<Decl*>();
4427  if (UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
4428    // FIXME: This is, unfortunately, linear time.
4429    UsingDecl::shadow_iterator Pos = Using->shadow_begin();
4430    std::advance(Pos, index);
4431    return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), TU);
4432  }
4433  if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
4434    return MakeCXCursor(Classes->getForwardInterfaceDecl(), TU);
4435  if (ObjCForwardProtocolDecl *Protocols = dyn_cast<ObjCForwardProtocolDecl>(D))
4436    return MakeCXCursor(Protocols->protocol_begin()[index], TU);
4437
4438  return clang_getNullCursor();
4439}
4440
4441void clang_getDefinitionSpellingAndExtent(CXCursor C,
4442                                          const char **startBuf,
4443                                          const char **endBuf,
4444                                          unsigned *startLine,
4445                                          unsigned *startColumn,
4446                                          unsigned *endLine,
4447                                          unsigned *endColumn) {
4448  assert(getCursorDecl(C) && "CXCursor has null decl");
4449  NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
4450  FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
4451  CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
4452
4453  SourceManager &SM = FD->getASTContext().getSourceManager();
4454  *startBuf = SM.getCharacterData(Body->getLBracLoc());
4455  *endBuf = SM.getCharacterData(Body->getRBracLoc());
4456  *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
4457  *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
4458  *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
4459  *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
4460}
4461
4462
4463CXSourceRange clang_getCursorReferenceNameRange(CXCursor C, unsigned NameFlags,
4464                                                unsigned PieceIndex) {
4465  RefNamePieces Pieces;
4466
4467  switch (C.kind) {
4468  case CXCursor_MemberRefExpr:
4469    if (MemberExpr *E = dyn_cast<MemberExpr>(getCursorExpr(C)))
4470      Pieces = buildPieces(NameFlags, true, E->getMemberNameInfo(),
4471                           E->getQualifierLoc().getSourceRange());
4472    break;
4473
4474  case CXCursor_DeclRefExpr:
4475    if (DeclRefExpr *E = dyn_cast<DeclRefExpr>(getCursorExpr(C)))
4476      Pieces = buildPieces(NameFlags, false, E->getNameInfo(),
4477                           E->getQualifierLoc().getSourceRange(),
4478                           E->getExplicitTemplateArgsOpt());
4479    break;
4480
4481  case CXCursor_CallExpr:
4482    if (CXXOperatorCallExpr *OCE =
4483        dyn_cast<CXXOperatorCallExpr>(getCursorExpr(C))) {
4484      Expr *Callee = OCE->getCallee();
4485      if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Callee))
4486        Callee = ICE->getSubExpr();
4487
4488      if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Callee))
4489        Pieces = buildPieces(NameFlags, false, DRE->getNameInfo(),
4490                             DRE->getQualifierLoc().getSourceRange());
4491    }
4492    break;
4493
4494  default:
4495    break;
4496  }
4497
4498  if (Pieces.empty()) {
4499    if (PieceIndex == 0)
4500      return clang_getCursorExtent(C);
4501  } else if (PieceIndex < Pieces.size()) {
4502      SourceRange R = Pieces[PieceIndex];
4503      if (R.isValid())
4504        return cxloc::translateSourceRange(getCursorContext(C), R);
4505  }
4506
4507  return clang_getNullRange();
4508}
4509
4510void clang_enableStackTraces(void) {
4511  llvm::sys::PrintStackTraceOnErrorSignal();
4512}
4513
4514void clang_executeOnThread(void (*fn)(void*), void *user_data,
4515                           unsigned stack_size) {
4516  llvm::llvm_execute_on_thread(fn, user_data, stack_size);
4517}
4518
4519} // end: extern "C"
4520
4521//===----------------------------------------------------------------------===//
4522// Token-based Operations.
4523//===----------------------------------------------------------------------===//
4524
4525/* CXToken layout:
4526 *   int_data[0]: a CXTokenKind
4527 *   int_data[1]: starting token location
4528 *   int_data[2]: token length
4529 *   int_data[3]: reserved
4530 *   ptr_data: for identifiers and keywords, an IdentifierInfo*.
4531 *   otherwise unused.
4532 */
4533extern "C" {
4534
4535CXTokenKind clang_getTokenKind(CXToken CXTok) {
4536  return static_cast<CXTokenKind>(CXTok.int_data[0]);
4537}
4538
4539CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
4540  switch (clang_getTokenKind(CXTok)) {
4541  case CXToken_Identifier:
4542  case CXToken_Keyword:
4543    // We know we have an IdentifierInfo*, so use that.
4544    return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
4545                            ->getNameStart());
4546
4547  case CXToken_Literal: {
4548    // We have stashed the starting pointer in the ptr_data field. Use it.
4549    const char *Text = static_cast<const char *>(CXTok.ptr_data);
4550    return createCXString(StringRef(Text, CXTok.int_data[2]));
4551  }
4552
4553  case CXToken_Punctuation:
4554  case CXToken_Comment:
4555    break;
4556  }
4557
4558  // We have to find the starting buffer pointer the hard way, by
4559  // deconstructing the source location.
4560  ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
4561  if (!CXXUnit)
4562    return createCXString("");
4563
4564  SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
4565  std::pair<FileID, unsigned> LocInfo
4566    = CXXUnit->getSourceManager().getDecomposedSpellingLoc(Loc);
4567  bool Invalid = false;
4568  StringRef Buffer
4569    = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
4570  if (Invalid)
4571    return createCXString("");
4572
4573  return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
4574}
4575
4576CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
4577  ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
4578  if (!CXXUnit)
4579    return clang_getNullLocation();
4580
4581  return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
4582                        SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
4583}
4584
4585CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
4586  ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
4587  if (!CXXUnit)
4588    return clang_getNullRange();
4589
4590  return cxloc::translateSourceRange(CXXUnit->getASTContext(),
4591                        SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
4592}
4593
4594static void getTokens(ASTUnit *CXXUnit, SourceRange Range,
4595                      SmallVectorImpl<CXToken> &CXTokens) {
4596  SourceManager &SourceMgr = CXXUnit->getSourceManager();
4597  std::pair<FileID, unsigned> BeginLocInfo
4598    = SourceMgr.getDecomposedLoc(Range.getBegin());
4599  std::pair<FileID, unsigned> EndLocInfo
4600    = SourceMgr.getDecomposedLoc(Range.getEnd());
4601
4602  // Cannot tokenize across files.
4603  if (BeginLocInfo.first != EndLocInfo.first)
4604    return;
4605
4606  // Create a lexer
4607  bool Invalid = false;
4608  StringRef Buffer
4609    = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
4610  if (Invalid)
4611    return;
4612
4613  Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
4614            CXXUnit->getASTContext().getLangOptions(),
4615            Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
4616  Lex.SetCommentRetentionState(true);
4617
4618  // Lex tokens until we hit the end of the range.
4619  const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
4620  Token Tok;
4621  bool previousWasAt = false;
4622  do {
4623    // Lex the next token
4624    Lex.LexFromRawLexer(Tok);
4625    if (Tok.is(tok::eof))
4626      break;
4627
4628    // Initialize the CXToken.
4629    CXToken CXTok;
4630
4631    //   - Common fields
4632    CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
4633    CXTok.int_data[2] = Tok.getLength();
4634    CXTok.int_data[3] = 0;
4635
4636    //   - Kind-specific fields
4637    if (Tok.isLiteral()) {
4638      CXTok.int_data[0] = CXToken_Literal;
4639      CXTok.ptr_data = (void *)Tok.getLiteralData();
4640    } else if (Tok.is(tok::raw_identifier)) {
4641      // Lookup the identifier to determine whether we have a keyword.
4642      IdentifierInfo *II
4643        = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok);
4644
4645      if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
4646        CXTok.int_data[0] = CXToken_Keyword;
4647      }
4648      else {
4649        CXTok.int_data[0] = Tok.is(tok::identifier)
4650          ? CXToken_Identifier
4651          : CXToken_Keyword;
4652      }
4653      CXTok.ptr_data = II;
4654    } else if (Tok.is(tok::comment)) {
4655      CXTok.int_data[0] = CXToken_Comment;
4656      CXTok.ptr_data = 0;
4657    } else {
4658      CXTok.int_data[0] = CXToken_Punctuation;
4659      CXTok.ptr_data = 0;
4660    }
4661    CXTokens.push_back(CXTok);
4662    previousWasAt = Tok.is(tok::at);
4663  } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
4664}
4665
4666void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
4667                    CXToken **Tokens, unsigned *NumTokens) {
4668  if (Tokens)
4669    *Tokens = 0;
4670  if (NumTokens)
4671    *NumTokens = 0;
4672
4673  ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
4674  if (!CXXUnit || !Tokens || !NumTokens)
4675    return;
4676
4677  ASTUnit::ConcurrencyCheck Check(*CXXUnit);
4678
4679  SourceRange R = cxloc::translateCXSourceRange(Range);
4680  if (R.isInvalid())
4681    return;
4682
4683  SmallVector<CXToken, 32> CXTokens;
4684  getTokens(CXXUnit, R, CXTokens);
4685
4686  if (CXTokens.empty())
4687    return;
4688
4689  *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
4690  memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
4691  *NumTokens = CXTokens.size();
4692}
4693
4694void clang_disposeTokens(CXTranslationUnit TU,
4695                         CXToken *Tokens, unsigned NumTokens) {
4696  free(Tokens);
4697}
4698
4699} // end: extern "C"
4700
4701//===----------------------------------------------------------------------===//
4702// Token annotation APIs.
4703//===----------------------------------------------------------------------===//
4704
4705typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
4706static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
4707                                                     CXCursor parent,
4708                                                     CXClientData client_data);
4709namespace {
4710class AnnotateTokensWorker {
4711  AnnotateTokensData &Annotated;
4712  CXToken *Tokens;
4713  CXCursor *Cursors;
4714  unsigned NumTokens;
4715  unsigned TokIdx;
4716  unsigned PreprocessingTokIdx;
4717  CursorVisitor AnnotateVis;
4718  SourceManager &SrcMgr;
4719  bool HasContextSensitiveKeywords;
4720
4721  bool MoreTokens() const { return TokIdx < NumTokens; }
4722  unsigned NextToken() const { return TokIdx; }
4723  void AdvanceToken() { ++TokIdx; }
4724  SourceLocation GetTokenLoc(unsigned tokI) {
4725    return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
4726  }
4727  bool isFunctionMacroToken(unsigned tokI) const {
4728    return Tokens[tokI].int_data[3] != 0;
4729  }
4730  SourceLocation getFunctionMacroTokenLoc(unsigned tokI) const {
4731    return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[3]);
4732  }
4733
4734  void annotateAndAdvanceTokens(CXCursor, RangeComparisonResult, SourceRange);
4735  void annotateAndAdvanceFunctionMacroTokens(CXCursor, RangeComparisonResult,
4736                                             SourceRange);
4737
4738public:
4739  AnnotateTokensWorker(AnnotateTokensData &annotated,
4740                       CXToken *tokens, CXCursor *cursors, unsigned numTokens,
4741                       CXTranslationUnit tu, SourceRange RegionOfInterest)
4742    : Annotated(annotated), Tokens(tokens), Cursors(cursors),
4743      NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0),
4744      AnnotateVis(tu,
4745                  AnnotateTokensVisitor, this, true, RegionOfInterest),
4746      SrcMgr(static_cast<ASTUnit*>(tu->TUData)->getSourceManager()),
4747      HasContextSensitiveKeywords(false) { }
4748
4749  void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
4750  enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
4751  void AnnotateTokens(CXCursor parent);
4752  void AnnotateTokens() {
4753    AnnotateTokens(clang_getTranslationUnitCursor(AnnotateVis.getTU()));
4754  }
4755
4756  /// \brief Determine whether the annotator saw any cursors that have
4757  /// context-sensitive keywords.
4758  bool hasContextSensitiveKeywords() const {
4759    return HasContextSensitiveKeywords;
4760  }
4761};
4762}
4763
4764void AnnotateTokensWorker::AnnotateTokens(CXCursor parent) {
4765  // Walk the AST within the region of interest, annotating tokens
4766  // along the way.
4767  VisitChildren(parent);
4768
4769  for (unsigned I = 0 ; I < TokIdx ; ++I) {
4770    AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
4771    if (Pos != Annotated.end() &&
4772        (clang_isInvalid(Cursors[I].kind) ||
4773         Pos->second.kind != CXCursor_PreprocessingDirective))
4774      Cursors[I] = Pos->second;
4775  }
4776
4777  // Finish up annotating any tokens left.
4778  if (!MoreTokens())
4779    return;
4780
4781  const CXCursor &C = clang_getNullCursor();
4782  for (unsigned I = TokIdx ; I < NumTokens ; ++I) {
4783    AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
4784    Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second;
4785  }
4786}
4787
4788/// \brief It annotates and advances tokens with a cursor until the comparison
4789//// between the cursor location and the source range is the same as
4790/// \arg compResult.
4791///
4792/// Pass RangeBefore to annotate tokens with a cursor until a range is reached.
4793/// Pass RangeOverlap to annotate tokens inside a range.
4794void AnnotateTokensWorker::annotateAndAdvanceTokens(CXCursor updateC,
4795                                               RangeComparisonResult compResult,
4796                                               SourceRange range) {
4797  while (MoreTokens()) {
4798    const unsigned I = NextToken();
4799    if (isFunctionMacroToken(I))
4800      return annotateAndAdvanceFunctionMacroTokens(updateC, compResult, range);
4801
4802    SourceLocation TokLoc = GetTokenLoc(I);
4803    if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
4804      Cursors[I] = updateC;
4805      AdvanceToken();
4806      continue;
4807    }
4808    break;
4809  }
4810}
4811
4812/// \brief Special annotation handling for macro argument tokens.
4813void AnnotateTokensWorker::annotateAndAdvanceFunctionMacroTokens(
4814                                               CXCursor updateC,
4815                                               RangeComparisonResult compResult,
4816                                               SourceRange range) {
4817  assert(MoreTokens());
4818  assert(isFunctionMacroToken(NextToken()) &&
4819         "Should be called only for macro arg tokens");
4820
4821  // This works differently than annotateAndAdvanceTokens; because expanded
4822  // macro arguments can have arbitrary translation-unit source order, we do not
4823  // advance the token index one by one until a token fails the range test.
4824  // We only advance once past all of the macro arg tokens if all of them
4825  // pass the range test. If one of them fails we keep the token index pointing
4826  // at the start of the macro arg tokens so that the failing token will be
4827  // annotated by a subsequent annotation try.
4828
4829  bool atLeastOneCompFail = false;
4830
4831  unsigned I = NextToken();
4832  for (; I < NumTokens && isFunctionMacroToken(I); ++I) {
4833    SourceLocation TokLoc = getFunctionMacroTokenLoc(I);
4834    if (TokLoc.isFileID())
4835      continue; // not macro arg token, it's parens or comma.
4836    if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
4837      if (clang_isInvalid(clang_getCursorKind(Cursors[I])))
4838        Cursors[I] = updateC;
4839    } else
4840      atLeastOneCompFail = true;
4841  }
4842
4843  if (!atLeastOneCompFail)
4844    TokIdx = I; // All of the tokens were handled, advance beyond all of them.
4845}
4846
4847enum CXChildVisitResult
4848AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
4849  CXSourceLocation Loc = clang_getCursorLocation(cursor);
4850  SourceRange cursorRange = getRawCursorExtent(cursor);
4851  if (cursorRange.isInvalid())
4852    return CXChildVisit_Recurse;
4853
4854  if (!HasContextSensitiveKeywords) {
4855    // Objective-C properties can have context-sensitive keywords.
4856    if (cursor.kind == CXCursor_ObjCPropertyDecl) {
4857      if (ObjCPropertyDecl *Property
4858                  = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(cursor)))
4859        HasContextSensitiveKeywords = Property->getPropertyAttributesAsWritten() != 0;
4860    }
4861    // Objective-C methods can have context-sensitive keywords.
4862    else if (cursor.kind == CXCursor_ObjCInstanceMethodDecl ||
4863             cursor.kind == CXCursor_ObjCClassMethodDecl) {
4864      if (ObjCMethodDecl *Method
4865            = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
4866        if (Method->getObjCDeclQualifier())
4867          HasContextSensitiveKeywords = true;
4868        else {
4869          for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
4870                                           PEnd = Method->param_end();
4871               P != PEnd; ++P) {
4872            if ((*P)->getObjCDeclQualifier()) {
4873              HasContextSensitiveKeywords = true;
4874              break;
4875            }
4876          }
4877        }
4878      }
4879    }
4880    // C++ methods can have context-sensitive keywords.
4881    else if (cursor.kind == CXCursor_CXXMethod) {
4882      if (CXXMethodDecl *Method
4883                  = dyn_cast_or_null<CXXMethodDecl>(getCursorDecl(cursor))) {
4884        if (Method->hasAttr<FinalAttr>() || Method->hasAttr<OverrideAttr>())
4885          HasContextSensitiveKeywords = true;
4886      }
4887    }
4888    // C++ classes can have context-sensitive keywords.
4889    else if (cursor.kind == CXCursor_StructDecl ||
4890             cursor.kind == CXCursor_ClassDecl ||
4891             cursor.kind == CXCursor_ClassTemplate ||
4892             cursor.kind == CXCursor_ClassTemplatePartialSpecialization) {
4893      if (Decl *D = getCursorDecl(cursor))
4894        if (D->hasAttr<FinalAttr>())
4895          HasContextSensitiveKeywords = true;
4896    }
4897  }
4898
4899  if (clang_isPreprocessing(cursor.kind)) {
4900    // For macro expansions, just note where the beginning of the macro
4901    // expansion occurs.
4902    if (cursor.kind == CXCursor_MacroExpansion) {
4903      Annotated[Loc.int_data] = cursor;
4904      return CXChildVisit_Recurse;
4905    }
4906
4907    // Items in the preprocessing record are kept separate from items in
4908    // declarations, so we keep a separate token index.
4909    unsigned SavedTokIdx = TokIdx;
4910    TokIdx = PreprocessingTokIdx;
4911
4912    // Skip tokens up until we catch up to the beginning of the preprocessing
4913    // entry.
4914    while (MoreTokens()) {
4915      const unsigned I = NextToken();
4916      SourceLocation TokLoc = GetTokenLoc(I);
4917      switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4918      case RangeBefore:
4919        AdvanceToken();
4920        continue;
4921      case RangeAfter:
4922      case RangeOverlap:
4923        break;
4924      }
4925      break;
4926    }
4927
4928    // Look at all of the tokens within this range.
4929    while (MoreTokens()) {
4930      const unsigned I = NextToken();
4931      SourceLocation TokLoc = GetTokenLoc(I);
4932      switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4933      case RangeBefore:
4934        llvm_unreachable("Infeasible");
4935      case RangeAfter:
4936        break;
4937      case RangeOverlap:
4938        Cursors[I] = cursor;
4939        AdvanceToken();
4940        continue;
4941      }
4942      break;
4943    }
4944
4945    // Save the preprocessing token index; restore the non-preprocessing
4946    // token index.
4947    PreprocessingTokIdx = TokIdx;
4948    TokIdx = SavedTokIdx;
4949    return CXChildVisit_Recurse;
4950  }
4951
4952  if (cursorRange.isInvalid())
4953    return CXChildVisit_Continue;
4954
4955  SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data);
4956
4957  // Adjust the annotated range based specific declarations.
4958  const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
4959  if (cursorK >= CXCursor_FirstDecl && cursorK <= CXCursor_LastDecl) {
4960    Decl *D = cxcursor::getCursorDecl(cursor);
4961
4962    SourceLocation StartLoc;
4963    if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
4964      if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
4965        StartLoc = TI->getTypeLoc().getSourceRange().getBegin();
4966    } else if (TypedefDecl *Typedef = dyn_cast<TypedefDecl>(D)) {
4967      if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
4968        StartLoc = TI->getTypeLoc().getSourceRange().getBegin();
4969    }
4970
4971    if (StartLoc.isValid() && L.isValid() &&
4972        SrcMgr.isBeforeInTranslationUnit(StartLoc, L))
4973      cursorRange.setBegin(StartLoc);
4974  }
4975
4976  // If the location of the cursor occurs within a macro instantiation, record
4977  // the spelling location of the cursor in our annotation map.  We can then
4978  // paper over the token labelings during a post-processing step to try and
4979  // get cursor mappings for tokens that are the *arguments* of a macro
4980  // instantiation.
4981  if (L.isMacroID()) {
4982    unsigned rawEncoding = SrcMgr.getSpellingLoc(L).getRawEncoding();
4983    // Only invalidate the old annotation if it isn't part of a preprocessing
4984    // directive.  Here we assume that the default construction of CXCursor
4985    // results in CXCursor.kind being an initialized value (i.e., 0).  If
4986    // this isn't the case, we can fix by doing lookup + insertion.
4987
4988    CXCursor &oldC = Annotated[rawEncoding];
4989    if (!clang_isPreprocessing(oldC.kind))
4990      oldC = cursor;
4991  }
4992
4993  const enum CXCursorKind K = clang_getCursorKind(parent);
4994  const CXCursor updateC =
4995    (clang_isInvalid(K) || K == CXCursor_TranslationUnit)
4996     ? clang_getNullCursor() : parent;
4997
4998  annotateAndAdvanceTokens(updateC, RangeBefore, cursorRange);
4999
5000  // Avoid having the cursor of an expression "overwrite" the annotation of the
5001  // variable declaration that it belongs to.
5002  // This can happen for C++ constructor expressions whose range generally
5003  // include the variable declaration, e.g.:
5004  //  MyCXXClass foo; // Make sure we don't annotate 'foo' as a CallExpr cursor.
5005  if (clang_isExpression(cursorK)) {
5006    Expr *E = getCursorExpr(cursor);
5007    if (Decl *D = getCursorParentDecl(cursor)) {
5008      const unsigned I = NextToken();
5009      if (E->getLocStart().isValid() && D->getLocation().isValid() &&
5010          E->getLocStart() == D->getLocation() &&
5011          E->getLocStart() == GetTokenLoc(I)) {
5012        Cursors[I] = updateC;
5013        AdvanceToken();
5014      }
5015    }
5016  }
5017
5018  // Visit children to get their cursor information.
5019  const unsigned BeforeChildren = NextToken();
5020  VisitChildren(cursor);
5021  const unsigned AfterChildren = NextToken();
5022
5023  // Scan the tokens that are at the end of the cursor, but are not captured
5024  // but the child cursors.
5025  annotateAndAdvanceTokens(cursor, RangeOverlap, cursorRange);
5026
5027  // Scan the tokens that are at the beginning of the cursor, but are not
5028  // capture by the child cursors.
5029  for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
5030    if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
5031      break;
5032
5033    Cursors[I] = cursor;
5034  }
5035
5036  return CXChildVisit_Continue;
5037}
5038
5039static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
5040                                                     CXCursor parent,
5041                                                     CXClientData client_data) {
5042  return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
5043}
5044
5045namespace {
5046
5047/// \brief Uses the macro expansions in the preprocessing record to find
5048/// and mark tokens that are macro arguments. This info is used by the
5049/// AnnotateTokensWorker.
5050class MarkMacroArgTokensVisitor {
5051  SourceManager &SM;
5052  CXToken *Tokens;
5053  unsigned NumTokens;
5054  unsigned CurIdx;
5055
5056public:
5057  MarkMacroArgTokensVisitor(SourceManager &SM,
5058                            CXToken *tokens, unsigned numTokens)
5059    : SM(SM), Tokens(tokens), NumTokens(numTokens), CurIdx(0) { }
5060
5061  CXChildVisitResult visit(CXCursor cursor, CXCursor parent) {
5062    if (cursor.kind != CXCursor_MacroExpansion)
5063      return CXChildVisit_Continue;
5064
5065    SourceRange macroRange = getCursorMacroExpansion(cursor)->getSourceRange();
5066    if (macroRange.getBegin() == macroRange.getEnd())
5067      return CXChildVisit_Continue; // it's not a function macro.
5068
5069    for (; CurIdx < NumTokens; ++CurIdx) {
5070      if (!SM.isBeforeInTranslationUnit(getTokenLoc(CurIdx),
5071                                        macroRange.getBegin()))
5072        break;
5073    }
5074
5075    if (CurIdx == NumTokens)
5076      return CXChildVisit_Break;
5077
5078    for (; CurIdx < NumTokens; ++CurIdx) {
5079      SourceLocation tokLoc = getTokenLoc(CurIdx);
5080      if (!SM.isBeforeInTranslationUnit(tokLoc, macroRange.getEnd()))
5081        break;
5082
5083      setFunctionMacroTokenLoc(CurIdx, SM.getMacroArgExpandedLocation(tokLoc));
5084    }
5085
5086    if (CurIdx == NumTokens)
5087      return CXChildVisit_Break;
5088
5089    return CXChildVisit_Continue;
5090  }
5091
5092private:
5093  SourceLocation getTokenLoc(unsigned tokI) {
5094    return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
5095  }
5096
5097  void setFunctionMacroTokenLoc(unsigned tokI, SourceLocation loc) {
5098    // The third field is reserved and currently not used. Use it here
5099    // to mark macro arg expanded tokens with their expanded locations.
5100    Tokens[tokI].int_data[3] = loc.getRawEncoding();
5101  }
5102};
5103
5104} // end anonymous namespace
5105
5106static CXChildVisitResult
5107MarkMacroArgTokensVisitorDelegate(CXCursor cursor, CXCursor parent,
5108                                  CXClientData client_data) {
5109  return static_cast<MarkMacroArgTokensVisitor*>(client_data)->visit(cursor,
5110                                                                     parent);
5111}
5112
5113namespace {
5114  struct clang_annotateTokens_Data {
5115    CXTranslationUnit TU;
5116    ASTUnit *CXXUnit;
5117    CXToken *Tokens;
5118    unsigned NumTokens;
5119    CXCursor *Cursors;
5120  };
5121}
5122
5123static void annotatePreprocessorTokens(CXTranslationUnit TU,
5124                                       SourceRange RegionOfInterest,
5125                                       AnnotateTokensData &Annotated) {
5126  ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
5127
5128  SourceManager &SourceMgr = CXXUnit->getSourceManager();
5129  std::pair<FileID, unsigned> BeginLocInfo
5130    = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
5131  std::pair<FileID, unsigned> EndLocInfo
5132    = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
5133
5134  if (BeginLocInfo.first != EndLocInfo.first)
5135    return;
5136
5137  StringRef Buffer;
5138  bool Invalid = false;
5139  Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
5140  if (Buffer.empty() || Invalid)
5141    return;
5142
5143  Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
5144            CXXUnit->getASTContext().getLangOptions(),
5145            Buffer.begin(), Buffer.data() + BeginLocInfo.second,
5146            Buffer.end());
5147  Lex.SetCommentRetentionState(true);
5148
5149  // Lex tokens in raw mode until we hit the end of the range, to avoid
5150  // entering #includes or expanding macros.
5151  while (true) {
5152    Token Tok;
5153    Lex.LexFromRawLexer(Tok);
5154
5155  reprocess:
5156    if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
5157      // We have found a preprocessing directive. Gobble it up so that we
5158      // don't see it while preprocessing these tokens later, but keep track
5159      // of all of the token locations inside this preprocessing directive so
5160      // that we can annotate them appropriately.
5161      //
5162      // FIXME: Some simple tests here could identify macro definitions and
5163      // #undefs, to provide specific cursor kinds for those.
5164      SmallVector<SourceLocation, 32> Locations;
5165      do {
5166        Locations.push_back(Tok.getLocation());
5167        Lex.LexFromRawLexer(Tok);
5168      } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
5169
5170      using namespace cxcursor;
5171      CXCursor Cursor
5172      = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
5173                                                     Locations.back()),
5174                                         TU);
5175      for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
5176        Annotated[Locations[I].getRawEncoding()] = Cursor;
5177      }
5178
5179      if (Tok.isAtStartOfLine())
5180        goto reprocess;
5181
5182      continue;
5183    }
5184
5185    if (Tok.is(tok::eof))
5186      break;
5187  }
5188}
5189
5190// This gets run a separate thread to avoid stack blowout.
5191static void clang_annotateTokensImpl(void *UserData) {
5192  CXTranslationUnit TU = ((clang_annotateTokens_Data*)UserData)->TU;
5193  ASTUnit *CXXUnit = ((clang_annotateTokens_Data*)UserData)->CXXUnit;
5194  CXToken *Tokens = ((clang_annotateTokens_Data*)UserData)->Tokens;
5195  const unsigned NumTokens = ((clang_annotateTokens_Data*)UserData)->NumTokens;
5196  CXCursor *Cursors = ((clang_annotateTokens_Data*)UserData)->Cursors;
5197
5198  // Determine the region of interest, which contains all of the tokens.
5199  SourceRange RegionOfInterest;
5200  RegionOfInterest.setBegin(
5201    cxloc::translateSourceLocation(clang_getTokenLocation(TU, Tokens[0])));
5202  RegionOfInterest.setEnd(
5203    cxloc::translateSourceLocation(clang_getTokenLocation(TU,
5204                                                         Tokens[NumTokens-1])));
5205
5206  // A mapping from the source locations found when re-lexing or traversing the
5207  // region of interest to the corresponding cursors.
5208  AnnotateTokensData Annotated;
5209
5210  // Relex the tokens within the source range to look for preprocessing
5211  // directives.
5212  annotatePreprocessorTokens(TU, RegionOfInterest, Annotated);
5213
5214  if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
5215    // Search and mark tokens that are macro argument expansions.
5216    MarkMacroArgTokensVisitor Visitor(CXXUnit->getSourceManager(),
5217                                      Tokens, NumTokens);
5218    CursorVisitor MacroArgMarker(TU,
5219                                 MarkMacroArgTokensVisitorDelegate, &Visitor,
5220                                 true, RegionOfInterest);
5221    MacroArgMarker.visitPreprocessedEntitiesInRegion();
5222  }
5223
5224  // Annotate all of the source locations in the region of interest that map to
5225  // a specific cursor.
5226  AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens,
5227                         TU, RegionOfInterest);
5228
5229  // FIXME: We use a ridiculous stack size here because the data-recursion
5230  // algorithm uses a large stack frame than the non-data recursive version,
5231  // and AnnotationTokensWorker currently transforms the data-recursion
5232  // algorithm back into a traditional recursion by explicitly calling
5233  // VisitChildren().  We will need to remove this explicit recursive call.
5234  W.AnnotateTokens();
5235
5236  // If we ran into any entities that involve context-sensitive keywords,
5237  // take another pass through the tokens to mark them as such.
5238  if (W.hasContextSensitiveKeywords()) {
5239    for (unsigned I = 0; I != NumTokens; ++I) {
5240      if (clang_getTokenKind(Tokens[I]) != CXToken_Identifier)
5241        continue;
5242
5243      if (Cursors[I].kind == CXCursor_ObjCPropertyDecl) {
5244        IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
5245        if (ObjCPropertyDecl *Property
5246            = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(Cursors[I]))) {
5247          if (Property->getPropertyAttributesAsWritten() != 0 &&
5248              llvm::StringSwitch<bool>(II->getName())
5249              .Case("readonly", true)
5250              .Case("assign", true)
5251              .Case("unsafe_unretained", true)
5252              .Case("readwrite", true)
5253              .Case("retain", true)
5254              .Case("copy", true)
5255              .Case("nonatomic", true)
5256              .Case("atomic", true)
5257              .Case("getter", true)
5258              .Case("setter", true)
5259              .Case("strong", true)
5260              .Case("weak", true)
5261              .Default(false))
5262            Tokens[I].int_data[0] = CXToken_Keyword;
5263        }
5264        continue;
5265      }
5266
5267      if (Cursors[I].kind == CXCursor_ObjCInstanceMethodDecl ||
5268          Cursors[I].kind == CXCursor_ObjCClassMethodDecl) {
5269        IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
5270        if (llvm::StringSwitch<bool>(II->getName())
5271            .Case("in", true)
5272            .Case("out", true)
5273            .Case("inout", true)
5274            .Case("oneway", true)
5275            .Case("bycopy", true)
5276            .Case("byref", true)
5277            .Default(false))
5278          Tokens[I].int_data[0] = CXToken_Keyword;
5279        continue;
5280      }
5281
5282      if (Cursors[I].kind == CXCursor_CXXFinalAttr ||
5283          Cursors[I].kind == CXCursor_CXXOverrideAttr) {
5284        Tokens[I].int_data[0] = CXToken_Keyword;
5285        continue;
5286      }
5287    }
5288  }
5289}
5290
5291extern "C" {
5292
5293void clang_annotateTokens(CXTranslationUnit TU,
5294                          CXToken *Tokens, unsigned NumTokens,
5295                          CXCursor *Cursors) {
5296
5297  if (NumTokens == 0 || !Tokens || !Cursors)
5298    return;
5299
5300  // Any token we don't specifically annotate will have a NULL cursor.
5301  CXCursor C = clang_getNullCursor();
5302  for (unsigned I = 0; I != NumTokens; ++I)
5303    Cursors[I] = C;
5304
5305  ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
5306  if (!CXXUnit)
5307    return;
5308
5309  ASTUnit::ConcurrencyCheck Check(*CXXUnit);
5310
5311  clang_annotateTokens_Data data = { TU, CXXUnit, Tokens, NumTokens, Cursors };
5312  llvm::CrashRecoveryContext CRC;
5313  if (!RunSafely(CRC, clang_annotateTokensImpl, &data,
5314                 GetSafetyThreadStackSize() * 2)) {
5315    fprintf(stderr, "libclang: crash detected while annotating tokens\n");
5316  }
5317}
5318
5319} // end: extern "C"
5320
5321//===----------------------------------------------------------------------===//
5322// Operations for querying linkage of a cursor.
5323//===----------------------------------------------------------------------===//
5324
5325extern "C" {
5326CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
5327  if (!clang_isDeclaration(cursor.kind))
5328    return CXLinkage_Invalid;
5329
5330  Decl *D = cxcursor::getCursorDecl(cursor);
5331  if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
5332    switch (ND->getLinkage()) {
5333      case NoLinkage: return CXLinkage_NoLinkage;
5334      case InternalLinkage: return CXLinkage_Internal;
5335      case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
5336      case ExternalLinkage: return CXLinkage_External;
5337    };
5338
5339  return CXLinkage_Invalid;
5340}
5341} // end: extern "C"
5342
5343//===----------------------------------------------------------------------===//
5344// Operations for querying language of a cursor.
5345//===----------------------------------------------------------------------===//
5346
5347static CXLanguageKind getDeclLanguage(const Decl *D) {
5348  switch (D->getKind()) {
5349    default:
5350      break;
5351    case Decl::ImplicitParam:
5352    case Decl::ObjCAtDefsField:
5353    case Decl::ObjCCategory:
5354    case Decl::ObjCCategoryImpl:
5355    case Decl::ObjCClass:
5356    case Decl::ObjCCompatibleAlias:
5357    case Decl::ObjCForwardProtocol:
5358    case Decl::ObjCImplementation:
5359    case Decl::ObjCInterface:
5360    case Decl::ObjCIvar:
5361    case Decl::ObjCMethod:
5362    case Decl::ObjCProperty:
5363    case Decl::ObjCPropertyImpl:
5364    case Decl::ObjCProtocol:
5365      return CXLanguage_ObjC;
5366    case Decl::CXXConstructor:
5367    case Decl::CXXConversion:
5368    case Decl::CXXDestructor:
5369    case Decl::CXXMethod:
5370    case Decl::CXXRecord:
5371    case Decl::ClassTemplate:
5372    case Decl::ClassTemplatePartialSpecialization:
5373    case Decl::ClassTemplateSpecialization:
5374    case Decl::Friend:
5375    case Decl::FriendTemplate:
5376    case Decl::FunctionTemplate:
5377    case Decl::LinkageSpec:
5378    case Decl::Namespace:
5379    case Decl::NamespaceAlias:
5380    case Decl::NonTypeTemplateParm:
5381    case Decl::StaticAssert:
5382    case Decl::TemplateTemplateParm:
5383    case Decl::TemplateTypeParm:
5384    case Decl::UnresolvedUsingTypename:
5385    case Decl::UnresolvedUsingValue:
5386    case Decl::Using:
5387    case Decl::UsingDirective:
5388    case Decl::UsingShadow:
5389      return CXLanguage_CPlusPlus;
5390  }
5391
5392  return CXLanguage_C;
5393}
5394
5395extern "C" {
5396
5397enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
5398  if (clang_isDeclaration(cursor.kind))
5399    if (Decl *D = cxcursor::getCursorDecl(cursor)) {
5400      if (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted())
5401        return CXAvailability_Available;
5402
5403      switch (D->getAvailability()) {
5404      case AR_Available:
5405      case AR_NotYetIntroduced:
5406        return CXAvailability_Available;
5407
5408      case AR_Deprecated:
5409        return CXAvailability_Deprecated;
5410
5411      case AR_Unavailable:
5412        return CXAvailability_NotAvailable;
5413      }
5414    }
5415
5416  return CXAvailability_Available;
5417}
5418
5419CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
5420  if (clang_isDeclaration(cursor.kind))
5421    return getDeclLanguage(cxcursor::getCursorDecl(cursor));
5422
5423  return CXLanguage_Invalid;
5424}
5425
5426 /// \brief If the given cursor is the "templated" declaration
5427 /// descibing a class or function template, return the class or
5428 /// function template.
5429static Decl *maybeGetTemplateCursor(Decl *D) {
5430  if (!D)
5431    return 0;
5432
5433  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
5434    if (FunctionTemplateDecl *FunTmpl = FD->getDescribedFunctionTemplate())
5435      return FunTmpl;
5436
5437  if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
5438    if (ClassTemplateDecl *ClassTmpl = RD->getDescribedClassTemplate())
5439      return ClassTmpl;
5440
5441  return D;
5442}
5443
5444CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
5445  if (clang_isDeclaration(cursor.kind)) {
5446    if (Decl *D = getCursorDecl(cursor)) {
5447      DeclContext *DC = D->getDeclContext();
5448      if (!DC)
5449        return clang_getNullCursor();
5450
5451      return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
5452                          getCursorTU(cursor));
5453    }
5454  }
5455
5456  if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
5457    if (Decl *D = getCursorDecl(cursor))
5458      return MakeCXCursor(D, getCursorTU(cursor));
5459  }
5460
5461  return clang_getNullCursor();
5462}
5463
5464CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
5465  if (clang_isDeclaration(cursor.kind)) {
5466    if (Decl *D = getCursorDecl(cursor)) {
5467      DeclContext *DC = D->getLexicalDeclContext();
5468      if (!DC)
5469        return clang_getNullCursor();
5470
5471      return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
5472                          getCursorTU(cursor));
5473    }
5474  }
5475
5476  // FIXME: Note that we can't easily compute the lexical context of a
5477  // statement or expression, so we return nothing.
5478  return clang_getNullCursor();
5479}
5480
5481void clang_getOverriddenCursors(CXCursor cursor,
5482                                CXCursor **overridden,
5483                                unsigned *num_overridden) {
5484  if (overridden)
5485    *overridden = 0;
5486  if (num_overridden)
5487    *num_overridden = 0;
5488  if (!overridden || !num_overridden)
5489    return;
5490
5491  SmallVector<CXCursor, 8> Overridden;
5492  cxcursor::getOverriddenCursors(cursor, Overridden);
5493
5494  *num_overridden = Overridden.size();
5495  *overridden = new CXCursor [Overridden.size()];
5496  std::copy(Overridden.begin(), Overridden.end(), *overridden);
5497}
5498
5499void clang_disposeOverriddenCursors(CXCursor *overridden) {
5500  delete [] overridden;
5501}
5502
5503CXFile clang_getIncludedFile(CXCursor cursor) {
5504  if (cursor.kind != CXCursor_InclusionDirective)
5505    return 0;
5506
5507  InclusionDirective *ID = getCursorInclusionDirective(cursor);
5508  return (void *)ID->getFile();
5509}
5510
5511} // end: extern "C"
5512
5513
5514//===----------------------------------------------------------------------===//
5515// C++ AST instrospection.
5516//===----------------------------------------------------------------------===//
5517
5518extern "C" {
5519unsigned clang_CXXMethod_isStatic(CXCursor C) {
5520  if (!clang_isDeclaration(C.kind))
5521    return 0;
5522
5523  CXXMethodDecl *Method = 0;
5524  Decl *D = cxcursor::getCursorDecl(C);
5525  if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
5526    Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
5527  else
5528    Method = dyn_cast_or_null<CXXMethodDecl>(D);
5529  return (Method && Method->isStatic()) ? 1 : 0;
5530}
5531
5532unsigned clang_CXXMethod_isVirtual(CXCursor C) {
5533  if (!clang_isDeclaration(C.kind))
5534    return 0;
5535
5536  CXXMethodDecl *Method = 0;
5537  Decl *D = cxcursor::getCursorDecl(C);
5538  if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
5539    Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
5540  else
5541    Method = dyn_cast_or_null<CXXMethodDecl>(D);
5542  return (Method && Method->isVirtual()) ? 1 : 0;
5543}
5544} // end: extern "C"
5545
5546//===----------------------------------------------------------------------===//
5547// Attribute introspection.
5548//===----------------------------------------------------------------------===//
5549
5550extern "C" {
5551CXType clang_getIBOutletCollectionType(CXCursor C) {
5552  if (C.kind != CXCursor_IBOutletCollectionAttr)
5553    return cxtype::MakeCXType(QualType(), cxcursor::getCursorTU(C));
5554
5555  IBOutletCollectionAttr *A =
5556    cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
5557
5558  return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorTU(C));
5559}
5560} // end: extern "C"
5561
5562//===----------------------------------------------------------------------===//
5563// Inspecting memory usage.
5564//===----------------------------------------------------------------------===//
5565
5566typedef std::vector<CXTUResourceUsageEntry> MemUsageEntries;
5567
5568static inline void createCXTUResourceUsageEntry(MemUsageEntries &entries,
5569                                              enum CXTUResourceUsageKind k,
5570                                              unsigned long amount) {
5571  CXTUResourceUsageEntry entry = { k, amount };
5572  entries.push_back(entry);
5573}
5574
5575extern "C" {
5576
5577const char *clang_getTUResourceUsageName(CXTUResourceUsageKind kind) {
5578  const char *str = "";
5579  switch (kind) {
5580    case CXTUResourceUsage_AST:
5581      str = "ASTContext: expressions, declarations, and types";
5582      break;
5583    case CXTUResourceUsage_Identifiers:
5584      str = "ASTContext: identifiers";
5585      break;
5586    case CXTUResourceUsage_Selectors:
5587      str = "ASTContext: selectors";
5588      break;
5589    case CXTUResourceUsage_GlobalCompletionResults:
5590      str = "Code completion: cached global results";
5591      break;
5592    case CXTUResourceUsage_SourceManagerContentCache:
5593      str = "SourceManager: content cache allocator";
5594      break;
5595    case CXTUResourceUsage_AST_SideTables:
5596      str = "ASTContext: side tables";
5597      break;
5598    case CXTUResourceUsage_SourceManager_Membuffer_Malloc:
5599      str = "SourceManager: malloc'ed memory buffers";
5600      break;
5601    case CXTUResourceUsage_SourceManager_Membuffer_MMap:
5602      str = "SourceManager: mmap'ed memory buffers";
5603      break;
5604    case CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc:
5605      str = "ExternalASTSource: malloc'ed memory buffers";
5606      break;
5607    case CXTUResourceUsage_ExternalASTSource_Membuffer_MMap:
5608      str = "ExternalASTSource: mmap'ed memory buffers";
5609      break;
5610    case CXTUResourceUsage_Preprocessor:
5611      str = "Preprocessor: malloc'ed memory";
5612      break;
5613    case CXTUResourceUsage_PreprocessingRecord:
5614      str = "Preprocessor: PreprocessingRecord";
5615      break;
5616    case CXTUResourceUsage_SourceManager_DataStructures:
5617      str = "SourceManager: data structures and tables";
5618      break;
5619    case CXTUResourceUsage_Preprocessor_HeaderSearch:
5620      str = "Preprocessor: header search tables";
5621      break;
5622  }
5623  return str;
5624}
5625
5626CXTUResourceUsage clang_getCXTUResourceUsage(CXTranslationUnit TU) {
5627  if (!TU) {
5628    CXTUResourceUsage usage = { (void*) 0, 0, 0 };
5629    return usage;
5630  }
5631
5632  ASTUnit *astUnit = static_cast<ASTUnit*>(TU->TUData);
5633  llvm::OwningPtr<MemUsageEntries> entries(new MemUsageEntries());
5634  ASTContext &astContext = astUnit->getASTContext();
5635
5636  // How much memory is used by AST nodes and types?
5637  createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST,
5638    (unsigned long) astContext.getASTAllocatedMemory());
5639
5640  // How much memory is used by identifiers?
5641  createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Identifiers,
5642    (unsigned long) astContext.Idents.getAllocator().getTotalMemory());
5643
5644  // How much memory is used for selectors?
5645  createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Selectors,
5646    (unsigned long) astContext.Selectors.getTotalMemory());
5647
5648  // How much memory is used by ASTContext's side tables?
5649  createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST_SideTables,
5650    (unsigned long) astContext.getSideTableAllocatedMemory());
5651
5652  // How much memory is used for caching global code completion results?
5653  unsigned long completionBytes = 0;
5654  if (GlobalCodeCompletionAllocator *completionAllocator =
5655      astUnit->getCachedCompletionAllocator().getPtr()) {
5656    completionBytes = completionAllocator->getTotalMemory();
5657  }
5658  createCXTUResourceUsageEntry(*entries,
5659                               CXTUResourceUsage_GlobalCompletionResults,
5660                               completionBytes);
5661
5662  // How much memory is being used by SourceManager's content cache?
5663  createCXTUResourceUsageEntry(*entries,
5664          CXTUResourceUsage_SourceManagerContentCache,
5665          (unsigned long) astContext.getSourceManager().getContentCacheSize());
5666
5667  // How much memory is being used by the MemoryBuffer's in SourceManager?
5668  const SourceManager::MemoryBufferSizes &srcBufs =
5669    astUnit->getSourceManager().getMemoryBufferSizes();
5670
5671  createCXTUResourceUsageEntry(*entries,
5672                               CXTUResourceUsage_SourceManager_Membuffer_Malloc,
5673                               (unsigned long) srcBufs.malloc_bytes);
5674  createCXTUResourceUsageEntry(*entries,
5675                               CXTUResourceUsage_SourceManager_Membuffer_MMap,
5676                               (unsigned long) srcBufs.mmap_bytes);
5677  createCXTUResourceUsageEntry(*entries,
5678                               CXTUResourceUsage_SourceManager_DataStructures,
5679                               (unsigned long) astContext.getSourceManager()
5680                                .getDataStructureSizes());
5681
5682  // How much memory is being used by the ExternalASTSource?
5683  if (ExternalASTSource *esrc = astContext.getExternalSource()) {
5684    const ExternalASTSource::MemoryBufferSizes &sizes =
5685      esrc->getMemoryBufferSizes();
5686
5687    createCXTUResourceUsageEntry(*entries,
5688      CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc,
5689                                 (unsigned long) sizes.malloc_bytes);
5690    createCXTUResourceUsageEntry(*entries,
5691      CXTUResourceUsage_ExternalASTSource_Membuffer_MMap,
5692                                 (unsigned long) sizes.mmap_bytes);
5693  }
5694
5695  // How much memory is being used by the Preprocessor?
5696  Preprocessor &pp = astUnit->getPreprocessor();
5697  createCXTUResourceUsageEntry(*entries,
5698                               CXTUResourceUsage_Preprocessor,
5699                               pp.getTotalMemory());
5700
5701  if (PreprocessingRecord *pRec = pp.getPreprocessingRecord()) {
5702    createCXTUResourceUsageEntry(*entries,
5703                                 CXTUResourceUsage_PreprocessingRecord,
5704                                 pRec->getTotalMemory());
5705  }
5706
5707  createCXTUResourceUsageEntry(*entries,
5708                               CXTUResourceUsage_Preprocessor_HeaderSearch,
5709                               pp.getHeaderSearchInfo().getTotalMemory());
5710
5711  CXTUResourceUsage usage = { (void*) entries.get(),
5712                            (unsigned) entries->size(),
5713                            entries->size() ? &(*entries)[0] : 0 };
5714  entries.take();
5715  return usage;
5716}
5717
5718void clang_disposeCXTUResourceUsage(CXTUResourceUsage usage) {
5719  if (usage.data)
5720    delete (MemUsageEntries*) usage.data;
5721}
5722
5723} // end extern "C"
5724
5725void clang::PrintLibclangResourceUsage(CXTranslationUnit TU) {
5726  CXTUResourceUsage Usage = clang_getCXTUResourceUsage(TU);
5727  for (unsigned I = 0; I != Usage.numEntries; ++I)
5728    fprintf(stderr, "  %s: %lu\n",
5729            clang_getTUResourceUsageName(Usage.entries[I].kind),
5730            Usage.entries[I].amount);
5731
5732  clang_disposeCXTUResourceUsage(Usage);
5733}
5734
5735//===----------------------------------------------------------------------===//
5736// Misc. utility functions.
5737//===----------------------------------------------------------------------===//
5738
5739/// Default to using an 8 MB stack size on "safety" threads.
5740static unsigned SafetyStackThreadSize = 8 << 20;
5741
5742namespace clang {
5743
5744bool RunSafely(llvm::CrashRecoveryContext &CRC,
5745               void (*Fn)(void*), void *UserData,
5746               unsigned Size) {
5747  if (!Size)
5748    Size = GetSafetyThreadStackSize();
5749  if (Size)
5750    return CRC.RunSafelyOnThread(Fn, UserData, Size);
5751  return CRC.RunSafely(Fn, UserData);
5752}
5753
5754unsigned GetSafetyThreadStackSize() {
5755  return SafetyStackThreadSize;
5756}
5757
5758void SetSafetyThreadStackSize(unsigned Value) {
5759  SafetyStackThreadSize = Value;
5760}
5761
5762}
5763
5764extern "C" {
5765
5766CXString clang_getClangVersion() {
5767  return createCXString(getClangFullVersion());
5768}
5769
5770} // end: extern "C"
5771
5772