blob: a0e204d61fe52ad73730361e7135752f76a0b6eb [file] [log] [blame]
Ted Kremenekd2fa5662009-08-26 22:36:44 +00001//===- CIndex.cpp - Clang-C Source Indexing Library -----------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00007//
Ted Kremenekd2fa5662009-08-26 22:36:44 +00008//===----------------------------------------------------------------------===//
9//
Ted Kremenekab188932010-01-05 19:32:54 +000010// This file implements the main API hooks in the Clang-C Source Indexing
11// library.
Ted Kremenekd2fa5662009-08-26 22:36:44 +000012//
13//===----------------------------------------------------------------------===//
14
Ted Kremenekab188932010-01-05 19:32:54 +000015#include "CIndexer.h"
Ted Kremenek16c440a2010-01-15 20:35:54 +000016#include "CXCursor.h"
Ted Kremenek0a90d322010-11-17 23:24:11 +000017#include "CXTranslationUnit.h"
Ted Kremeneked122732010-11-16 01:56:27 +000018#include "CXString.h"
Ted Kremenek95f33552010-08-26 01:42:22 +000019#include "CXType.h"
Ted Kremeneka297de22010-01-25 22:34:44 +000020#include "CXSourceLocation.h"
Douglas Gregor5352ac02010-01-28 00:27:43 +000021#include "CIndexDiagnostic.h"
Ted Kremenekab188932010-01-05 19:32:54 +000022
Ted Kremenek04bb7162010-01-22 22:44:15 +000023#include "clang/Basic/Version.h"
Douglas Gregor936ea3b2010-01-28 00:56:43 +000024
Steve Naroff50398192009-08-28 15:28:48 +000025#include "clang/AST/DeclVisitor.h"
Steve Narofffb570422009-09-22 19:25:29 +000026#include "clang/AST/StmtVisitor.h"
Douglas Gregor7d0d40e2010-01-21 16:28:34 +000027#include "clang/AST/TypeLocVisitor.h"
Benjamin Kramerb846deb2010-04-12 19:45:50 +000028#include "clang/Basic/Diagnostic.h"
29#include "clang/Frontend/ASTUnit.h"
30#include "clang/Frontend/CompilerInstance.h"
Douglas Gregor936ea3b2010-01-28 00:56:43 +000031#include "clang/Frontend/FrontendDiagnostic.h"
Ted Kremenekd8210652010-01-06 23:43:31 +000032#include "clang/Lex/Lexer.h"
Benjamin Kramerb846deb2010-04-12 19:45:50 +000033#include "clang/Lex/PreprocessingRecord.h"
Douglas Gregor33e9abd2010-01-22 19:49:59 +000034#include "clang/Lex/Preprocessor.h"
Douglas Gregora67e03f2010-09-09 21:42:20 +000035#include "llvm/ADT/STLExtras.h"
Ted Kremenekd8c370c2010-11-02 23:10:24 +000036#include "llvm/ADT/Optional.h"
Douglas Gregorf5251602011-03-08 17:10:18 +000037#include "llvm/ADT/StringSwitch.h"
Ted Kremenekd8c370c2010-11-02 23:10:24 +000038#include "clang/Analysis/Support/SaveAndRestore.h"
Daniel Dunbarc7df4f32010-08-18 18:43:14 +000039#include "llvm/Support/CrashRecoveryContext.h"
Daniel Dunbar48615ff2010-10-08 19:30:33 +000040#include "llvm/Support/PrettyStackTrace.h"
Douglas Gregor02465752009-10-16 21:24:31 +000041#include "llvm/Support/MemoryBuffer.h"
Douglas Gregor358559d2010-10-02 22:49:11 +000042#include "llvm/Support/raw_ostream.h"
Douglas Gregor7a07fcb2010-08-09 21:00:09 +000043#include "llvm/Support/Timer.h"
Michael J. Spencer03013fa2010-11-29 18:12:39 +000044#include "llvm/Support/Mutex.h"
45#include "llvm/Support/Program.h"
46#include "llvm/Support/Signals.h"
47#include "llvm/Support/Threading.h"
Ted Kremenek37f1ea02010-11-15 23:11:54 +000048#include "llvm/Support/Compiler.h"
Ted Kremenekfc062212009-10-19 21:44:57 +000049
Steve Naroff50398192009-08-28 15:28:48 +000050using namespace clang;
Ted Kremenek16c440a2010-01-15 20:35:54 +000051using namespace clang::cxcursor;
Ted Kremenekee4db4f2010-02-17 00:41:08 +000052using namespace clang::cxstring;
Steve Naroff50398192009-08-28 15:28:48 +000053
Ted Kremeneka60ed472010-11-16 08:15:36 +000054static CXTranslationUnit MakeCXTranslationUnit(ASTUnit *TU) {
55 if (!TU)
56 return 0;
57 CXTranslationUnit D = new CXTranslationUnitImpl();
58 D->TUData = TU;
59 D->StringPool = createCXStringPool();
60 return D;
61}
62
Douglas Gregor33e9abd2010-01-22 19:49:59 +000063/// \brief The result of comparing two source ranges.
64enum RangeComparisonResult {
65 /// \brief Either the ranges overlap or one of the ranges is invalid.
66 RangeOverlap,
Ted Kremenekf0e23e82010-02-17 00:41:40 +000067
Douglas Gregor33e9abd2010-01-22 19:49:59 +000068 /// \brief The first range ends before the second range starts.
69 RangeBefore,
Ted Kremenekf0e23e82010-02-17 00:41:40 +000070
Douglas Gregor33e9abd2010-01-22 19:49:59 +000071 /// \brief The first range starts after the second range ends.
72 RangeAfter
73};
74
Ted Kremenekf0e23e82010-02-17 00:41:40 +000075/// \brief Compare two source ranges to determine their relative position in
Douglas Gregor33e9abd2010-01-22 19:49:59 +000076/// the translation unit.
Ted Kremenekf0e23e82010-02-17 00:41:40 +000077static RangeComparisonResult RangeCompare(SourceManager &SM,
78 SourceRange R1,
Douglas Gregor33e9abd2010-01-22 19:49:59 +000079 SourceRange R2) {
80 assert(R1.isValid() && "First range is invalid?");
81 assert(R2.isValid() && "Second range is invalid?");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +000082 if (R1.getEnd() != R2.getBegin() &&
Daniel Dunbard52864b2010-02-14 10:02:57 +000083 SM.isBeforeInTranslationUnit(R1.getEnd(), R2.getBegin()))
Douglas Gregor33e9abd2010-01-22 19:49:59 +000084 return RangeBefore;
Douglas Gregora8e5c5b2010-07-22 20:22:31 +000085 if (R2.getEnd() != R1.getBegin() &&
Daniel Dunbard52864b2010-02-14 10:02:57 +000086 SM.isBeforeInTranslationUnit(R2.getEnd(), R1.getBegin()))
Douglas Gregor33e9abd2010-01-22 19:49:59 +000087 return RangeAfter;
88 return RangeOverlap;
89}
90
Ted Kremenekfbd84ca2010-05-05 00:55:23 +000091/// \brief Determine if a source location falls within, before, or after a
92/// a given source range.
93static RangeComparisonResult LocationCompare(SourceManager &SM,
94 SourceLocation L, SourceRange R) {
95 assert(R.isValid() && "First range is invalid?");
96 assert(L.isValid() && "Second range is invalid?");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +000097 if (L == R.getBegin() || L == R.getEnd())
Ted Kremenekfbd84ca2010-05-05 00:55:23 +000098 return RangeOverlap;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +000099 if (SM.isBeforeInTranslationUnit(L, R.getBegin()))
100 return RangeBefore;
101 if (SM.isBeforeInTranslationUnit(R.getEnd(), L))
102 return RangeAfter;
103 return RangeOverlap;
104}
105
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000106/// \brief Translate a Clang source range into a CIndex source range.
107///
108/// Clang internally represents ranges where the end location points to the
109/// start of the token at the end. However, for external clients it is more
110/// useful to have a CXSourceRange be a proper half-open interval. This routine
111/// does the appropriate translation.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000112CXSourceRange cxloc::translateSourceRange(const SourceManager &SM,
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000113 const LangOptions &LangOpts,
Chris Lattner0a76aae2010-06-18 22:45:06 +0000114 const CharSourceRange &R) {
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000115 // We want the last character in this location, so we will adjust the
Douglas Gregor6a5a23f2010-03-19 21:51:54 +0000116 // location accordingly.
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000117 SourceLocation EndLoc = R.getEnd();
Douglas Gregora9b06d42010-11-09 06:24:54 +0000118 if (EndLoc.isValid() && EndLoc.isMacroID())
Douglas Gregorffcd9852011-04-20 21:16:21 +0000119 EndLoc = SM.getInstantiationRange(EndLoc).second;
Chris Lattner0a76aae2010-06-18 22:45:06 +0000120 if (R.isTokenRange() && !EndLoc.isInvalid() && EndLoc.isFileID()) {
Douglas Gregor6a5a23f2010-03-19 21:51:54 +0000121 unsigned Length = Lexer::MeasureTokenLength(EndLoc, SM, LangOpts);
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000122 EndLoc = EndLoc.getFileLocWithOffset(Length);
123 }
124
125 CXSourceRange Result = { { (void *)&SM, (void *)&LangOpts },
126 R.getBegin().getRawEncoding(),
127 EndLoc.getRawEncoding() };
128 return Result;
129}
Douglas Gregor1db19de2010-01-19 21:36:55 +0000130
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000131//===----------------------------------------------------------------------===//
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000132// Cursor visitor.
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000133//===----------------------------------------------------------------------===//
134
Steve Naroff89922f82009-08-31 00:59:03 +0000135namespace {
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000136
137class VisitorJob {
138public:
Ted Kremenekcdb4caf2010-11-12 21:34:12 +0000139 enum Kind { DeclVisitKind, StmtVisitKind, MemberExprPartsKind,
Ted Kremeneke4979cc2010-11-13 00:58:18 +0000140 TypeLocVisitKind, OverloadExprPartsKind,
Ted Kremenek60608ec2010-11-17 00:50:47 +0000141 DeclRefExprPartsKind, LabelRefVisitKind,
Ted Kremenekf64d8032010-11-18 00:02:32 +0000142 ExplicitTemplateArgsVisitKind,
143 NestedNameSpecifierVisitKind,
Douglas Gregorf3db29f2011-02-25 18:19:59 +0000144 NestedNameSpecifierLocVisitKind,
Ted Kremenekcdba6592010-11-18 00:42:18 +0000145 DeclarationNameInfoVisitKind,
Douglas Gregor94d96292011-01-19 20:34:17 +0000146 MemberRefVisitKind, SizeOfPackExprPartsKind };
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000147protected:
Ted Kremenekf64d8032010-11-18 00:02:32 +0000148 void *data[3];
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000149 CXCursor parent;
150 Kind K;
Ted Kremenekf64d8032010-11-18 00:02:32 +0000151 VisitorJob(CXCursor C, Kind k, void *d1, void *d2 = 0, void *d3 = 0)
152 : parent(C), K(k) {
153 data[0] = d1;
154 data[1] = d2;
155 data[2] = d3;
156 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000157public:
158 Kind getKind() const { return K; }
159 const CXCursor &getParent() const { return parent; }
160 static bool classof(VisitorJob *VJ) { return true; }
161};
162
163typedef llvm::SmallVector<VisitorJob, 10> VisitorWorkList;
164
Douglas Gregorb1373d02010-01-20 20:59:29 +0000165// Cursor visitor.
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000166class CursorVisitor : public DeclVisitor<CursorVisitor, bool>,
Ted Kremenekcdba6592010-11-18 00:42:18 +0000167 public TypeLocVisitor<CursorVisitor, bool>
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000168{
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000169 /// \brief The translation unit we are traversing.
Ted Kremeneka60ed472010-11-16 08:15:36 +0000170 CXTranslationUnit TU;
171 ASTUnit *AU;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000172
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000173 /// \brief The parent cursor whose children we are traversing.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000174 CXCursor Parent;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000175
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000176 /// \brief The declaration that serves at the parent of any statement or
177 /// expression nodes.
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000178 Decl *StmtParent;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000179
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000180 /// \brief The visitor function.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000181 CXCursorVisitor Visitor;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000182
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000183 /// \brief The opaque client data, to be passed along to the visitor.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000184 CXClientData ClientData;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000185
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000186 // MaxPCHLevel - the maximum PCH level of declarations that we will pass on
187 // to the visitor. Declarations with a PCH level greater than this value will
188 // be suppressed.
189 unsigned MaxPCHLevel;
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000190
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000191 /// \brief Whether we should visit the preprocessing record entries last,
192 /// after visiting other declarations.
193 bool VisitPreprocessorLast;
194
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000195 /// \brief When valid, a source range to which the cursor should restrict
196 /// its search.
197 SourceRange RegionOfInterest;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000198
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000199 // FIXME: Eventually remove. This part of a hack to support proper
200 // iteration over all Decls contained lexically within an ObjC container.
201 DeclContext::decl_iterator *DI_current;
202 DeclContext::decl_iterator DE_current;
203
Ted Kremenekd1ded662010-11-15 23:31:32 +0000204 // Cache of pre-allocated worklists for data-recursion walk of Stmts.
205 llvm::SmallVector<VisitorWorkList*, 5> WorkListFreeList;
206 llvm::SmallVector<VisitorWorkList*, 5> WorkListCache;
207
Douglas Gregorb1373d02010-01-20 20:59:29 +0000208 using DeclVisitor<CursorVisitor, bool>::Visit;
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000209 using TypeLocVisitor<CursorVisitor, bool>::Visit;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000210
211 /// \brief Determine whether this particular source range comes before, comes
212 /// after, or overlaps the region of interest.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000213 ///
Daniel Dunbard52864b2010-02-14 10:02:57 +0000214 /// \param R a half-open source range retrieved from the abstract syntax tree.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000215 RangeComparisonResult CompareRegionOfInterest(SourceRange R);
216
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000217 class SetParentRAII {
218 CXCursor &Parent;
219 Decl *&StmtParent;
220 CXCursor OldParent;
221
222 public:
223 SetParentRAII(CXCursor &Parent, Decl *&StmtParent, CXCursor NewParent)
224 : Parent(Parent), StmtParent(StmtParent), OldParent(Parent)
225 {
226 Parent = NewParent;
227 if (clang_isDeclaration(Parent.kind))
228 StmtParent = getCursorDecl(Parent);
229 }
230
231 ~SetParentRAII() {
232 Parent = OldParent;
233 if (clang_isDeclaration(Parent.kind))
234 StmtParent = getCursorDecl(Parent);
235 }
236 };
237
Steve Naroff89922f82009-08-31 00:59:03 +0000238public:
Ted Kremeneka60ed472010-11-16 08:15:36 +0000239 CursorVisitor(CXTranslationUnit TU, CXCursorVisitor Visitor,
240 CXClientData ClientData,
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000241 unsigned MaxPCHLevel,
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000242 bool VisitPreprocessorLast,
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000243 SourceRange RegionOfInterest = SourceRange())
Ted Kremeneka60ed472010-11-16 08:15:36 +0000244 : TU(TU), AU(static_cast<ASTUnit*>(TU->TUData)),
245 Visitor(Visitor), ClientData(ClientData),
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000246 MaxPCHLevel(MaxPCHLevel), VisitPreprocessorLast(VisitPreprocessorLast),
247 RegionOfInterest(RegionOfInterest), DI_current(0)
Douglas Gregorb1373d02010-01-20 20:59:29 +0000248 {
249 Parent.kind = CXCursor_NoDeclFound;
250 Parent.data[0] = 0;
251 Parent.data[1] = 0;
252 Parent.data[2] = 0;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000253 StmtParent = 0;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000254 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000255
Ted Kremenekd1ded662010-11-15 23:31:32 +0000256 ~CursorVisitor() {
257 // Free the pre-allocated worklists for data-recursion.
258 for (llvm::SmallVectorImpl<VisitorWorkList*>::iterator
259 I = WorkListCache.begin(), E = WorkListCache.end(); I != E; ++I) {
260 delete *I;
261 }
262 }
263
Ted Kremeneka60ed472010-11-16 08:15:36 +0000264 ASTUnit *getASTUnit() const { return static_cast<ASTUnit*>(TU->TUData); }
265 CXTranslationUnit getTU() const { return TU; }
Ted Kremenekab979612010-11-11 08:05:23 +0000266
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000267 bool Visit(CXCursor Cursor, bool CheckedRegionOfInterest = false);
Douglas Gregor788f5a12010-03-20 00:41:21 +0000268
269 std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
270 getPreprocessedEntities();
271
Douglas Gregorb1373d02010-01-20 20:59:29 +0000272 bool VisitChildren(CXCursor Parent);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000273
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000274 // Declaration visitors
Richard Smith162e1c12011-04-15 14:24:37 +0000275 bool VisitTypeAliasDecl(TypeAliasDecl *D);
Ted Kremenek09dfa372010-02-18 05:46:33 +0000276 bool VisitAttributes(Decl *D);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000277 bool VisitBlockDecl(BlockDecl *B);
Ted Kremenek3064ef92010-08-27 21:34:58 +0000278 bool VisitCXXRecordDecl(CXXRecordDecl *D);
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000279 llvm::Optional<bool> shouldVisitCursor(CXCursor C);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000280 bool VisitDeclContext(DeclContext *DC);
Ted Kremenek4540c9c2010-02-18 18:47:08 +0000281 bool VisitTranslationUnitDecl(TranslationUnitDecl *D);
282 bool VisitTypedefDecl(TypedefDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000283 bool VisitTagDecl(TagDecl *D);
Douglas Gregor0ab1e9f2010-09-01 17:32:36 +0000284 bool VisitClassTemplateSpecializationDecl(ClassTemplateSpecializationDecl *D);
Douglas Gregor74dbe642010-08-31 19:31:58 +0000285 bool VisitClassTemplatePartialSpecializationDecl(
286 ClassTemplatePartialSpecializationDecl *D);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000287 bool VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000288 bool VisitEnumConstantDecl(EnumConstantDecl *D);
289 bool VisitDeclaratorDecl(DeclaratorDecl *DD);
290 bool VisitFunctionDecl(FunctionDecl *ND);
291 bool VisitFieldDecl(FieldDecl *D);
Ted Kremenek4540c9c2010-02-18 18:47:08 +0000292 bool VisitVarDecl(VarDecl *);
Douglas Gregor84b51d72010-09-01 20:16:53 +0000293 bool VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000294 bool VisitFunctionTemplateDecl(FunctionTemplateDecl *D);
Douglas Gregor39d6f072010-08-31 19:02:00 +0000295 bool VisitClassTemplateDecl(ClassTemplateDecl *D);
Douglas Gregor84b51d72010-09-01 20:16:53 +0000296 bool VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000297 bool VisitObjCMethodDecl(ObjCMethodDecl *ND);
298 bool VisitObjCContainerDecl(ObjCContainerDecl *D);
299 bool VisitObjCCategoryDecl(ObjCCategoryDecl *ND);
300 bool VisitObjCProtocolDecl(ObjCProtocolDecl *PID);
Ted Kremenek23173d72010-05-18 21:09:07 +0000301 bool VisitObjCPropertyDecl(ObjCPropertyDecl *PD);
Ted Kremenek79758f62010-02-18 22:36:18 +0000302 bool VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
303 bool VisitObjCImplDecl(ObjCImplDecl *D);
304 bool VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
305 bool VisitObjCImplementationDecl(ObjCImplementationDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000306 // FIXME: ObjCCompatibleAliasDecl requires aliased-class locations.
307 bool VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D);
308 bool VisitObjCClassDecl(ObjCClassDecl *D);
Douglas Gregora4ffd852010-11-17 01:03:52 +0000309 bool VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *PD);
Ted Kremeneka0536d82010-05-07 01:04:29 +0000310 bool VisitLinkageSpecDecl(LinkageSpecDecl *D);
Ted Kremenek8f06e0e2010-05-06 23:38:21 +0000311 bool VisitNamespaceDecl(NamespaceDecl *D);
Douglas Gregor69319002010-08-31 23:48:11 +0000312 bool VisitNamespaceAliasDecl(NamespaceAliasDecl *D);
Douglas Gregor0a35bce2010-09-01 03:07:18 +0000313 bool VisitUsingDirectiveDecl(UsingDirectiveDecl *D);
Douglas Gregor7e242562010-09-01 19:52:22 +0000314 bool VisitUsingDecl(UsingDecl *D);
315 bool VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D);
316 bool VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D);
Douglas Gregor0a35bce2010-09-01 03:07:18 +0000317
Douglas Gregor01829d32010-08-31 14:41:23 +0000318 // Name visitor
319 bool VisitDeclarationNameInfo(DeclarationNameInfo Name);
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000320 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS, SourceRange Range);
Douglas Gregordc355712011-02-25 00:36:19 +0000321 bool VisitNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS);
Douglas Gregor01829d32010-08-31 14:41:23 +0000322
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000323 // Template visitors
324 bool VisitTemplateParameters(const TemplateParameterList *Params);
Douglas Gregor0b36e612010-08-31 20:37:03 +0000325 bool VisitTemplateName(TemplateName Name, SourceLocation Loc);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000326 bool VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL);
327
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000328 // Type visitors
Douglas Gregor01829d32010-08-31 14:41:23 +0000329 bool VisitQualifiedTypeLoc(QualifiedTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000330 bool VisitBuiltinTypeLoc(BuiltinTypeLoc TL);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000331 bool VisitTypedefTypeLoc(TypedefTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000332 bool VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL);
333 bool VisitTagTypeLoc(TagTypeLoc TL);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000334 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000335 bool VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL);
John McCallc12c5bb2010-05-15 11:32:37 +0000336 bool VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000337 bool VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL);
Abramo Bagnara075f8f12010-12-10 16:29:40 +0000338 bool VisitParenTypeLoc(ParenTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000339 bool VisitPointerTypeLoc(PointerTypeLoc TL);
340 bool VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL);
341 bool VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL);
342 bool VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL);
343 bool VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL);
Douglas Gregor01829d32010-08-31 14:41:23 +0000344 bool VisitFunctionTypeLoc(FunctionTypeLoc TL, bool SkipResultType = false);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000345 bool VisitArrayTypeLoc(ArrayTypeLoc TL);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000346 bool VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL);
Douglas Gregor2332c112010-01-21 20:48:56 +0000347 // FIXME: Implement visitors here when the unimplemented TypeLocs get
348 // implemented
349 bool VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL);
Douglas Gregor7536dd52010-12-20 02:24:11 +0000350 bool VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL);
Douglas Gregor2332c112010-01-21 20:48:56 +0000351 bool VisitTypeOfTypeLoc(TypeOfTypeLoc TL);
Douglas Gregor2494dd02011-03-01 01:34:45 +0000352 bool VisitDependentNameTypeLoc(DependentNameTypeLoc TL);
Douglas Gregor94fdffa2011-03-01 20:11:18 +0000353 bool VisitDependentTemplateSpecializationTypeLoc(
354 DependentTemplateSpecializationTypeLoc TL);
Douglas Gregor9e876872011-03-01 18:12:44 +0000355 bool VisitElaboratedTypeLoc(ElaboratedTypeLoc TL);
Douglas Gregor2494dd02011-03-01 01:34:45 +0000356
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000357 // Data-recursive visitor functions.
358 bool IsInRegionOfInterest(CXCursor C);
359 bool RunVisitorWorkList(VisitorWorkList &WL);
360 void EnqueueWorkList(VisitorWorkList &WL, Stmt *S);
Ted Kremenekcdba6592010-11-18 00:42:18 +0000361 LLVM_ATTRIBUTE_NOINLINE bool Visit(Stmt *S);
Steve Naroff89922f82009-08-31 00:59:03 +0000362};
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000363
Ted Kremenekab188932010-01-05 19:32:54 +0000364} // end anonymous namespace
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000365
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000366static SourceRange getRawCursorExtent(CXCursor C);
Douglas Gregor66537982010-11-17 17:14:07 +0000367static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr);
368
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000369
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000370RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000371 return RangeCompare(AU->getSourceManager(), R, RegionOfInterest);
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000372}
373
Douglas Gregorb1373d02010-01-20 20:59:29 +0000374/// \brief Visit the given cursor and, if requested by the visitor,
375/// its children.
376///
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000377/// \param Cursor the cursor to visit.
378///
379/// \param CheckRegionOfInterest if true, then the caller already checked that
380/// this cursor is within the region of interest.
381///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000382/// \returns true if the visitation should be aborted, false if it
383/// should continue.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000384bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
Douglas Gregorb1373d02010-01-20 20:59:29 +0000385 if (clang_isInvalid(Cursor.kind))
386 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000387
Douglas Gregorb1373d02010-01-20 20:59:29 +0000388 if (clang_isDeclaration(Cursor.kind)) {
389 Decl *D = getCursorDecl(Cursor);
390 assert(D && "Invalid declaration cursor");
391 if (D->getPCHLevel() > MaxPCHLevel)
392 return false;
393
394 if (D->isImplicit())
395 return false;
396 }
397
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000398 // If we have a range of interest, and this cursor doesn't intersect with it,
399 // we're done.
400 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000401 SourceRange Range = getRawCursorExtent(Cursor);
Daniel Dunbarf408f322010-02-14 08:32:05 +0000402 if (Range.isInvalid() || CompareRegionOfInterest(Range))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000403 return false;
404 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000405
Douglas Gregorb1373d02010-01-20 20:59:29 +0000406 switch (Visitor(Cursor, Parent, ClientData)) {
407 case CXChildVisit_Break:
408 return true;
409
410 case CXChildVisit_Continue:
411 return false;
412
413 case CXChildVisit_Recurse:
414 return VisitChildren(Cursor);
415 }
416
Douglas Gregorfd643772010-01-25 16:45:46 +0000417 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000418}
419
Douglas Gregor788f5a12010-03-20 00:41:21 +0000420std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
421CursorVisitor::getPreprocessedEntities() {
422 PreprocessingRecord &PPRec
Ted Kremeneka60ed472010-11-16 08:15:36 +0000423 = *AU->getPreprocessor().getPreprocessingRecord();
Douglas Gregor788f5a12010-03-20 00:41:21 +0000424
425 bool OnlyLocalDecls
Douglas Gregor32038bb2010-12-21 19:07:48 +0000426 = !AU->isMainFileAST() && AU->getOnlyLocalDecls();
427
428 if (OnlyLocalDecls && RegionOfInterest.isValid()) {
429 // If we would only look at local declarations but we have a region of
430 // interest, check whether that region of interest is in the main file.
431 // If not, we should traverse all declarations.
432 // FIXME: My kingdom for a proper binary search approach to finding
433 // cursors!
434 std::pair<FileID, unsigned> Location
435 = AU->getSourceManager().getDecomposedInstantiationLoc(
436 RegionOfInterest.getBegin());
437 if (Location.first != AU->getSourceManager().getMainFileID())
438 OnlyLocalDecls = false;
439 }
Douglas Gregor788f5a12010-03-20 00:41:21 +0000440
Douglas Gregor89d99802010-11-30 06:16:57 +0000441 PreprocessingRecord::iterator StartEntity, EndEntity;
442 if (OnlyLocalDecls) {
443 StartEntity = AU->pp_entity_begin();
444 EndEntity = AU->pp_entity_end();
445 } else {
446 StartEntity = PPRec.begin();
447 EndEntity = PPRec.end();
448 }
449
Douglas Gregor788f5a12010-03-20 00:41:21 +0000450 // There is no region of interest; we have to walk everything.
451 if (RegionOfInterest.isInvalid())
Douglas Gregor89d99802010-11-30 06:16:57 +0000452 return std::make_pair(StartEntity, EndEntity);
Douglas Gregor788f5a12010-03-20 00:41:21 +0000453
454 // Find the file in which the region of interest lands.
Ted Kremeneka60ed472010-11-16 08:15:36 +0000455 SourceManager &SM = AU->getSourceManager();
Douglas Gregor788f5a12010-03-20 00:41:21 +0000456 std::pair<FileID, unsigned> Begin
457 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getBegin());
458 std::pair<FileID, unsigned> End
459 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getEnd());
460
461 // The region of interest spans files; we have to walk everything.
462 if (Begin.first != End.first)
Douglas Gregor89d99802010-11-30 06:16:57 +0000463 return std::make_pair(StartEntity, EndEntity);
Douglas Gregor788f5a12010-03-20 00:41:21 +0000464
465 ASTUnit::PreprocessedEntitiesByFileMap &ByFileMap
Ted Kremeneka60ed472010-11-16 08:15:36 +0000466 = AU->getPreprocessedEntitiesByFile();
Douglas Gregor788f5a12010-03-20 00:41:21 +0000467 if (ByFileMap.empty()) {
468 // Build the mapping from files to sets of preprocessed entities.
Douglas Gregor89d99802010-11-30 06:16:57 +0000469 for (PreprocessingRecord::iterator E = StartEntity; E != EndEntity; ++E) {
Douglas Gregor788f5a12010-03-20 00:41:21 +0000470 std::pair<FileID, unsigned> P
471 = SM.getDecomposedInstantiationLoc((*E)->getSourceRange().getBegin());
Douglas Gregor89d99802010-11-30 06:16:57 +0000472
Douglas Gregor788f5a12010-03-20 00:41:21 +0000473 ByFileMap[P.first].push_back(*E);
474 }
475 }
476
477 return std::make_pair(ByFileMap[Begin.first].begin(),
478 ByFileMap[Begin.first].end());
479}
480
Douglas Gregorb1373d02010-01-20 20:59:29 +0000481/// \brief Visit the children of the given cursor.
Ted Kremeneka60ed472010-11-16 08:15:36 +0000482///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000483/// \returns true if the visitation should be aborted, false if it
484/// should continue.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000485bool CursorVisitor::VisitChildren(CXCursor Cursor) {
Douglas Gregorc314aa42011-03-02 19:17:03 +0000486 if (clang_isReference(Cursor.kind) &&
487 Cursor.kind != CXCursor_CXXBaseSpecifier) {
Douglas Gregora59e3902010-01-21 23:27:09 +0000488 // By definition, references have no children.
489 return false;
490 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000491
492 // Set the Parent field to Cursor, then back to its old value once we're
Douglas Gregorb1373d02010-01-20 20:59:29 +0000493 // done.
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000494 SetParentRAII SetParent(Parent, StmtParent, Cursor);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000495
Douglas Gregorb1373d02010-01-20 20:59:29 +0000496 if (clang_isDeclaration(Cursor.kind)) {
497 Decl *D = getCursorDecl(Cursor);
Douglas Gregor06d9b1a2011-04-14 21:41:34 +0000498 if (!D)
499 return false;
500
Ted Kremenek539311e2010-02-18 18:47:01 +0000501 return VisitAttributes(D) || Visit(D);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000502 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000503
Douglas Gregor06d9b1a2011-04-14 21:41:34 +0000504 if (clang_isStatement(Cursor.kind)) {
505 if (Stmt *S = getCursorStmt(Cursor))
506 return Visit(S);
507
508 return false;
509 }
510
511 if (clang_isExpression(Cursor.kind)) {
512 if (Expr *E = getCursorExpr(Cursor))
513 return Visit(E);
514
515 return false;
516 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000517
Douglas Gregorb1373d02010-01-20 20:59:29 +0000518 if (clang_isTranslationUnit(Cursor.kind)) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000519 CXTranslationUnit tu = getCursorTU(Cursor);
520 ASTUnit *CXXUnit = static_cast<ASTUnit*>(tu->TUData);
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000521
522 int VisitOrder[2] = { VisitPreprocessorLast, !VisitPreprocessorLast };
523 for (unsigned I = 0; I != 2; ++I) {
524 if (VisitOrder[I]) {
525 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
526 RegionOfInterest.isInvalid()) {
527 for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(),
528 TLEnd = CXXUnit->top_level_end();
529 TL != TLEnd; ++TL) {
530 if (Visit(MakeCXCursor(*TL, tu), true))
531 return true;
532 }
533 } else if (VisitDeclContext(
534 CXXUnit->getASTContext().getTranslationUnitDecl()))
Douglas Gregor7b691f332010-01-20 21:13:59 +0000535 return true;
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000536 continue;
Douglas Gregor7b691f332010-01-20 21:13:59 +0000537 }
Bob Wilson3178cb62010-03-19 03:57:57 +0000538
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000539 // Walk the preprocessing record.
540 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
541 // FIXME: Once we have the ability to deserialize a preprocessing record,
542 // do so.
543 PreprocessingRecord::iterator E, EEnd;
544 for (llvm::tie(E, EEnd) = getPreprocessedEntities(); E != EEnd; ++E) {
545 if (MacroInstantiation *MI = dyn_cast<MacroInstantiation>(*E)) {
546 if (Visit(MakeMacroInstantiationCursor(MI, tu)))
547 return true;
548
549 continue;
550 }
Douglas Gregor788f5a12010-03-20 00:41:21 +0000551
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000552 if (MacroDefinition *MD = dyn_cast<MacroDefinition>(*E)) {
553 if (Visit(MakeMacroDefinitionCursor(MD, tu)))
554 return true;
555
556 continue;
557 }
Douglas Gregor0396f462010-03-19 05:22:59 +0000558
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000559 if (InclusionDirective *ID = dyn_cast<InclusionDirective>(*E)) {
560 if (Visit(MakeInclusionDirectiveCursor(ID, tu)))
561 return true;
562
563 continue;
564 }
Douglas Gregorecdcb882010-10-20 22:00:55 +0000565 }
Douglas Gregor0396f462010-03-19 05:22:59 +0000566 }
567 }
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000568
Douglas Gregor7b691f332010-01-20 21:13:59 +0000569 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000570 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000571
Douglas Gregorc314aa42011-03-02 19:17:03 +0000572 if (Cursor.kind == CXCursor_CXXBaseSpecifier) {
573 if (CXXBaseSpecifier *Base = getCursorCXXBaseSpecifier(Cursor)) {
574 if (TypeSourceInfo *BaseTSInfo = Base->getTypeSourceInfo()) {
575 return Visit(BaseTSInfo->getTypeLoc());
576 }
577 }
578 }
579
Douglas Gregorb1373d02010-01-20 20:59:29 +0000580 // Nothing to visit at the moment.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000581 return false;
582}
583
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000584bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
Douglas Gregor13c8ccb2011-04-22 23:49:24 +0000585 if (TypeSourceInfo *TSInfo = B->getSignatureAsWritten())
586 if (Visit(TSInfo->getTypeLoc()))
587 return true;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000588
Ted Kremenek664cffd2010-07-22 11:30:19 +0000589 if (Stmt *Body = B->getBody())
590 return Visit(MakeCXCursor(Body, StmtParent, TU));
591
592 return false;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000593}
594
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000595llvm::Optional<bool> CursorVisitor::shouldVisitCursor(CXCursor Cursor) {
596 if (RegionOfInterest.isValid()) {
Douglas Gregor66537982010-11-17 17:14:07 +0000597 SourceRange Range = getFullCursorExtent(Cursor, AU->getSourceManager());
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000598 if (Range.isInvalid())
599 return llvm::Optional<bool>();
Douglas Gregor66537982010-11-17 17:14:07 +0000600
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000601 switch (CompareRegionOfInterest(Range)) {
602 case RangeBefore:
603 // This declaration comes before the region of interest; skip it.
604 return llvm::Optional<bool>();
605
606 case RangeAfter:
607 // This declaration comes after the region of interest; we're done.
608 return false;
609
610 case RangeOverlap:
611 // This declaration overlaps the region of interest; visit it.
612 break;
613 }
614 }
615 return true;
616}
617
618bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
619 DeclContext::decl_iterator I = DC->decls_begin(), E = DC->decls_end();
620
621 // FIXME: Eventually remove. This part of a hack to support proper
622 // iteration over all Decls contained lexically within an ObjC container.
623 SaveAndRestore<DeclContext::decl_iterator*> DI_saved(DI_current, &I);
624 SaveAndRestore<DeclContext::decl_iterator> DE_saved(DE_current, E);
625
626 for ( ; I != E; ++I) {
Ted Kremenek23173d72010-05-18 21:09:07 +0000627 Decl *D = *I;
628 if (D->getLexicalDeclContext() != DC)
629 continue;
Ted Kremenek23173d72010-05-18 21:09:07 +0000630 CXCursor Cursor = MakeCXCursor(D, TU);
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000631 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
632 if (!V.hasValue())
633 continue;
634 if (!V.getValue())
635 return false;
Daniel Dunbard52864b2010-02-14 10:02:57 +0000636 if (Visit(Cursor, true))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000637 return true;
638 }
Douglas Gregorb1373d02010-01-20 20:59:29 +0000639 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000640}
641
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000642bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
643 llvm_unreachable("Translation units are visited directly by Visit()");
644 return false;
645}
646
Richard Smith162e1c12011-04-15 14:24:37 +0000647bool CursorVisitor::VisitTypeAliasDecl(TypeAliasDecl *D) {
648 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
649 return Visit(TSInfo->getTypeLoc());
650
651 return false;
652}
653
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000654bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
655 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
656 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000657
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000658 return false;
659}
660
661bool CursorVisitor::VisitTagDecl(TagDecl *D) {
662 return VisitDeclContext(D);
663}
664
Douglas Gregor0ab1e9f2010-09-01 17:32:36 +0000665bool CursorVisitor::VisitClassTemplateSpecializationDecl(
666 ClassTemplateSpecializationDecl *D) {
667 bool ShouldVisitBody = false;
668 switch (D->getSpecializationKind()) {
669 case TSK_Undeclared:
670 case TSK_ImplicitInstantiation:
671 // Nothing to visit
672 return false;
673
674 case TSK_ExplicitInstantiationDeclaration:
675 case TSK_ExplicitInstantiationDefinition:
676 break;
677
678 case TSK_ExplicitSpecialization:
679 ShouldVisitBody = true;
680 break;
681 }
682
683 // Visit the template arguments used in the specialization.
684 if (TypeSourceInfo *SpecType = D->getTypeAsWritten()) {
685 TypeLoc TL = SpecType->getTypeLoc();
686 if (TemplateSpecializationTypeLoc *TSTLoc
687 = dyn_cast<TemplateSpecializationTypeLoc>(&TL)) {
688 for (unsigned I = 0, N = TSTLoc->getNumArgs(); I != N; ++I)
689 if (VisitTemplateArgumentLoc(TSTLoc->getArgLoc(I)))
690 return true;
691 }
692 }
693
694 if (ShouldVisitBody && VisitCXXRecordDecl(D))
695 return true;
696
697 return false;
698}
699
Douglas Gregor74dbe642010-08-31 19:31:58 +0000700bool CursorVisitor::VisitClassTemplatePartialSpecializationDecl(
701 ClassTemplatePartialSpecializationDecl *D) {
702 // FIXME: Visit the "outer" template parameter lists on the TagDecl
703 // before visiting these template parameters.
704 if (VisitTemplateParameters(D->getTemplateParameters()))
705 return true;
706
707 // Visit the partial specialization arguments.
708 const TemplateArgumentLoc *TemplateArgs = D->getTemplateArgsAsWritten();
709 for (unsigned I = 0, N = D->getNumTemplateArgsAsWritten(); I != N; ++I)
710 if (VisitTemplateArgumentLoc(TemplateArgs[I]))
711 return true;
712
713 return VisitCXXRecordDecl(D);
714}
715
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000716bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
Douglas Gregor84b51d72010-09-01 20:16:53 +0000717 // Visit the default argument.
718 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
719 if (TypeSourceInfo *DefArg = D->getDefaultArgumentInfo())
720 if (Visit(DefArg->getTypeLoc()))
721 return true;
722
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000723 return false;
724}
725
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000726bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
727 if (Expr *Init = D->getInitExpr())
728 return Visit(MakeCXCursor(Init, StmtParent, TU));
729 return false;
730}
731
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000732bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
733 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
734 if (Visit(TSInfo->getTypeLoc()))
735 return true;
736
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000737 // Visit the nested-name-specifier, if present.
738 if (NestedNameSpecifierLoc QualifierLoc = DD->getQualifierLoc())
739 if (VisitNestedNameSpecifierLoc(QualifierLoc))
740 return true;
741
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000742 return false;
743}
744
Douglas Gregora67e03f2010-09-09 21:42:20 +0000745/// \brief Compare two base or member initializers based on their source order.
Sean Huntcbb67482011-01-08 20:30:50 +0000746static int CompareCXXCtorInitializers(const void* Xp, const void *Yp) {
747 CXXCtorInitializer const * const *X
748 = static_cast<CXXCtorInitializer const * const *>(Xp);
749 CXXCtorInitializer const * const *Y
750 = static_cast<CXXCtorInitializer const * const *>(Yp);
Douglas Gregora67e03f2010-09-09 21:42:20 +0000751
752 if ((*X)->getSourceOrder() < (*Y)->getSourceOrder())
753 return -1;
754 else if ((*X)->getSourceOrder() > (*Y)->getSourceOrder())
755 return 1;
756 else
757 return 0;
758}
759
Douglas Gregorb1373d02010-01-20 20:59:29 +0000760bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Douglas Gregor01829d32010-08-31 14:41:23 +0000761 if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) {
762 // Visit the function declaration's syntactic components in the order
763 // written. This requires a bit of work.
Abramo Bagnara723df242010-12-14 22:11:44 +0000764 TypeLoc TL = TSInfo->getTypeLoc().IgnoreParens();
Douglas Gregor01829d32010-08-31 14:41:23 +0000765 FunctionTypeLoc *FTL = dyn_cast<FunctionTypeLoc>(&TL);
766
767 // If we have a function declared directly (without the use of a typedef),
768 // visit just the return type. Otherwise, just visit the function's type
769 // now.
770 if ((FTL && !isa<CXXConversionDecl>(ND) && Visit(FTL->getResultLoc())) ||
771 (!FTL && Visit(TL)))
772 return true;
773
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000774 // Visit the nested-name-specifier, if present.
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000775 if (NestedNameSpecifierLoc QualifierLoc = ND->getQualifierLoc())
776 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000777 return true;
Douglas Gregor01829d32010-08-31 14:41:23 +0000778
779 // Visit the declaration name.
780 if (VisitDeclarationNameInfo(ND->getNameInfo()))
781 return true;
782
783 // FIXME: Visit explicitly-specified template arguments!
784
785 // Visit the function parameters, if we have a function type.
786 if (FTL && VisitFunctionTypeLoc(*FTL, true))
787 return true;
788
789 // FIXME: Attributes?
790 }
791
Francois Pichet8387e2a2011-04-22 22:18:13 +0000792 if (ND->isThisDeclarationADefinition() && !ND->isLateTemplateParsed()) {
Douglas Gregora67e03f2010-09-09 21:42:20 +0000793 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ND)) {
794 // Find the initializers that were written in the source.
Sean Huntcbb67482011-01-08 20:30:50 +0000795 llvm::SmallVector<CXXCtorInitializer *, 4> WrittenInits;
Douglas Gregora67e03f2010-09-09 21:42:20 +0000796 for (CXXConstructorDecl::init_iterator I = Constructor->init_begin(),
797 IEnd = Constructor->init_end();
798 I != IEnd; ++I) {
799 if (!(*I)->isWritten())
800 continue;
801
802 WrittenInits.push_back(*I);
803 }
804
805 // Sort the initializers in source order
806 llvm::array_pod_sort(WrittenInits.begin(), WrittenInits.end(),
Sean Huntcbb67482011-01-08 20:30:50 +0000807 &CompareCXXCtorInitializers);
Douglas Gregora67e03f2010-09-09 21:42:20 +0000808
809 // Visit the initializers in source order
810 for (unsigned I = 0, N = WrittenInits.size(); I != N; ++I) {
Sean Huntcbb67482011-01-08 20:30:50 +0000811 CXXCtorInitializer *Init = WrittenInits[I];
Francois Pichet00eb3f92010-12-04 09:14:42 +0000812 if (Init->isAnyMemberInitializer()) {
813 if (Visit(MakeCursorMemberRef(Init->getAnyMember(),
Douglas Gregora67e03f2010-09-09 21:42:20 +0000814 Init->getMemberLocation(), TU)))
815 return true;
816 } else if (TypeSourceInfo *BaseInfo = Init->getBaseClassInfo()) {
817 if (Visit(BaseInfo->getTypeLoc()))
818 return true;
819 }
820
821 // Visit the initializer value.
822 if (Expr *Initializer = Init->getInit())
823 if (Visit(MakeCXCursor(Initializer, ND, TU)))
824 return true;
825 }
826 }
827
828 if (Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
829 return true;
830 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000831
Douglas Gregorb1373d02010-01-20 20:59:29 +0000832 return false;
833}
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000834
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000835bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
836 if (VisitDeclaratorDecl(D))
837 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000838
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000839 if (Expr *BitWidth = D->getBitWidth())
840 return Visit(MakeCXCursor(BitWidth, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000841
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000842 return false;
843}
844
845bool CursorVisitor::VisitVarDecl(VarDecl *D) {
846 if (VisitDeclaratorDecl(D))
847 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000848
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000849 if (Expr *Init = D->getInit())
850 return Visit(MakeCXCursor(Init, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000851
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000852 return false;
853}
854
Douglas Gregor84b51d72010-09-01 20:16:53 +0000855bool CursorVisitor::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
856 if (VisitDeclaratorDecl(D))
857 return true;
858
859 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
860 if (Expr *DefArg = D->getDefaultArgument())
861 return Visit(MakeCXCursor(DefArg, StmtParent, TU));
862
863 return false;
864}
865
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000866bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
867 // FIXME: Visit the "outer" template parameter lists on the FunctionDecl
868 // before visiting these template parameters.
869 if (VisitTemplateParameters(D->getTemplateParameters()))
870 return true;
871
872 return VisitFunctionDecl(D->getTemplatedDecl());
873}
874
Douglas Gregor39d6f072010-08-31 19:02:00 +0000875bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) {
876 // FIXME: Visit the "outer" template parameter lists on the TagDecl
877 // before visiting these template parameters.
878 if (VisitTemplateParameters(D->getTemplateParameters()))
879 return true;
880
881 return VisitCXXRecordDecl(D->getTemplatedDecl());
882}
883
Douglas Gregor84b51d72010-09-01 20:16:53 +0000884bool CursorVisitor::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
885 if (VisitTemplateParameters(D->getTemplateParameters()))
886 return true;
887
888 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited() &&
889 VisitTemplateArgumentLoc(D->getDefaultArgument()))
890 return true;
891
892 return false;
893}
894
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000895bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
Douglas Gregor4bc1cb62010-03-08 14:59:44 +0000896 if (TypeSourceInfo *TSInfo = ND->getResultTypeSourceInfo())
897 if (Visit(TSInfo->getTypeLoc()))
898 return true;
899
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000900 for (ObjCMethodDecl::param_iterator P = ND->param_begin(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000901 PEnd = ND->param_end();
902 P != PEnd; ++P) {
903 if (Visit(MakeCXCursor(*P, TU)))
904 return true;
905 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000906
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000907 if (ND->isThisDeclarationADefinition() &&
908 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
909 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000910
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000911 return false;
912}
913
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000914namespace {
915 struct ContainerDeclsSort {
916 SourceManager &SM;
917 ContainerDeclsSort(SourceManager &sm) : SM(sm) {}
918 bool operator()(Decl *A, Decl *B) {
919 SourceLocation L_A = A->getLocStart();
920 SourceLocation L_B = B->getLocStart();
921 assert(L_A.isValid() && L_B.isValid());
922 return SM.isBeforeInTranslationUnit(L_A, L_B);
923 }
924 };
925}
926
Douglas Gregora59e3902010-01-21 23:27:09 +0000927bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000928 // FIXME: Eventually convert back to just 'VisitDeclContext()'. Essentially
929 // an @implementation can lexically contain Decls that are not properly
930 // nested in the AST. When we identify such cases, we need to retrofit
931 // this nesting here.
932 if (!DI_current)
933 return VisitDeclContext(D);
934
935 // Scan the Decls that immediately come after the container
936 // in the current DeclContext. If any fall within the
937 // container's lexical region, stash them into a vector
938 // for later processing.
939 llvm::SmallVector<Decl *, 24> DeclsInContainer;
940 SourceLocation EndLoc = D->getSourceRange().getEnd();
Ted Kremeneka60ed472010-11-16 08:15:36 +0000941 SourceManager &SM = AU->getSourceManager();
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000942 if (EndLoc.isValid()) {
943 DeclContext::decl_iterator next = *DI_current;
944 while (++next != DE_current) {
945 Decl *D_next = *next;
946 if (!D_next)
947 break;
948 SourceLocation L = D_next->getLocStart();
949 if (!L.isValid())
950 break;
951 if (SM.isBeforeInTranslationUnit(L, EndLoc)) {
952 *DI_current = next;
953 DeclsInContainer.push_back(D_next);
954 continue;
955 }
956 break;
957 }
958 }
959
960 // The common case.
961 if (DeclsInContainer.empty())
962 return VisitDeclContext(D);
963
964 // Get all the Decls in the DeclContext, and sort them with the
965 // additional ones we've collected. Then visit them.
966 for (DeclContext::decl_iterator I = D->decls_begin(), E = D->decls_end();
967 I!=E; ++I) {
968 Decl *subDecl = *I;
Ted Kremenek0582c892010-11-02 23:17:51 +0000969 if (!subDecl || subDecl->getLexicalDeclContext() != D ||
970 subDecl->getLocStart().isInvalid())
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000971 continue;
972 DeclsInContainer.push_back(subDecl);
973 }
974
975 // Now sort the Decls so that they appear in lexical order.
976 std::sort(DeclsInContainer.begin(), DeclsInContainer.end(),
977 ContainerDeclsSort(SM));
978
979 // Now visit the decls.
980 for (llvm::SmallVectorImpl<Decl*>::iterator I = DeclsInContainer.begin(),
981 E = DeclsInContainer.end(); I != E; ++I) {
982 CXCursor Cursor = MakeCXCursor(*I, TU);
983 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
984 if (!V.hasValue())
985 continue;
986 if (!V.getValue())
987 return false;
988 if (Visit(Cursor, true))
989 return true;
990 }
991 return false;
Douglas Gregora59e3902010-01-21 23:27:09 +0000992}
993
Douglas Gregorb1373d02010-01-20 20:59:29 +0000994bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000995 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
996 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000997 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000998
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000999 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
1000 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
1001 E = ND->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001002 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001003 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001004
Douglas Gregora59e3902010-01-21 23:27:09 +00001005 return VisitObjCContainerDecl(ND);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001006}
1007
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001008bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
1009 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
1010 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
1011 E = PID->protocol_end(); I != E; ++I, ++PL)
1012 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
1013 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001014
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001015 return VisitObjCContainerDecl(PID);
1016}
1017
Ted Kremenek23173d72010-05-18 21:09:07 +00001018bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
Douglas Gregor83cb9422010-09-09 17:09:21 +00001019 if (PD->getTypeSourceInfo() && Visit(PD->getTypeSourceInfo()->getTypeLoc()))
John McCallfc929202010-06-04 22:33:30 +00001020 return true;
1021
Ted Kremenek23173d72010-05-18 21:09:07 +00001022 // FIXME: This implements a workaround with @property declarations also being
1023 // installed in the DeclContext for the @interface. Eventually this code
1024 // should be removed.
1025 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
1026 if (!CDecl || !CDecl->IsClassExtension())
1027 return false;
1028
1029 ObjCInterfaceDecl *ID = CDecl->getClassInterface();
1030 if (!ID)
1031 return false;
1032
1033 IdentifierInfo *PropertyId = PD->getIdentifier();
1034 ObjCPropertyDecl *prevDecl =
1035 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId);
1036
1037 if (!prevDecl)
1038 return false;
1039
1040 // Visit synthesized methods since they will be skipped when visiting
1041 // the @interface.
1042 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +00001043 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Ted Kremenek23173d72010-05-18 21:09:07 +00001044 if (Visit(MakeCXCursor(MD, TU)))
1045 return true;
1046
1047 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +00001048 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Ted Kremenek23173d72010-05-18 21:09:07 +00001049 if (Visit(MakeCXCursor(MD, TU)))
1050 return true;
1051
1052 return false;
1053}
1054
Douglas Gregorb1373d02010-01-20 20:59:29 +00001055bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001056 // Issue callbacks for super class.
Douglas Gregorb1373d02010-01-20 20:59:29 +00001057 if (D->getSuperClass() &&
1058 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001059 D->getSuperClassLoc(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001060 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001061 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001062
Douglas Gregor78db0cd2010-01-16 15:44:18 +00001063 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1064 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
1065 E = D->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001066 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001067 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001068
Douglas Gregora59e3902010-01-21 23:27:09 +00001069 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001070}
1071
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001072bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
1073 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001074}
1075
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001076bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
Ted Kremenekebfa3392010-03-19 20:39:03 +00001077 // 'ID' could be null when dealing with invalid code.
1078 if (ObjCInterfaceDecl *ID = D->getClassInterface())
1079 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
1080 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001081
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001082 return VisitObjCImplDecl(D);
1083}
1084
1085bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
1086#if 0
1087 // Issue callbacks for super class.
1088 // FIXME: No source location information!
1089 if (D->getSuperClass() &&
1090 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001091 D->getSuperClassLoc(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001092 TU)))
1093 return true;
1094#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001095
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001096 return VisitObjCImplDecl(D);
1097}
1098
1099bool CursorVisitor::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D) {
1100 ObjCForwardProtocolDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1101 for (ObjCForwardProtocolDecl::protocol_iterator I = D->protocol_begin(),
1102 E = D->protocol_end();
1103 I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001104 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001105 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001106
1107 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001108}
1109
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001110bool CursorVisitor::VisitObjCClassDecl(ObjCClassDecl *D) {
1111 for (ObjCClassDecl::iterator C = D->begin(), CEnd = D->end(); C != CEnd; ++C)
1112 if (Visit(MakeCursorObjCClassRef(C->getInterface(), C->getLocation(), TU)))
1113 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001114
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001115 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001116}
1117
Douglas Gregora4ffd852010-11-17 01:03:52 +00001118bool CursorVisitor::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *PD) {
1119 if (ObjCIvarDecl *Ivar = PD->getPropertyIvarDecl())
1120 return Visit(MakeCursorMemberRef(Ivar, PD->getPropertyIvarDeclLoc(), TU));
1121
1122 return false;
1123}
1124
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00001125bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
1126 return VisitDeclContext(D);
1127}
1128
Douglas Gregor69319002010-08-31 23:48:11 +00001129bool CursorVisitor::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001130 // Visit nested-name-specifier.
Douglas Gregor0cfaf6a2011-02-25 17:08:07 +00001131 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1132 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001133 return true;
Douglas Gregor69319002010-08-31 23:48:11 +00001134
1135 return Visit(MakeCursorNamespaceRef(D->getAliasedNamespace(),
1136 D->getTargetNameLoc(), TU));
1137}
1138
Douglas Gregor7e242562010-09-01 19:52:22 +00001139bool CursorVisitor::VisitUsingDecl(UsingDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001140 // Visit nested-name-specifier.
Douglas Gregordc355712011-02-25 00:36:19 +00001141 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1142 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001143 return true;
Douglas Gregordc355712011-02-25 00:36:19 +00001144 }
Douglas Gregor7e242562010-09-01 19:52:22 +00001145
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001146 if (Visit(MakeCursorOverloadedDeclRef(D, D->getLocation(), TU)))
1147 return true;
1148
Douglas Gregor7e242562010-09-01 19:52:22 +00001149 return VisitDeclarationNameInfo(D->getNameInfo());
1150}
1151
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001152bool CursorVisitor::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001153 // Visit nested-name-specifier.
Douglas Gregordb992412011-02-25 16:33:46 +00001154 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1155 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001156 return true;
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001157
1158 return Visit(MakeCursorNamespaceRef(D->getNominatedNamespaceAsWritten(),
1159 D->getIdentLocation(), TU));
1160}
1161
Douglas Gregor7e242562010-09-01 19:52:22 +00001162bool CursorVisitor::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001163 // Visit nested-name-specifier.
Douglas Gregordc355712011-02-25 00:36:19 +00001164 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1165 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001166 return true;
Douglas Gregordc355712011-02-25 00:36:19 +00001167 }
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001168
Douglas Gregor7e242562010-09-01 19:52:22 +00001169 return VisitDeclarationNameInfo(D->getNameInfo());
1170}
1171
1172bool CursorVisitor::VisitUnresolvedUsingTypenameDecl(
1173 UnresolvedUsingTypenameDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001174 // Visit nested-name-specifier.
Douglas Gregordc355712011-02-25 00:36:19 +00001175 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1176 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001177 return true;
1178
Douglas Gregor7e242562010-09-01 19:52:22 +00001179 return false;
1180}
1181
Douglas Gregor01829d32010-08-31 14:41:23 +00001182bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) {
1183 switch (Name.getName().getNameKind()) {
1184 case clang::DeclarationName::Identifier:
1185 case clang::DeclarationName::CXXLiteralOperatorName:
1186 case clang::DeclarationName::CXXOperatorName:
1187 case clang::DeclarationName::CXXUsingDirective:
1188 return false;
1189
1190 case clang::DeclarationName::CXXConstructorName:
1191 case clang::DeclarationName::CXXDestructorName:
1192 case clang::DeclarationName::CXXConversionFunctionName:
1193 if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo())
1194 return Visit(TSInfo->getTypeLoc());
1195 return false;
1196
1197 case clang::DeclarationName::ObjCZeroArgSelector:
1198 case clang::DeclarationName::ObjCOneArgSelector:
1199 case clang::DeclarationName::ObjCMultiArgSelector:
1200 // FIXME: Per-identifier location info?
1201 return false;
1202 }
1203
1204 return false;
1205}
1206
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001207bool CursorVisitor::VisitNestedNameSpecifier(NestedNameSpecifier *NNS,
1208 SourceRange Range) {
1209 // FIXME: This whole routine is a hack to work around the lack of proper
1210 // source information in nested-name-specifiers (PR5791). Since we do have
1211 // a beginning source location, we can visit the first component of the
1212 // nested-name-specifier, if it's a single-token component.
1213 if (!NNS)
1214 return false;
1215
1216 // Get the first component in the nested-name-specifier.
1217 while (NestedNameSpecifier *Prefix = NNS->getPrefix())
1218 NNS = Prefix;
1219
1220 switch (NNS->getKind()) {
1221 case NestedNameSpecifier::Namespace:
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001222 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(), Range.getBegin(),
1223 TU));
1224
Douglas Gregor14aba762011-02-24 02:36:08 +00001225 case NestedNameSpecifier::NamespaceAlias:
1226 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
1227 Range.getBegin(), TU));
1228
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001229 case NestedNameSpecifier::TypeSpec: {
1230 // If the type has a form where we know that the beginning of the source
1231 // range matches up with a reference cursor. Visit the appropriate reference
1232 // cursor.
John McCallf4c73712011-01-19 06:33:43 +00001233 const Type *T = NNS->getAsType();
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001234 if (const TypedefType *Typedef = dyn_cast<TypedefType>(T))
1235 return Visit(MakeCursorTypeRef(Typedef->getDecl(), Range.getBegin(), TU));
1236 if (const TagType *Tag = dyn_cast<TagType>(T))
1237 return Visit(MakeCursorTypeRef(Tag->getDecl(), Range.getBegin(), TU));
1238 if (const TemplateSpecializationType *TST
1239 = dyn_cast<TemplateSpecializationType>(T))
1240 return VisitTemplateName(TST->getTemplateName(), Range.getBegin());
1241 break;
1242 }
1243
1244 case NestedNameSpecifier::TypeSpecWithTemplate:
1245 case NestedNameSpecifier::Global:
1246 case NestedNameSpecifier::Identifier:
1247 break;
1248 }
1249
1250 return false;
1251}
1252
Douglas Gregordc355712011-02-25 00:36:19 +00001253bool
1254CursorVisitor::VisitNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
1255 llvm::SmallVector<NestedNameSpecifierLoc, 4> Qualifiers;
1256 for (; Qualifier; Qualifier = Qualifier.getPrefix())
1257 Qualifiers.push_back(Qualifier);
1258
1259 while (!Qualifiers.empty()) {
1260 NestedNameSpecifierLoc Q = Qualifiers.pop_back_val();
1261 NestedNameSpecifier *NNS = Q.getNestedNameSpecifier();
1262 switch (NNS->getKind()) {
1263 case NestedNameSpecifier::Namespace:
1264 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(),
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001265 Q.getLocalBeginLoc(),
Douglas Gregordc355712011-02-25 00:36:19 +00001266 TU)))
1267 return true;
1268
1269 break;
1270
1271 case NestedNameSpecifier::NamespaceAlias:
1272 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001273 Q.getLocalBeginLoc(),
Douglas Gregordc355712011-02-25 00:36:19 +00001274 TU)))
1275 return true;
1276
1277 break;
1278
1279 case NestedNameSpecifier::TypeSpec:
1280 case NestedNameSpecifier::TypeSpecWithTemplate:
1281 if (Visit(Q.getTypeLoc()))
1282 return true;
1283
1284 break;
1285
1286 case NestedNameSpecifier::Global:
1287 case NestedNameSpecifier::Identifier:
1288 break;
1289 }
1290 }
1291
1292 return false;
1293}
1294
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001295bool CursorVisitor::VisitTemplateParameters(
1296 const TemplateParameterList *Params) {
1297 if (!Params)
1298 return false;
1299
1300 for (TemplateParameterList::const_iterator P = Params->begin(),
1301 PEnd = Params->end();
1302 P != PEnd; ++P) {
1303 if (Visit(MakeCXCursor(*P, TU)))
1304 return true;
1305 }
1306
1307 return false;
1308}
1309
Douglas Gregor0b36e612010-08-31 20:37:03 +00001310bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) {
1311 switch (Name.getKind()) {
1312 case TemplateName::Template:
1313 return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU));
1314
1315 case TemplateName::OverloadedTemplate:
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001316 // Visit the overloaded template set.
1317 if (Visit(MakeCursorOverloadedDeclRef(Name, Loc, TU)))
1318 return true;
1319
Douglas Gregor0b36e612010-08-31 20:37:03 +00001320 return false;
1321
1322 case TemplateName::DependentTemplate:
1323 // FIXME: Visit nested-name-specifier.
1324 return false;
1325
1326 case TemplateName::QualifiedTemplate:
1327 // FIXME: Visit nested-name-specifier.
1328 return Visit(MakeCursorTemplateRef(
1329 Name.getAsQualifiedTemplateName()->getDecl(),
1330 Loc, TU));
Douglas Gregor1aee05d2011-01-15 06:45:20 +00001331
1332 case TemplateName::SubstTemplateTemplateParmPack:
1333 return Visit(MakeCursorTemplateRef(
1334 Name.getAsSubstTemplateTemplateParmPack()->getParameterPack(),
1335 Loc, TU));
Douglas Gregor0b36e612010-08-31 20:37:03 +00001336 }
1337
1338 return false;
1339}
1340
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001341bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) {
1342 switch (TAL.getArgument().getKind()) {
1343 case TemplateArgument::Null:
1344 case TemplateArgument::Integral:
Douglas Gregor87dd6972010-12-20 16:52:59 +00001345 case TemplateArgument::Pack:
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001346 return false;
1347
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001348 case TemplateArgument::Type:
1349 if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo())
1350 return Visit(TSInfo->getTypeLoc());
1351 return false;
1352
1353 case TemplateArgument::Declaration:
1354 if (Expr *E = TAL.getSourceDeclExpression())
1355 return Visit(MakeCXCursor(E, StmtParent, TU));
1356 return false;
1357
1358 case TemplateArgument::Expression:
1359 if (Expr *E = TAL.getSourceExpression())
1360 return Visit(MakeCXCursor(E, StmtParent, TU));
1361 return false;
1362
1363 case TemplateArgument::Template:
Douglas Gregora7fc9012011-01-05 18:58:31 +00001364 case TemplateArgument::TemplateExpansion:
Douglas Gregorb6744ef2011-03-02 17:09:35 +00001365 if (VisitNestedNameSpecifierLoc(TAL.getTemplateQualifierLoc()))
1366 return true;
1367
Douglas Gregora7fc9012011-01-05 18:58:31 +00001368 return VisitTemplateName(TAL.getArgument().getAsTemplateOrTemplatePattern(),
Douglas Gregor0b36e612010-08-31 20:37:03 +00001369 TAL.getTemplateNameLoc());
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001370 }
1371
1372 return false;
1373}
1374
Ted Kremeneka0536d82010-05-07 01:04:29 +00001375bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1376 return VisitDeclContext(D);
1377}
1378
Douglas Gregor01829d32010-08-31 14:41:23 +00001379bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1380 return Visit(TL.getUnqualifiedLoc());
1381}
1382
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001383bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00001384 ASTContext &Context = AU->getASTContext();
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001385
1386 // Some builtin types (such as Objective-C's "id", "sel", and
1387 // "Class") have associated declarations. Create cursors for those.
1388 QualType VisitType;
1389 switch (TL.getType()->getAs<BuiltinType>()->getKind()) {
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001390 case BuiltinType::Void:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001391 case BuiltinType::Bool:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001392 case BuiltinType::Char_U:
1393 case BuiltinType::UChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001394 case BuiltinType::Char16:
1395 case BuiltinType::Char32:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001396 case BuiltinType::UShort:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001397 case BuiltinType::UInt:
1398 case BuiltinType::ULong:
1399 case BuiltinType::ULongLong:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001400 case BuiltinType::UInt128:
1401 case BuiltinType::Char_S:
1402 case BuiltinType::SChar:
Chris Lattner3f59c972010-12-25 23:25:43 +00001403 case BuiltinType::WChar_U:
1404 case BuiltinType::WChar_S:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001405 case BuiltinType::Short:
1406 case BuiltinType::Int:
1407 case BuiltinType::Long:
1408 case BuiltinType::LongLong:
1409 case BuiltinType::Int128:
1410 case BuiltinType::Float:
1411 case BuiltinType::Double:
1412 case BuiltinType::LongDouble:
1413 case BuiltinType::NullPtr:
1414 case BuiltinType::Overload:
John McCall864c0412011-04-26 20:42:42 +00001415 case BuiltinType::BoundMember:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001416 case BuiltinType::Dependent:
John McCall1de4d4e2011-04-07 08:22:57 +00001417 case BuiltinType::UnknownAny:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001418 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001419
Ted Kremenekc4174cc2010-02-18 18:52:18 +00001420 case BuiltinType::ObjCId:
1421 VisitType = Context.getObjCIdType();
1422 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001423
1424 case BuiltinType::ObjCClass:
1425 VisitType = Context.getObjCClassType();
1426 break;
1427
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001428 case BuiltinType::ObjCSel:
1429 VisitType = Context.getObjCSelType();
1430 break;
1431 }
1432
1433 if (!VisitType.isNull()) {
1434 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001435 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001436 TU));
1437 }
1438
1439 return false;
1440}
1441
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001442bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
Richard Smith162e1c12011-04-15 14:24:37 +00001443 return Visit(MakeCursorTypeRef(TL.getTypedefNameDecl(), TL.getNameLoc(), TU));
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001444}
1445
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001446bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
1447 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1448}
1449
1450bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
1451 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1452}
1453
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001454bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001455 // FIXME: We can't visit the template type parameter, because there's
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001456 // no context information with which we can match up the depth/index in the
1457 // type to the appropriate
1458 return false;
1459}
1460
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001461bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
1462 if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
1463 return true;
1464
John McCallc12c5bb2010-05-15 11:32:37 +00001465 return false;
1466}
1467
1468bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
1469 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
1470 return true;
1471
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001472 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1473 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1474 TU)))
1475 return true;
1476 }
1477
1478 return false;
1479}
1480
1481bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
John McCallc12c5bb2010-05-15 11:32:37 +00001482 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001483}
1484
Abramo Bagnara075f8f12010-12-10 16:29:40 +00001485bool CursorVisitor::VisitParenTypeLoc(ParenTypeLoc TL) {
1486 return Visit(TL.getInnerLoc());
1487}
1488
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001489bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
1490 return Visit(TL.getPointeeLoc());
1491}
1492
1493bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1494 return Visit(TL.getPointeeLoc());
1495}
1496
1497bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1498 return Visit(TL.getPointeeLoc());
1499}
1500
1501bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001502 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001503}
1504
1505bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001506 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001507}
1508
Douglas Gregor01829d32010-08-31 14:41:23 +00001509bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL,
1510 bool SkipResultType) {
1511 if (!SkipResultType && Visit(TL.getResultLoc()))
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001512 return true;
1513
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001514 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
Ted Kremenek5dbacb42010-04-07 00:27:13 +00001515 if (Decl *D = TL.getArg(I))
1516 if (Visit(MakeCXCursor(D, TU)))
1517 return true;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001518
1519 return false;
1520}
1521
1522bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
1523 if (Visit(TL.getElementLoc()))
1524 return true;
1525
1526 if (Expr *Size = TL.getSizeExpr())
1527 return Visit(MakeCXCursor(Size, StmtParent, TU));
1528
1529 return false;
1530}
1531
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001532bool CursorVisitor::VisitTemplateSpecializationTypeLoc(
1533 TemplateSpecializationTypeLoc TL) {
Douglas Gregor0b36e612010-08-31 20:37:03 +00001534 // Visit the template name.
1535 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1536 TL.getTemplateNameLoc()))
1537 return true;
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001538
1539 // Visit the template arguments.
1540 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1541 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1542 return true;
1543
1544 return false;
1545}
1546
Douglas Gregor2332c112010-01-21 20:48:56 +00001547bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
1548 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
1549}
1550
1551bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
1552 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1553 return Visit(TSInfo->getTypeLoc());
1554
1555 return false;
1556}
1557
Douglas Gregor2494dd02011-03-01 01:34:45 +00001558bool CursorVisitor::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
1559 if (VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1560 return true;
1561
1562 return false;
1563}
1564
Douglas Gregor94fdffa2011-03-01 20:11:18 +00001565bool CursorVisitor::VisitDependentTemplateSpecializationTypeLoc(
1566 DependentTemplateSpecializationTypeLoc TL) {
1567 // Visit the nested-name-specifier, if there is one.
1568 if (TL.getQualifierLoc() &&
1569 VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1570 return true;
1571
1572 // Visit the template arguments.
1573 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1574 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1575 return true;
1576
1577 return false;
1578}
1579
Douglas Gregor9e876872011-03-01 18:12:44 +00001580bool CursorVisitor::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
1581 if (VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1582 return true;
1583
1584 return Visit(TL.getNamedTypeLoc());
1585}
1586
Douglas Gregor7536dd52010-12-20 02:24:11 +00001587bool CursorVisitor::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
1588 return Visit(TL.getPatternLoc());
1589}
1590
Ted Kremenek3064ef92010-08-27 21:34:58 +00001591bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001592 // Visit the nested-name-specifier, if present.
1593 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1594 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1595 return true;
1596
Ted Kremenek3064ef92010-08-27 21:34:58 +00001597 if (D->isDefinition()) {
1598 for (CXXRecordDecl::base_class_iterator I = D->bases_begin(),
1599 E = D->bases_end(); I != E; ++I) {
1600 if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(I, TU)))
1601 return true;
1602 }
1603 }
1604
1605 return VisitTagDecl(D);
1606}
1607
Ted Kremenek09dfa372010-02-18 05:46:33 +00001608bool CursorVisitor::VisitAttributes(Decl *D) {
Sean Huntcf807c42010-08-18 23:23:40 +00001609 for (AttrVec::const_iterator i = D->attr_begin(), e = D->attr_end();
1610 i != e; ++i)
1611 if (Visit(MakeCXCursor(*i, D, TU)))
Ted Kremenek09dfa372010-02-18 05:46:33 +00001612 return true;
1613
1614 return false;
1615}
1616
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001617//===----------------------------------------------------------------------===//
1618// Data-recursive visitor methods.
1619//===----------------------------------------------------------------------===//
1620
Ted Kremenek28a71942010-11-13 00:36:47 +00001621namespace {
Ted Kremenek035dc412010-11-13 00:36:50 +00001622#define DEF_JOB(NAME, DATA, KIND)\
1623class NAME : public VisitorJob {\
1624public:\
1625 NAME(DATA *d, CXCursor parent) : VisitorJob(parent, VisitorJob::KIND, d) {} \
1626 static bool classof(const VisitorJob *VJ) { return VJ->getKind() == KIND; }\
Ted Kremenekf64d8032010-11-18 00:02:32 +00001627 DATA *get() const { return static_cast<DATA*>(data[0]); }\
Ted Kremenek035dc412010-11-13 00:36:50 +00001628};
1629
1630DEF_JOB(StmtVisit, Stmt, StmtVisitKind)
1631DEF_JOB(MemberExprParts, MemberExpr, MemberExprPartsKind)
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001632DEF_JOB(DeclRefExprParts, DeclRefExpr, DeclRefExprPartsKind)
Ted Kremenek035dc412010-11-13 00:36:50 +00001633DEF_JOB(OverloadExprParts, OverloadExpr, OverloadExprPartsKind)
Ted Kremenek60608ec2010-11-17 00:50:47 +00001634DEF_JOB(ExplicitTemplateArgsVisit, ExplicitTemplateArgumentList,
1635 ExplicitTemplateArgsVisitKind)
Douglas Gregor94d96292011-01-19 20:34:17 +00001636DEF_JOB(SizeOfPackExprParts, SizeOfPackExpr, SizeOfPackExprPartsKind)
Ted Kremenek035dc412010-11-13 00:36:50 +00001637#undef DEF_JOB
1638
1639class DeclVisit : public VisitorJob {
1640public:
1641 DeclVisit(Decl *d, CXCursor parent, bool isFirst) :
1642 VisitorJob(parent, VisitorJob::DeclVisitKind,
1643 d, isFirst ? (void*) 1 : (void*) 0) {}
1644 static bool classof(const VisitorJob *VJ) {
Ted Kremenek82f3c502010-11-15 22:23:26 +00001645 return VJ->getKind() == DeclVisitKind;
Ted Kremenek035dc412010-11-13 00:36:50 +00001646 }
Ted Kremenekf64d8032010-11-18 00:02:32 +00001647 Decl *get() const { return static_cast<Decl*>(data[0]); }
1648 bool isFirst() const { return data[1] ? true : false; }
Ted Kremenek035dc412010-11-13 00:36:50 +00001649};
Ted Kremenek035dc412010-11-13 00:36:50 +00001650class TypeLocVisit : public VisitorJob {
1651public:
1652 TypeLocVisit(TypeLoc tl, CXCursor parent) :
1653 VisitorJob(parent, VisitorJob::TypeLocVisitKind,
1654 tl.getType().getAsOpaquePtr(), tl.getOpaqueData()) {}
1655
1656 static bool classof(const VisitorJob *VJ) {
1657 return VJ->getKind() == TypeLocVisitKind;
1658 }
1659
Ted Kremenek82f3c502010-11-15 22:23:26 +00001660 TypeLoc get() const {
Ted Kremenekf64d8032010-11-18 00:02:32 +00001661 QualType T = QualType::getFromOpaquePtr(data[0]);
1662 return TypeLoc(T, data[1]);
Ted Kremenek035dc412010-11-13 00:36:50 +00001663 }
1664};
1665
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001666class LabelRefVisit : public VisitorJob {
1667public:
Chris Lattnerad8dcf42011-02-17 07:39:24 +00001668 LabelRefVisit(LabelDecl *LD, SourceLocation labelLoc, CXCursor parent)
1669 : VisitorJob(parent, VisitorJob::LabelRefVisitKind, LD,
Jeffrey Yasskindec09842011-01-18 02:00:16 +00001670 labelLoc.getPtrEncoding()) {}
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001671
1672 static bool classof(const VisitorJob *VJ) {
1673 return VJ->getKind() == VisitorJob::LabelRefVisitKind;
1674 }
Chris Lattnerad8dcf42011-02-17 07:39:24 +00001675 LabelDecl *get() const { return static_cast<LabelDecl*>(data[0]); }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001676 SourceLocation getLoc() const {
Jeffrey Yasskindec09842011-01-18 02:00:16 +00001677 return SourceLocation::getFromPtrEncoding(data[1]); }
Ted Kremenekf64d8032010-11-18 00:02:32 +00001678};
1679class NestedNameSpecifierVisit : public VisitorJob {
1680public:
1681 NestedNameSpecifierVisit(NestedNameSpecifier *NS, SourceRange R,
1682 CXCursor parent)
1683 : VisitorJob(parent, VisitorJob::NestedNameSpecifierVisitKind,
Jeffrey Yasskindec09842011-01-18 02:00:16 +00001684 NS, R.getBegin().getPtrEncoding(),
1685 R.getEnd().getPtrEncoding()) {}
Ted Kremenekf64d8032010-11-18 00:02:32 +00001686 static bool classof(const VisitorJob *VJ) {
1687 return VJ->getKind() == VisitorJob::NestedNameSpecifierVisitKind;
1688 }
1689 NestedNameSpecifier *get() const {
1690 return static_cast<NestedNameSpecifier*>(data[0]);
1691 }
1692 SourceRange getSourceRange() const {
1693 SourceLocation A =
1694 SourceLocation::getFromRawEncoding((unsigned)(uintptr_t) data[1]);
1695 SourceLocation B =
1696 SourceLocation::getFromRawEncoding((unsigned)(uintptr_t) data[2]);
1697 return SourceRange(A, B);
1698 }
1699};
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001700
1701class NestedNameSpecifierLocVisit : public VisitorJob {
1702public:
1703 NestedNameSpecifierLocVisit(NestedNameSpecifierLoc Qualifier, CXCursor parent)
1704 : VisitorJob(parent, VisitorJob::NestedNameSpecifierLocVisitKind,
1705 Qualifier.getNestedNameSpecifier(),
1706 Qualifier.getOpaqueData()) { }
1707
1708 static bool classof(const VisitorJob *VJ) {
1709 return VJ->getKind() == VisitorJob::NestedNameSpecifierLocVisitKind;
1710 }
1711
1712 NestedNameSpecifierLoc get() const {
1713 return NestedNameSpecifierLoc(static_cast<NestedNameSpecifier*>(data[0]),
1714 data[1]);
1715 }
1716};
1717
Ted Kremenekf64d8032010-11-18 00:02:32 +00001718class DeclarationNameInfoVisit : public VisitorJob {
1719public:
1720 DeclarationNameInfoVisit(Stmt *S, CXCursor parent)
1721 : VisitorJob(parent, VisitorJob::DeclarationNameInfoVisitKind, S) {}
1722 static bool classof(const VisitorJob *VJ) {
1723 return VJ->getKind() == VisitorJob::DeclarationNameInfoVisitKind;
1724 }
1725 DeclarationNameInfo get() const {
1726 Stmt *S = static_cast<Stmt*>(data[0]);
1727 switch (S->getStmtClass()) {
1728 default:
1729 llvm_unreachable("Unhandled Stmt");
1730 case Stmt::CXXDependentScopeMemberExprClass:
1731 return cast<CXXDependentScopeMemberExpr>(S)->getMemberNameInfo();
1732 case Stmt::DependentScopeDeclRefExprClass:
1733 return cast<DependentScopeDeclRefExpr>(S)->getNameInfo();
1734 }
1735 }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001736};
Ted Kremenekcdba6592010-11-18 00:42:18 +00001737class MemberRefVisit : public VisitorJob {
1738public:
1739 MemberRefVisit(FieldDecl *D, SourceLocation L, CXCursor parent)
1740 : VisitorJob(parent, VisitorJob::MemberRefVisitKind, D,
Jeffrey Yasskindec09842011-01-18 02:00:16 +00001741 L.getPtrEncoding()) {}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001742 static bool classof(const VisitorJob *VJ) {
1743 return VJ->getKind() == VisitorJob::MemberRefVisitKind;
1744 }
1745 FieldDecl *get() const {
1746 return static_cast<FieldDecl*>(data[0]);
1747 }
1748 SourceLocation getLoc() const {
1749 return SourceLocation::getFromRawEncoding((unsigned)(uintptr_t) data[1]);
1750 }
1751};
Ted Kremenek28a71942010-11-13 00:36:47 +00001752class EnqueueVisitor : public StmtVisitor<EnqueueVisitor, void> {
1753 VisitorWorkList &WL;
1754 CXCursor Parent;
1755public:
1756 EnqueueVisitor(VisitorWorkList &wl, CXCursor parent)
1757 : WL(wl), Parent(parent) {}
1758
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001759 void VisitAddrLabelExpr(AddrLabelExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001760 void VisitBlockExpr(BlockExpr *B);
Ted Kremenek28a71942010-11-13 00:36:47 +00001761 void VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
Ted Kremenek083c7e22010-11-13 05:38:03 +00001762 void VisitCompoundStmt(CompoundStmt *S);
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001763 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { /* Do nothing. */ }
Ted Kremenekf64d8032010-11-18 00:02:32 +00001764 void VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E);
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001765 void VisitCXXNewExpr(CXXNewExpr *E);
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00001766 void VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001767 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001768 void VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001769 void VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E);
Ted Kremenekb8dd1ca2010-11-17 00:50:41 +00001770 void VisitCXXTypeidExpr(CXXTypeidExpr *E);
Ted Kremenek55b933a2010-11-17 00:50:36 +00001771 void VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr *E);
Ted Kremenek1e7e8772010-11-17 00:50:52 +00001772 void VisitCXXUuidofExpr(CXXUuidofExpr *E);
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001773 void VisitDeclRefExpr(DeclRefExpr *D);
Ted Kremenek035dc412010-11-13 00:36:50 +00001774 void VisitDeclStmt(DeclStmt *S);
Ted Kremenekf64d8032010-11-18 00:02:32 +00001775 void VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001776 void VisitDesignatedInitExpr(DesignatedInitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001777 void VisitExplicitCastExpr(ExplicitCastExpr *E);
1778 void VisitForStmt(ForStmt *FS);
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001779 void VisitGotoStmt(GotoStmt *GS);
Ted Kremenek28a71942010-11-13 00:36:47 +00001780 void VisitIfStmt(IfStmt *If);
1781 void VisitInitListExpr(InitListExpr *IE);
1782 void VisitMemberExpr(MemberExpr *M);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001783 void VisitOffsetOfExpr(OffsetOfExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001784 void VisitObjCEncodeExpr(ObjCEncodeExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001785 void VisitObjCMessageExpr(ObjCMessageExpr *M);
1786 void VisitOverloadExpr(OverloadExpr *E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001787 void VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001788 void VisitStmt(Stmt *S);
1789 void VisitSwitchStmt(SwitchStmt *S);
1790 void VisitWhileStmt(WhileStmt *W);
Ted Kremenek2939b6f2010-11-17 00:50:50 +00001791 void VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E);
Francois Pichet6ad6f282010-12-07 00:08:36 +00001792 void VisitBinaryTypeTraitExpr(BinaryTypeTraitExpr *E);
John Wiegley55262202011-04-25 06:54:41 +00001793 void VisitExpressionTraitExpr(ExpressionTraitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001794 void VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U);
Ted Kremenek9d3bf792010-11-17 00:50:43 +00001795 void VisitVAArgExpr(VAArgExpr *E);
Douglas Gregor94d96292011-01-19 20:34:17 +00001796 void VisitSizeOfPackExpr(SizeOfPackExpr *E);
Douglas Gregoree8aff02011-01-04 17:33:58 +00001797
Ted Kremenek28a71942010-11-13 00:36:47 +00001798private:
Ted Kremenekf64d8032010-11-18 00:02:32 +00001799 void AddDeclarationNameInfo(Stmt *S);
1800 void AddNestedNameSpecifier(NestedNameSpecifier *NS, SourceRange R);
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001801 void AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier);
Ted Kremenek60608ec2010-11-17 00:50:47 +00001802 void AddExplicitTemplateArgs(const ExplicitTemplateArgumentList *A);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001803 void AddMemberRef(FieldDecl *D, SourceLocation L);
Ted Kremenek28a71942010-11-13 00:36:47 +00001804 void AddStmt(Stmt *S);
Ted Kremenek035dc412010-11-13 00:36:50 +00001805 void AddDecl(Decl *D, bool isFirst = true);
Ted Kremenek28a71942010-11-13 00:36:47 +00001806 void AddTypeLoc(TypeSourceInfo *TI);
1807 void EnqueueChildren(Stmt *S);
1808};
1809} // end anonyous namespace
1810
Ted Kremenekf64d8032010-11-18 00:02:32 +00001811void EnqueueVisitor::AddDeclarationNameInfo(Stmt *S) {
1812 // 'S' should always be non-null, since it comes from the
1813 // statement we are visiting.
1814 WL.push_back(DeclarationNameInfoVisit(S, Parent));
1815}
1816void EnqueueVisitor::AddNestedNameSpecifier(NestedNameSpecifier *N,
1817 SourceRange R) {
1818 if (N)
1819 WL.push_back(NestedNameSpecifierVisit(N, R, Parent));
1820}
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001821
1822void
1823EnqueueVisitor::AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
1824 if (Qualifier)
1825 WL.push_back(NestedNameSpecifierLocVisit(Qualifier, Parent));
1826}
1827
Ted Kremenek28a71942010-11-13 00:36:47 +00001828void EnqueueVisitor::AddStmt(Stmt *S) {
1829 if (S)
1830 WL.push_back(StmtVisit(S, Parent));
1831}
Ted Kremenek035dc412010-11-13 00:36:50 +00001832void EnqueueVisitor::AddDecl(Decl *D, bool isFirst) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001833 if (D)
Ted Kremenek035dc412010-11-13 00:36:50 +00001834 WL.push_back(DeclVisit(D, Parent, isFirst));
Ted Kremenek28a71942010-11-13 00:36:47 +00001835}
Ted Kremenek60608ec2010-11-17 00:50:47 +00001836void EnqueueVisitor::
1837 AddExplicitTemplateArgs(const ExplicitTemplateArgumentList *A) {
1838 if (A)
1839 WL.push_back(ExplicitTemplateArgsVisit(
1840 const_cast<ExplicitTemplateArgumentList*>(A), Parent));
1841}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001842void EnqueueVisitor::AddMemberRef(FieldDecl *D, SourceLocation L) {
1843 if (D)
1844 WL.push_back(MemberRefVisit(D, L, Parent));
1845}
Ted Kremenek28a71942010-11-13 00:36:47 +00001846void EnqueueVisitor::AddTypeLoc(TypeSourceInfo *TI) {
1847 if (TI)
1848 WL.push_back(TypeLocVisit(TI->getTypeLoc(), Parent));
1849 }
1850void EnqueueVisitor::EnqueueChildren(Stmt *S) {
Ted Kremeneka6b70432010-11-12 21:34:09 +00001851 unsigned size = WL.size();
John McCall7502c1d2011-02-13 04:07:26 +00001852 for (Stmt::child_range Child = S->children(); Child; ++Child) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001853 AddStmt(*Child);
Ted Kremeneka6b70432010-11-12 21:34:09 +00001854 }
1855 if (size == WL.size())
1856 return;
1857 // Now reverse the entries we just added. This will match the DFS
1858 // ordering performed by the worklist.
1859 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1860 std::reverse(I, E);
1861}
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001862void EnqueueVisitor::VisitAddrLabelExpr(AddrLabelExpr *E) {
1863 WL.push_back(LabelRefVisit(E->getLabel(), E->getLabelLoc(), Parent));
1864}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001865void EnqueueVisitor::VisitBlockExpr(BlockExpr *B) {
1866 AddDecl(B->getBlockDecl());
1867}
Ted Kremenek28a71942010-11-13 00:36:47 +00001868void EnqueueVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
1869 EnqueueChildren(E);
1870 AddTypeLoc(E->getTypeSourceInfo());
1871}
Ted Kremenek083c7e22010-11-13 05:38:03 +00001872void EnqueueVisitor::VisitCompoundStmt(CompoundStmt *S) {
1873 for (CompoundStmt::reverse_body_iterator I = S->body_rbegin(),
1874 E = S->body_rend(); I != E; ++I) {
1875 AddStmt(*I);
1876 }
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001877}
Ted Kremenekf64d8032010-11-18 00:02:32 +00001878void EnqueueVisitor::
1879VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E) {
1880 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
1881 AddDeclarationNameInfo(E);
Douglas Gregor7c3179c2011-02-28 18:50:33 +00001882 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
1883 AddNestedNameSpecifierLoc(QualifierLoc);
Ted Kremenekf64d8032010-11-18 00:02:32 +00001884 if (!E->isImplicitAccess())
1885 AddStmt(E->getBase());
1886}
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001887void EnqueueVisitor::VisitCXXNewExpr(CXXNewExpr *E) {
1888 // Enqueue the initializer or constructor arguments.
1889 for (unsigned I = E->getNumConstructorArgs(); I > 0; --I)
1890 AddStmt(E->getConstructorArg(I-1));
1891 // Enqueue the array size, if any.
1892 AddStmt(E->getArraySize());
1893 // Enqueue the allocated type.
1894 AddTypeLoc(E->getAllocatedTypeSourceInfo());
1895 // Enqueue the placement arguments.
1896 for (unsigned I = E->getNumPlacementArgs(); I > 0; --I)
1897 AddStmt(E->getPlacementArg(I-1));
1898}
Ted Kremenek28a71942010-11-13 00:36:47 +00001899void EnqueueVisitor::VisitCXXOperatorCallExpr(CXXOperatorCallExpr *CE) {
Ted Kremenek8b8d8c92010-11-13 05:55:56 +00001900 for (unsigned I = CE->getNumArgs(); I > 1 /* Yes, this is 1 */; --I)
1901 AddStmt(CE->getArg(I-1));
Ted Kremenek28a71942010-11-13 00:36:47 +00001902 AddStmt(CE->getCallee());
1903 AddStmt(CE->getArg(0));
1904}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001905void EnqueueVisitor::VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E) {
1906 // Visit the name of the type being destroyed.
1907 AddTypeLoc(E->getDestroyedTypeInfo());
1908 // Visit the scope type that looks disturbingly like the nested-name-specifier
1909 // but isn't.
1910 AddTypeLoc(E->getScopeTypeInfo());
1911 // Visit the nested-name-specifier.
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001912 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
1913 AddNestedNameSpecifierLoc(QualifierLoc);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001914 // Visit base expression.
1915 AddStmt(E->getBase());
1916}
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00001917void EnqueueVisitor::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
1918 AddTypeLoc(E->getTypeSourceInfo());
1919}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001920void EnqueueVisitor::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E) {
1921 EnqueueChildren(E);
1922 AddTypeLoc(E->getTypeSourceInfo());
1923}
Ted Kremenekb8dd1ca2010-11-17 00:50:41 +00001924void EnqueueVisitor::VisitCXXTypeidExpr(CXXTypeidExpr *E) {
1925 EnqueueChildren(E);
1926 if (E->isTypeOperand())
1927 AddTypeLoc(E->getTypeOperandSourceInfo());
1928}
Ted Kremenek55b933a2010-11-17 00:50:36 +00001929
1930void EnqueueVisitor::VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr
1931 *E) {
1932 EnqueueChildren(E);
1933 AddTypeLoc(E->getTypeSourceInfo());
1934}
Ted Kremenek1e7e8772010-11-17 00:50:52 +00001935void EnqueueVisitor::VisitCXXUuidofExpr(CXXUuidofExpr *E) {
1936 EnqueueChildren(E);
1937 if (E->isTypeOperand())
1938 AddTypeLoc(E->getTypeOperandSourceInfo());
1939}
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001940void EnqueueVisitor::VisitDeclRefExpr(DeclRefExpr *DR) {
Ted Kremenek60608ec2010-11-17 00:50:47 +00001941 if (DR->hasExplicitTemplateArgs()) {
1942 AddExplicitTemplateArgs(&DR->getExplicitTemplateArgs());
1943 }
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001944 WL.push_back(DeclRefExprParts(DR, Parent));
1945}
Ted Kremenekf64d8032010-11-18 00:02:32 +00001946void EnqueueVisitor::VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E) {
1947 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
1948 AddDeclarationNameInfo(E);
Douglas Gregor00cf3cc2011-02-25 20:49:16 +00001949 AddNestedNameSpecifierLoc(E->getQualifierLoc());
Ted Kremenekf64d8032010-11-18 00:02:32 +00001950}
Ted Kremenek035dc412010-11-13 00:36:50 +00001951void EnqueueVisitor::VisitDeclStmt(DeclStmt *S) {
1952 unsigned size = WL.size();
1953 bool isFirst = true;
1954 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
1955 D != DEnd; ++D) {
1956 AddDecl(*D, isFirst);
1957 isFirst = false;
1958 }
1959 if (size == WL.size())
1960 return;
1961 // Now reverse the entries we just added. This will match the DFS
1962 // ordering performed by the worklist.
1963 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1964 std::reverse(I, E);
1965}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001966void EnqueueVisitor::VisitDesignatedInitExpr(DesignatedInitExpr *E) {
1967 AddStmt(E->getInit());
1968 typedef DesignatedInitExpr::Designator Designator;
1969 for (DesignatedInitExpr::reverse_designators_iterator
1970 D = E->designators_rbegin(), DEnd = E->designators_rend();
1971 D != DEnd; ++D) {
1972 if (D->isFieldDesignator()) {
1973 if (FieldDecl *Field = D->getField())
1974 AddMemberRef(Field, D->getFieldLoc());
1975 continue;
1976 }
1977 if (D->isArrayDesignator()) {
1978 AddStmt(E->getArrayIndex(*D));
1979 continue;
1980 }
1981 assert(D->isArrayRangeDesignator() && "Unknown designator kind");
1982 AddStmt(E->getArrayRangeEnd(*D));
1983 AddStmt(E->getArrayRangeStart(*D));
1984 }
1985}
Ted Kremenek28a71942010-11-13 00:36:47 +00001986void EnqueueVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
1987 EnqueueChildren(E);
1988 AddTypeLoc(E->getTypeInfoAsWritten());
1989}
1990void EnqueueVisitor::VisitForStmt(ForStmt *FS) {
1991 AddStmt(FS->getBody());
1992 AddStmt(FS->getInc());
1993 AddStmt(FS->getCond());
1994 AddDecl(FS->getConditionVariable());
1995 AddStmt(FS->getInit());
1996}
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001997void EnqueueVisitor::VisitGotoStmt(GotoStmt *GS) {
1998 WL.push_back(LabelRefVisit(GS->getLabel(), GS->getLabelLoc(), Parent));
1999}
Ted Kremenek28a71942010-11-13 00:36:47 +00002000void EnqueueVisitor::VisitIfStmt(IfStmt *If) {
2001 AddStmt(If->getElse());
2002 AddStmt(If->getThen());
2003 AddStmt(If->getCond());
2004 AddDecl(If->getConditionVariable());
2005}
2006void EnqueueVisitor::VisitInitListExpr(InitListExpr *IE) {
2007 // We care about the syntactic form of the initializer list, only.
2008 if (InitListExpr *Syntactic = IE->getSyntacticForm())
2009 IE = Syntactic;
2010 EnqueueChildren(IE);
2011}
2012void EnqueueVisitor::VisitMemberExpr(MemberExpr *M) {
Douglas Gregor89629a72010-11-17 17:15:08 +00002013 WL.push_back(MemberExprParts(M, Parent));
2014
2015 // If the base of the member access expression is an implicit 'this', don't
2016 // visit it.
2017 // FIXME: If we ever want to show these implicit accesses, this will be
2018 // unfortunate. However, clang_getCursor() relies on this behavior.
Douglas Gregor75e85042011-03-02 21:06:53 +00002019 if (!M->isImplicitAccess())
2020 AddStmt(M->getBase());
Ted Kremenek28a71942010-11-13 00:36:47 +00002021}
Ted Kremenek73d15c42010-11-13 01:09:29 +00002022void EnqueueVisitor::VisitObjCEncodeExpr(ObjCEncodeExpr *E) {
2023 AddTypeLoc(E->getEncodedTypeSourceInfo());
2024}
Ted Kremenek28a71942010-11-13 00:36:47 +00002025void EnqueueVisitor::VisitObjCMessageExpr(ObjCMessageExpr *M) {
2026 EnqueueChildren(M);
2027 AddTypeLoc(M->getClassReceiverTypeInfo());
2028}
Ted Kremenekcdba6592010-11-18 00:42:18 +00002029void EnqueueVisitor::VisitOffsetOfExpr(OffsetOfExpr *E) {
2030 // Visit the components of the offsetof expression.
2031 for (unsigned N = E->getNumComponents(), I = N; I > 0; --I) {
2032 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
2033 const OffsetOfNode &Node = E->getComponent(I-1);
2034 switch (Node.getKind()) {
2035 case OffsetOfNode::Array:
2036 AddStmt(E->getIndexExpr(Node.getArrayExprIndex()));
2037 break;
2038 case OffsetOfNode::Field:
Abramo Bagnara06dec892011-03-12 09:45:03 +00002039 AddMemberRef(Node.getField(), Node.getSourceRange().getEnd());
Ted Kremenekcdba6592010-11-18 00:42:18 +00002040 break;
2041 case OffsetOfNode::Identifier:
2042 case OffsetOfNode::Base:
2043 continue;
2044 }
2045 }
2046 // Visit the type into which we're computing the offset.
2047 AddTypeLoc(E->getTypeSourceInfo());
2048}
Ted Kremenek28a71942010-11-13 00:36:47 +00002049void EnqueueVisitor::VisitOverloadExpr(OverloadExpr *E) {
Ted Kremenek60608ec2010-11-17 00:50:47 +00002050 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
Ted Kremenek60458782010-11-12 21:34:16 +00002051 WL.push_back(OverloadExprParts(E, Parent));
2052}
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002053void EnqueueVisitor::VisitUnaryExprOrTypeTraitExpr(
2054 UnaryExprOrTypeTraitExpr *E) {
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00002055 EnqueueChildren(E);
2056 if (E->isArgumentType())
2057 AddTypeLoc(E->getArgumentTypeInfo());
2058}
Ted Kremenek28a71942010-11-13 00:36:47 +00002059void EnqueueVisitor::VisitStmt(Stmt *S) {
2060 EnqueueChildren(S);
2061}
2062void EnqueueVisitor::VisitSwitchStmt(SwitchStmt *S) {
2063 AddStmt(S->getBody());
2064 AddStmt(S->getCond());
2065 AddDecl(S->getConditionVariable());
2066}
Ted Kremenekfafa75a2010-11-17 00:50:39 +00002067
Ted Kremenek28a71942010-11-13 00:36:47 +00002068void EnqueueVisitor::VisitWhileStmt(WhileStmt *W) {
2069 AddStmt(W->getBody());
2070 AddStmt(W->getCond());
2071 AddDecl(W->getConditionVariable());
2072}
Ted Kremenek2939b6f2010-11-17 00:50:50 +00002073void EnqueueVisitor::VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E) {
2074 AddTypeLoc(E->getQueriedTypeSourceInfo());
2075}
Francois Pichet6ad6f282010-12-07 00:08:36 +00002076
2077void EnqueueVisitor::VisitBinaryTypeTraitExpr(BinaryTypeTraitExpr *E) {
Francois Pichet6ad6f282010-12-07 00:08:36 +00002078 AddTypeLoc(E->getRhsTypeSourceInfo());
Francois Pichet0a03a3f2010-12-08 09:11:05 +00002079 AddTypeLoc(E->getLhsTypeSourceInfo());
Francois Pichet6ad6f282010-12-07 00:08:36 +00002080}
2081
John Wiegley55262202011-04-25 06:54:41 +00002082void EnqueueVisitor::VisitExpressionTraitExpr(ExpressionTraitExpr *E) {
2083 EnqueueChildren(E);
2084}
2085
Ted Kremenek28a71942010-11-13 00:36:47 +00002086void EnqueueVisitor::VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U) {
2087 VisitOverloadExpr(U);
2088 if (!U->isImplicitAccess())
2089 AddStmt(U->getBase());
2090}
Ted Kremenek9d3bf792010-11-17 00:50:43 +00002091void EnqueueVisitor::VisitVAArgExpr(VAArgExpr *E) {
2092 AddStmt(E->getSubExpr());
2093 AddTypeLoc(E->getWrittenTypeInfo());
2094}
Douglas Gregor94d96292011-01-19 20:34:17 +00002095void EnqueueVisitor::VisitSizeOfPackExpr(SizeOfPackExpr *E) {
2096 WL.push_back(SizeOfPackExprParts(E, Parent));
2097}
Ted Kremenek60458782010-11-12 21:34:16 +00002098
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002099void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, Stmt *S) {
Ted Kremenek28a71942010-11-13 00:36:47 +00002100 EnqueueVisitor(WL, MakeCXCursor(S, StmtParent, TU)).Visit(S);
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002101}
2102
2103bool CursorVisitor::IsInRegionOfInterest(CXCursor C) {
2104 if (RegionOfInterest.isValid()) {
2105 SourceRange Range = getRawCursorExtent(C);
2106 if (Range.isInvalid() || CompareRegionOfInterest(Range))
2107 return false;
2108 }
2109 return true;
2110}
2111
2112bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) {
2113 while (!WL.empty()) {
2114 // Dequeue the worklist item.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002115 VisitorJob LI = WL.back();
2116 WL.pop_back();
2117
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002118 // Set the Parent field, then back to its old value once we're done.
2119 SetParentRAII SetParent(Parent, StmtParent, LI.getParent());
2120
2121 switch (LI.getKind()) {
Ted Kremenekf1107452010-11-12 18:26:56 +00002122 case VisitorJob::DeclVisitKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002123 Decl *D = cast<DeclVisit>(&LI)->get();
Ted Kremenekf1107452010-11-12 18:26:56 +00002124 if (!D)
2125 continue;
2126
2127 // For now, perform default visitation for Decls.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002128 if (Visit(MakeCXCursor(D, TU, cast<DeclVisit>(&LI)->isFirst())))
Ted Kremenekf1107452010-11-12 18:26:56 +00002129 return true;
2130
2131 continue;
2132 }
Ted Kremenek60608ec2010-11-17 00:50:47 +00002133 case VisitorJob::ExplicitTemplateArgsVisitKind: {
2134 const ExplicitTemplateArgumentList *ArgList =
2135 cast<ExplicitTemplateArgsVisit>(&LI)->get();
2136 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
2137 *ArgEnd = Arg + ArgList->NumTemplateArgs;
2138 Arg != ArgEnd; ++Arg) {
2139 if (VisitTemplateArgumentLoc(*Arg))
2140 return true;
2141 }
2142 continue;
2143 }
Ted Kremenekcdb4caf2010-11-12 21:34:12 +00002144 case VisitorJob::TypeLocVisitKind: {
2145 // Perform default visitation for TypeLocs.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002146 if (Visit(cast<TypeLocVisit>(&LI)->get()))
Ted Kremenekcdb4caf2010-11-12 21:34:12 +00002147 return true;
2148 continue;
2149 }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00002150 case VisitorJob::LabelRefVisitKind: {
Chris Lattnerad8dcf42011-02-17 07:39:24 +00002151 LabelDecl *LS = cast<LabelRefVisit>(&LI)->get();
Ted Kremeneke7455012011-02-23 04:54:51 +00002152 if (LabelStmt *stmt = LS->getStmt()) {
2153 if (Visit(MakeCursorLabelRef(stmt, cast<LabelRefVisit>(&LI)->getLoc(),
2154 TU))) {
2155 return true;
2156 }
2157 }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00002158 continue;
2159 }
Douglas Gregorf3db29f2011-02-25 18:19:59 +00002160
Ted Kremenekf64d8032010-11-18 00:02:32 +00002161 case VisitorJob::NestedNameSpecifierVisitKind: {
2162 NestedNameSpecifierVisit *V = cast<NestedNameSpecifierVisit>(&LI);
2163 if (VisitNestedNameSpecifier(V->get(), V->getSourceRange()))
2164 return true;
2165 continue;
2166 }
Douglas Gregorf3db29f2011-02-25 18:19:59 +00002167
2168 case VisitorJob::NestedNameSpecifierLocVisitKind: {
2169 NestedNameSpecifierLocVisit *V = cast<NestedNameSpecifierLocVisit>(&LI);
2170 if (VisitNestedNameSpecifierLoc(V->get()))
2171 return true;
2172 continue;
2173 }
2174
Ted Kremenekf64d8032010-11-18 00:02:32 +00002175 case VisitorJob::DeclarationNameInfoVisitKind: {
2176 if (VisitDeclarationNameInfo(cast<DeclarationNameInfoVisit>(&LI)
2177 ->get()))
2178 return true;
2179 continue;
2180 }
Ted Kremenekcdba6592010-11-18 00:42:18 +00002181 case VisitorJob::MemberRefVisitKind: {
2182 MemberRefVisit *V = cast<MemberRefVisit>(&LI);
2183 if (Visit(MakeCursorMemberRef(V->get(), V->getLoc(), TU)))
2184 return true;
2185 continue;
2186 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002187 case VisitorJob::StmtVisitKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002188 Stmt *S = cast<StmtVisit>(&LI)->get();
Ted Kremenek8c269ac2010-11-11 23:11:43 +00002189 if (!S)
2190 continue;
2191
Ted Kremenekf1107452010-11-12 18:26:56 +00002192 // Update the current cursor.
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002193 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU);
Ted Kremenekcdba6592010-11-18 00:42:18 +00002194 if (!IsInRegionOfInterest(Cursor))
2195 continue;
2196 switch (Visitor(Cursor, Parent, ClientData)) {
2197 case CXChildVisit_Break: return true;
2198 case CXChildVisit_Continue: break;
2199 case CXChildVisit_Recurse:
2200 EnqueueWorkList(WL, S);
Ted Kremenek82f3c502010-11-15 22:23:26 +00002201 break;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002202 }
Ted Kremenek82f3c502010-11-15 22:23:26 +00002203 continue;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002204 }
2205 case VisitorJob::MemberExprPartsKind: {
2206 // Handle the other pieces in the MemberExpr besides the base.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002207 MemberExpr *M = cast<MemberExprParts>(&LI)->get();
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002208
2209 // Visit the nested-name-specifier
Douglas Gregor40d96a62011-02-28 21:54:11 +00002210 if (NestedNameSpecifierLoc QualifierLoc = M->getQualifierLoc())
2211 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002212 return true;
2213
2214 // Visit the declaration name.
2215 if (VisitDeclarationNameInfo(M->getMemberNameInfo()))
2216 return true;
2217
2218 // Visit the explicitly-specified template arguments, if any.
2219 if (M->hasExplicitTemplateArgs()) {
2220 for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(),
2221 *ArgEnd = Arg + M->getNumTemplateArgs();
2222 Arg != ArgEnd; ++Arg) {
2223 if (VisitTemplateArgumentLoc(*Arg))
2224 return true;
2225 }
2226 }
2227 continue;
2228 }
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002229 case VisitorJob::DeclRefExprPartsKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002230 DeclRefExpr *DR = cast<DeclRefExprParts>(&LI)->get();
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002231 // Visit nested-name-specifier, if present.
Douglas Gregor40d96a62011-02-28 21:54:11 +00002232 if (NestedNameSpecifierLoc QualifierLoc = DR->getQualifierLoc())
2233 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002234 return true;
2235 // Visit declaration name.
2236 if (VisitDeclarationNameInfo(DR->getNameInfo()))
2237 return true;
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002238 continue;
2239 }
Ted Kremenek60458782010-11-12 21:34:16 +00002240 case VisitorJob::OverloadExprPartsKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002241 OverloadExpr *O = cast<OverloadExprParts>(&LI)->get();
Ted Kremenek60458782010-11-12 21:34:16 +00002242 // Visit the nested-name-specifier.
Douglas Gregor4c9be892011-02-28 20:01:57 +00002243 if (NestedNameSpecifierLoc QualifierLoc = O->getQualifierLoc())
2244 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Ted Kremenek60458782010-11-12 21:34:16 +00002245 return true;
2246 // Visit the declaration name.
2247 if (VisitDeclarationNameInfo(O->getNameInfo()))
2248 return true;
2249 // Visit the overloaded declaration reference.
2250 if (Visit(MakeCursorOverloadedDeclRef(O, TU)))
2251 return true;
Ted Kremenek60458782010-11-12 21:34:16 +00002252 continue;
2253 }
Douglas Gregor94d96292011-01-19 20:34:17 +00002254 case VisitorJob::SizeOfPackExprPartsKind: {
2255 SizeOfPackExpr *E = cast<SizeOfPackExprParts>(&LI)->get();
2256 NamedDecl *Pack = E->getPack();
2257 if (isa<TemplateTypeParmDecl>(Pack)) {
2258 if (Visit(MakeCursorTypeRef(cast<TemplateTypeParmDecl>(Pack),
2259 E->getPackLoc(), TU)))
2260 return true;
2261
2262 continue;
2263 }
2264
2265 if (isa<TemplateTemplateParmDecl>(Pack)) {
2266 if (Visit(MakeCursorTemplateRef(cast<TemplateTemplateParmDecl>(Pack),
2267 E->getPackLoc(), TU)))
2268 return true;
2269
2270 continue;
2271 }
2272
2273 // Non-type template parameter packs and function parameter packs are
2274 // treated like DeclRefExpr cursors.
2275 continue;
2276 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002277 }
2278 }
2279 return false;
2280}
2281
Ted Kremenekcdba6592010-11-18 00:42:18 +00002282bool CursorVisitor::Visit(Stmt *S) {
Ted Kremenekd1ded662010-11-15 23:31:32 +00002283 VisitorWorkList *WL = 0;
2284 if (!WorkListFreeList.empty()) {
2285 WL = WorkListFreeList.back();
2286 WL->clear();
2287 WorkListFreeList.pop_back();
2288 }
2289 else {
2290 WL = new VisitorWorkList();
2291 WorkListCache.push_back(WL);
2292 }
2293 EnqueueWorkList(*WL, S);
2294 bool result = RunVisitorWorkList(*WL);
2295 WorkListFreeList.push_back(WL);
2296 return result;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002297}
2298
2299//===----------------------------------------------------------------------===//
2300// Misc. API hooks.
2301//===----------------------------------------------------------------------===//
2302
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002303static llvm::sys::Mutex EnableMultithreadingMutex;
2304static bool EnabledMultithreading;
2305
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00002306extern "C" {
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002307CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
2308 int displayDiagnostics) {
Daniel Dunbar48615ff2010-10-08 19:30:33 +00002309 // Disable pretty stack trace functionality, which will otherwise be a very
2310 // poor citizen of the world and set up all sorts of signal handlers.
2311 llvm::DisablePrettyStackTrace = true;
2312
Daniel Dunbarc7df4f32010-08-18 18:43:14 +00002313 // We use crash recovery to make some of our APIs more reliable, implicitly
2314 // enable it.
2315 llvm::CrashRecoveryContext::Enable();
2316
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002317 // Enable support for multithreading in LLVM.
2318 {
2319 llvm::sys::ScopedLock L(EnableMultithreadingMutex);
2320 if (!EnabledMultithreading) {
2321 llvm::llvm_start_multithreaded();
2322 EnabledMultithreading = true;
2323 }
2324 }
2325
Douglas Gregora030b7c2010-01-22 20:35:53 +00002326 CIndexer *CIdxr = new CIndexer();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002327 if (excludeDeclarationsFromPCH)
2328 CIdxr->setOnlyLocalDecls();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002329 if (displayDiagnostics)
2330 CIdxr->setDisplayDiagnostics();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002331 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +00002332}
2333
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002334void clang_disposeIndex(CXIndex CIdx) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002335 if (CIdx)
2336 delete static_cast<CIndexer *>(CIdx);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002337}
2338
Ted Kremenekd2427dd2011-03-18 23:05:39 +00002339void clang_toggleCrashRecovery(unsigned isEnabled) {
2340 if (isEnabled)
2341 llvm::CrashRecoveryContext::Enable();
2342 else
2343 llvm::CrashRecoveryContext::Disable();
2344}
2345
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002346CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
Douglas Gregora88084b2010-02-18 18:08:43 +00002347 const char *ast_filename) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002348 if (!CIdx)
2349 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002350
Douglas Gregor7d1d49d2009-10-16 20:01:17 +00002351 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00002352 FileSystemOptions FileSystemOpts;
2353 FileSystemOpts.WorkingDir = CXXIdx->getWorkingDirectory();
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002354
Douglas Gregor28019772010-04-05 23:52:57 +00002355 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
Ted Kremeneka60ed472010-11-16 08:15:36 +00002356 ASTUnit *TU = ASTUnit::LoadFromASTFile(ast_filename, Diags, FileSystemOpts,
Douglas Gregora88084b2010-02-18 18:08:43 +00002357 CXXIdx->getOnlyLocalDecls(),
2358 0, 0, true);
Ted Kremeneka60ed472010-11-16 08:15:36 +00002359 return MakeCXTranslationUnit(TU);
Steve Naroff600866c2009-08-27 19:51:58 +00002360}
2361
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002362unsigned clang_defaultEditingTranslationUnitOptions() {
Douglas Gregor2a2c50b2010-09-27 05:49:58 +00002363 return CXTranslationUnit_PrecompiledPreamble |
Douglas Gregor99ba2022010-10-27 17:24:53 +00002364 CXTranslationUnit_CacheCompletionResults |
2365 CXTranslationUnit_CXXPrecompiledPreamble;
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002366}
2367
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002368CXTranslationUnit
2369clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
2370 const char *source_filename,
2371 int num_command_line_args,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002372 const char * const *command_line_args,
Douglas Gregor4db64a42010-01-23 00:14:00 +00002373 unsigned num_unsaved_files,
Douglas Gregora88084b2010-02-18 18:08:43 +00002374 struct CXUnsavedFile *unsaved_files) {
Douglas Gregor5a430212010-07-21 18:52:53 +00002375 return clang_parseTranslationUnit(CIdx, source_filename,
2376 command_line_args, num_command_line_args,
2377 unsaved_files, num_unsaved_files,
2378 CXTranslationUnit_DetailedPreprocessingRecord);
2379}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002380
2381struct ParseTranslationUnitInfo {
2382 CXIndex CIdx;
2383 const char *source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002384 const char *const *command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002385 int num_command_line_args;
2386 struct CXUnsavedFile *unsaved_files;
2387 unsigned num_unsaved_files;
2388 unsigned options;
2389 CXTranslationUnit result;
2390};
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002391static void clang_parseTranslationUnit_Impl(void *UserData) {
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002392 ParseTranslationUnitInfo *PTUI =
2393 static_cast<ParseTranslationUnitInfo*>(UserData);
2394 CXIndex CIdx = PTUI->CIdx;
2395 const char *source_filename = PTUI->source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002396 const char * const *command_line_args = PTUI->command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002397 int num_command_line_args = PTUI->num_command_line_args;
2398 struct CXUnsavedFile *unsaved_files = PTUI->unsaved_files;
2399 unsigned num_unsaved_files = PTUI->num_unsaved_files;
2400 unsigned options = PTUI->options;
2401 PTUI->result = 0;
Douglas Gregor5a430212010-07-21 18:52:53 +00002402
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002403 if (!CIdx)
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002404 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002405
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002406 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
2407
Douglas Gregor44c181a2010-07-23 00:33:23 +00002408 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Douglas Gregordf95a132010-08-09 20:45:32 +00002409 bool CompleteTranslationUnit
2410 = ((options & CXTranslationUnit_Incomplete) == 0);
Douglas Gregor87c08a52010-08-13 22:48:40 +00002411 bool CacheCodeCompetionResults
2412 = options & CXTranslationUnit_CacheCompletionResults;
Douglas Gregor99ba2022010-10-27 17:24:53 +00002413 bool CXXPrecompilePreamble
2414 = options & CXTranslationUnit_CXXPrecompiledPreamble;
2415 bool CXXChainedPCH
2416 = options & CXTranslationUnit_CXXChainedPCH;
Douglas Gregor87c08a52010-08-13 22:48:40 +00002417
Douglas Gregor5352ac02010-01-28 00:27:43 +00002418 // Configure the diagnostics.
2419 DiagnosticOptions DiagOpts;
Ted Kremenek25a11e12011-03-22 01:15:24 +00002420 llvm::IntrusiveRefCntPtr<Diagnostic>
2421 Diags(CompilerInstance::createDiagnostics(DiagOpts, num_command_line_args,
2422 command_line_args));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002423
Ted Kremenek25a11e12011-03-22 01:15:24 +00002424 // Recover resources if we crash before exiting this function.
2425 llvm::CrashRecoveryContextCleanupRegistrar<Diagnostic,
2426 llvm::CrashRecoveryContextReleaseRefCleanup<Diagnostic> >
2427 DiagCleanup(Diags.getPtr());
2428
2429 llvm::OwningPtr<std::vector<ASTUnit::RemappedFile> >
2430 RemappedFiles(new std::vector<ASTUnit::RemappedFile>());
2431
2432 // Recover resources if we crash before exiting this function.
2433 llvm::CrashRecoveryContextCleanupRegistrar<
2434 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
2435
Douglas Gregor4db64a42010-01-23 00:14:00 +00002436 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattnera0a270c2010-04-05 22:42:27 +00002437 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002438 const llvm::MemoryBuffer *Buffer
Chris Lattnera0a270c2010-04-05 22:42:27 +00002439 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Ted Kremenek25a11e12011-03-22 01:15:24 +00002440 RemappedFiles->push_back(std::make_pair(unsaved_files[I].Filename,
2441 Buffer));
Douglas Gregor4db64a42010-01-23 00:14:00 +00002442 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002443
Ted Kremenek25a11e12011-03-22 01:15:24 +00002444 llvm::OwningPtr<std::vector<const char *> >
2445 Args(new std::vector<const char*>());
2446
2447 // Recover resources if we crash before exiting this method.
2448 llvm::CrashRecoveryContextCleanupRegistrar<std::vector<const char*> >
2449 ArgsCleanup(Args.get());
2450
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00002451 // Since the Clang C library is primarily used by batch tools dealing with
2452 // (often very broken) source code, where spell-checking can have a
2453 // significant negative impact on performance (particularly when
2454 // precompiled headers are involved), we disable it by default.
Douglas Gregorb10daed2010-10-11 16:52:23 +00002455 // Only do this if we haven't found a spell-checking-related argument.
2456 bool FoundSpellCheckingArgument = false;
2457 for (int I = 0; I != num_command_line_args; ++I) {
2458 if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
2459 strcmp(command_line_args[I], "-fspell-checking") == 0) {
2460 FoundSpellCheckingArgument = true;
2461 break;
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002462 }
Douglas Gregorb10daed2010-10-11 16:52:23 +00002463 }
2464 if (!FoundSpellCheckingArgument)
Ted Kremenek25a11e12011-03-22 01:15:24 +00002465 Args->push_back("-fno-spell-checking");
Douglas Gregorb10daed2010-10-11 16:52:23 +00002466
Ted Kremenek25a11e12011-03-22 01:15:24 +00002467 Args->insert(Args->end(), command_line_args,
2468 command_line_args + num_command_line_args);
Douglas Gregord93256e2010-01-28 06:00:51 +00002469
Argyrios Kyrtzidisc8429552011-03-20 18:17:52 +00002470 // The 'source_filename' argument is optional. If the caller does not
2471 // specify it then it is assumed that the source file is specified
2472 // in the actual argument list.
2473 // Put the source file after command_line_args otherwise if '-x' flag is
2474 // present it will be unused.
2475 if (source_filename)
Ted Kremenek25a11e12011-03-22 01:15:24 +00002476 Args->push_back(source_filename);
Argyrios Kyrtzidisc8429552011-03-20 18:17:52 +00002477
Douglas Gregor44c181a2010-07-23 00:33:23 +00002478 // Do we need the detailed preprocessing record?
2479 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
Ted Kremenek25a11e12011-03-22 01:15:24 +00002480 Args->push_back("-Xclang");
2481 Args->push_back("-detailed-preprocessing-record");
Douglas Gregor44c181a2010-07-23 00:33:23 +00002482 }
2483
Argyrios Kyrtzidis026f6912010-11-18 21:47:04 +00002484 unsigned NumErrors = Diags->getClient()->getNumErrors();
Douglas Gregorb10daed2010-10-11 16:52:23 +00002485 llvm::OwningPtr<ASTUnit> Unit(
Ted Kremenek4ee99262011-03-22 20:16:19 +00002486 ASTUnit::LoadFromCommandLine(Args->size() ? &(*Args)[0] : 0
2487 /* vector::data() not portable */,
2488 Args->size() ? (&(*Args)[0] + Args->size()) :0,
Douglas Gregorb10daed2010-10-11 16:52:23 +00002489 Diags,
2490 CXXIdx->getClangResourcesPath(),
2491 CXXIdx->getOnlyLocalDecls(),
Douglas Gregore47be3e2010-11-11 00:39:14 +00002492 /*CaptureDiagnostics=*/true,
Ted Kremenek4ee99262011-03-22 20:16:19 +00002493 RemappedFiles->size() ? &(*RemappedFiles)[0]:0,
Ted Kremenek25a11e12011-03-22 01:15:24 +00002494 RemappedFiles->size(),
Argyrios Kyrtzidis299a4a92011-03-08 23:35:24 +00002495 /*RemappedFilesKeepOriginalName=*/true,
Douglas Gregorb10daed2010-10-11 16:52:23 +00002496 PrecompilePreamble,
2497 CompleteTranslationUnit,
Douglas Gregor99ba2022010-10-27 17:24:53 +00002498 CacheCodeCompetionResults,
2499 CXXPrecompilePreamble,
2500 CXXChainedPCH));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002501
Argyrios Kyrtzidis026f6912010-11-18 21:47:04 +00002502 if (NumErrors != Diags->getClient()->getNumErrors()) {
Douglas Gregorb10daed2010-10-11 16:52:23 +00002503 // Make sure to check that 'Unit' is non-NULL.
2504 if (CXXIdx->getDisplayDiagnostics() && Unit.get()) {
2505 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
2506 DEnd = Unit->stored_diag_end();
2507 D != DEnd; ++D) {
2508 CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOptions());
2509 CXString Msg = clang_formatDiagnostic(&Diag,
2510 clang_defaultDiagnosticDisplayOptions());
2511 fprintf(stderr, "%s\n", clang_getCString(Msg));
2512 clang_disposeString(Msg);
2513 }
Douglas Gregor274f1902010-02-22 23:17:23 +00002514#ifdef LLVM_ON_WIN32
Douglas Gregorb10daed2010-10-11 16:52:23 +00002515 // On Windows, force a flush, since there may be multiple copies of
2516 // stderr and stdout in the file system, all with different buffers
2517 // but writing to the same device.
2518 fflush(stderr);
2519#endif
2520 }
Douglas Gregora88084b2010-02-18 18:08:43 +00002521 }
Douglas Gregord93256e2010-01-28 06:00:51 +00002522
Ted Kremeneka60ed472010-11-16 08:15:36 +00002523 PTUI->result = MakeCXTranslationUnit(Unit.take());
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002524}
2525CXTranslationUnit clang_parseTranslationUnit(CXIndex CIdx,
2526 const char *source_filename,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002527 const char * const *command_line_args,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002528 int num_command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002529 struct CXUnsavedFile *unsaved_files,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002530 unsigned num_unsaved_files,
2531 unsigned options) {
2532 ParseTranslationUnitInfo PTUI = { CIdx, source_filename, command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002533 num_command_line_args, unsaved_files,
2534 num_unsaved_files, options, 0 };
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002535 llvm::CrashRecoveryContext CRC;
2536
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002537 if (!RunSafely(CRC, clang_parseTranslationUnit_Impl, &PTUI)) {
Daniel Dunbar60a45432010-08-23 22:35:34 +00002538 fprintf(stderr, "libclang: crash detected during parsing: {\n");
2539 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
2540 fprintf(stderr, " 'command_line_args' : [");
2541 for (int i = 0; i != num_command_line_args; ++i) {
2542 if (i)
2543 fprintf(stderr, ", ");
2544 fprintf(stderr, "'%s'", command_line_args[i]);
2545 }
2546 fprintf(stderr, "],\n");
2547 fprintf(stderr, " 'unsaved_files' : [");
2548 for (unsigned i = 0; i != num_unsaved_files; ++i) {
2549 if (i)
2550 fprintf(stderr, ", ");
2551 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
2552 unsaved_files[i].Length);
2553 }
2554 fprintf(stderr, "],\n");
2555 fprintf(stderr, " 'options' : %d,\n", options);
2556 fprintf(stderr, "}\n");
2557
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002558 return 0;
2559 }
2560
2561 return PTUI.result;
Steve Naroff5b7d8e22009-10-15 20:04:39 +00002562}
2563
Douglas Gregor19998442010-08-13 15:35:05 +00002564unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
2565 return CXSaveTranslationUnit_None;
2566}
2567
2568int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
2569 unsigned options) {
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002570 if (!TU)
2571 return 1;
2572
Ted Kremeneka60ed472010-11-16 08:15:36 +00002573 return static_cast<ASTUnit *>(TU->TUData)->Save(FileName);
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002574}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002575
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002576void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002577 if (CTUnit) {
2578 // If the translation unit has been marked as unsafe to free, just discard
2579 // it.
Ted Kremeneka60ed472010-11-16 08:15:36 +00002580 if (static_cast<ASTUnit *>(CTUnit->TUData)->isUnsafeToFree())
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002581 return;
2582
Ted Kremeneka60ed472010-11-16 08:15:36 +00002583 delete static_cast<ASTUnit *>(CTUnit->TUData);
2584 disposeCXStringPool(CTUnit->StringPool);
2585 delete CTUnit;
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002586 }
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002587}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002588
Douglas Gregore1e13bf2010-08-11 15:58:42 +00002589unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
2590 return CXReparse_None;
2591}
2592
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002593struct ReparseTranslationUnitInfo {
2594 CXTranslationUnit TU;
2595 unsigned num_unsaved_files;
2596 struct CXUnsavedFile *unsaved_files;
2597 unsigned options;
2598 int result;
2599};
Douglas Gregor593b0c12010-09-23 18:47:53 +00002600
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002601static void clang_reparseTranslationUnit_Impl(void *UserData) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002602 ReparseTranslationUnitInfo *RTUI =
2603 static_cast<ReparseTranslationUnitInfo*>(UserData);
2604 CXTranslationUnit TU = RTUI->TU;
2605 unsigned num_unsaved_files = RTUI->num_unsaved_files;
2606 struct CXUnsavedFile *unsaved_files = RTUI->unsaved_files;
2607 unsigned options = RTUI->options;
2608 (void) options;
2609 RTUI->result = 1;
2610
Douglas Gregorabc563f2010-07-19 21:46:24 +00002611 if (!TU)
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002612 return;
Douglas Gregor593b0c12010-09-23 18:47:53 +00002613
Ted Kremeneka60ed472010-11-16 08:15:36 +00002614 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor593b0c12010-09-23 18:47:53 +00002615 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002616
Ted Kremenek25a11e12011-03-22 01:15:24 +00002617 llvm::OwningPtr<std::vector<ASTUnit::RemappedFile> >
2618 RemappedFiles(new std::vector<ASTUnit::RemappedFile>());
2619
2620 // Recover resources if we crash before exiting this function.
2621 llvm::CrashRecoveryContextCleanupRegistrar<
2622 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
2623
Douglas Gregorabc563f2010-07-19 21:46:24 +00002624 for (unsigned I = 0; I != num_unsaved_files; ++I) {
2625 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
2626 const llvm::MemoryBuffer *Buffer
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002627 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Ted Kremenek25a11e12011-03-22 01:15:24 +00002628 RemappedFiles->push_back(std::make_pair(unsaved_files[I].Filename,
2629 Buffer));
Douglas Gregorabc563f2010-07-19 21:46:24 +00002630 }
2631
Ted Kremenek4ee99262011-03-22 20:16:19 +00002632 if (!CXXUnit->Reparse(RemappedFiles->size() ? &(*RemappedFiles)[0] : 0,
2633 RemappedFiles->size()))
Douglas Gregor593b0c12010-09-23 18:47:53 +00002634 RTUI->result = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00002635}
Douglas Gregor593b0c12010-09-23 18:47:53 +00002636
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002637int clang_reparseTranslationUnit(CXTranslationUnit TU,
2638 unsigned num_unsaved_files,
2639 struct CXUnsavedFile *unsaved_files,
2640 unsigned options) {
2641 ReparseTranslationUnitInfo RTUI = { TU, num_unsaved_files, unsaved_files,
2642 options, 0 };
2643 llvm::CrashRecoveryContext CRC;
2644
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002645 if (!RunSafely(CRC, clang_reparseTranslationUnit_Impl, &RTUI)) {
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002646 fprintf(stderr, "libclang: crash detected during reparsing\n");
Ted Kremeneka60ed472010-11-16 08:15:36 +00002647 static_cast<ASTUnit *>(TU->TUData)->setUnsafeToFree(true);
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002648 return 1;
2649 }
2650
Ted Kremenek1dfb26a2010-10-29 01:06:50 +00002651
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002652 return RTUI.result;
2653}
2654
Douglas Gregordf95a132010-08-09 20:45:32 +00002655
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002656CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002657 if (!CTUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002658 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002659
Ted Kremeneka60ed472010-11-16 08:15:36 +00002660 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit->TUData);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002661 return createCXString(CXXUnit->getOriginalSourceFileName(), true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +00002662}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +00002663
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002664CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002665 CXCursor Result = { CXCursor_TranslationUnit, { 0, 0, TU } };
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002666 return Result;
2667}
2668
Ted Kremenekfb480492010-01-13 21:46:36 +00002669} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +00002670
Ted Kremenekfb480492010-01-13 21:46:36 +00002671//===----------------------------------------------------------------------===//
Douglas Gregor1db19de2010-01-19 21:36:55 +00002672// CXSourceLocation and CXSourceRange Operations.
2673//===----------------------------------------------------------------------===//
2674
Douglas Gregorb9790342010-01-22 21:44:22 +00002675extern "C" {
2676CXSourceLocation clang_getNullLocation() {
Douglas Gregor5352ac02010-01-28 00:27:43 +00002677 CXSourceLocation Result = { { 0, 0 }, 0 };
Douglas Gregorb9790342010-01-22 21:44:22 +00002678 return Result;
2679}
2680
2681unsigned clang_equalLocations(CXSourceLocation loc1, CXSourceLocation loc2) {
Daniel Dunbar90a6b9e2010-01-30 23:58:27 +00002682 return (loc1.ptr_data[0] == loc2.ptr_data[0] &&
2683 loc1.ptr_data[1] == loc2.ptr_data[1] &&
2684 loc1.int_data == loc2.int_data);
Douglas Gregorb9790342010-01-22 21:44:22 +00002685}
2686
2687CXSourceLocation clang_getLocation(CXTranslationUnit tu,
2688 CXFile file,
2689 unsigned line,
2690 unsigned column) {
Douglas Gregor42748ec2010-04-30 19:45:53 +00002691 if (!tu || !file)
Douglas Gregorb9790342010-01-22 21:44:22 +00002692 return clang_getNullLocation();
Douglas Gregor42748ec2010-04-30 19:45:53 +00002693
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00002694 bool Logging = ::getenv("LIBCLANG_LOGGING");
Ted Kremeneka60ed472010-11-16 08:15:36 +00002695 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00002696 const FileEntry *File = static_cast<const FileEntry *>(file);
Douglas Gregorb9790342010-01-22 21:44:22 +00002697 SourceLocation SLoc
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00002698 = CXXUnit->getSourceManager().getLocation(File, line, column);
2699 if (SLoc.isInvalid()) {
2700 if (Logging)
2701 llvm::errs() << "clang_getLocation(\"" << File->getName()
2702 << "\", " << line << ", " << column << ") = invalid\n";
2703 return clang_getNullLocation();
2704 }
2705
2706 if (Logging)
2707 llvm::errs() << "clang_getLocation(\"" << File->getName()
2708 << "\", " << line << ", " << column << ") = "
2709 << SLoc.getRawEncoding() << "\n";
David Chisnall83889a72010-10-15 17:07:39 +00002710
2711 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
2712}
2713
2714CXSourceLocation clang_getLocationForOffset(CXTranslationUnit tu,
2715 CXFile file,
2716 unsigned offset) {
2717 if (!tu || !file)
2718 return clang_getNullLocation();
2719
Ted Kremeneka60ed472010-11-16 08:15:36 +00002720 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
David Chisnall83889a72010-10-15 17:07:39 +00002721 SourceLocation Start
2722 = CXXUnit->getSourceManager().getLocation(
2723 static_cast<const FileEntry *>(file),
2724 1, 1);
2725 if (Start.isInvalid()) return clang_getNullLocation();
2726
2727 SourceLocation SLoc = Start.getFileLocWithOffset(offset);
2728
2729 if (SLoc.isInvalid()) return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002730
Ted Kremenek1a9a0bc2010-06-28 23:54:17 +00002731 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
Douglas Gregorb9790342010-01-22 21:44:22 +00002732}
2733
Douglas Gregor5352ac02010-01-28 00:27:43 +00002734CXSourceRange clang_getNullRange() {
2735 CXSourceRange Result = { { 0, 0 }, 0, 0 };
2736 return Result;
2737}
Daniel Dunbard52864b2010-02-14 10:02:57 +00002738
Douglas Gregor5352ac02010-01-28 00:27:43 +00002739CXSourceRange clang_getRange(CXSourceLocation begin, CXSourceLocation end) {
2740 if (begin.ptr_data[0] != end.ptr_data[0] ||
2741 begin.ptr_data[1] != end.ptr_data[1])
2742 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002743
2744 CXSourceRange Result = { { begin.ptr_data[0], begin.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002745 begin.int_data, end.int_data };
Douglas Gregorb9790342010-01-22 21:44:22 +00002746 return Result;
2747}
Ted Kremenek9d5a1652011-03-23 02:16:44 +00002748} // end: extern "C"
Douglas Gregorb9790342010-01-22 21:44:22 +00002749
Ted Kremenek9d5a1652011-03-23 02:16:44 +00002750static void createNullLocation(CXFile *file, unsigned *line,
2751 unsigned *column, unsigned *offset) {
2752 if (file)
2753 *file = 0;
2754 if (line)
2755 *line = 0;
2756 if (column)
2757 *column = 0;
2758 if (offset)
2759 *offset = 0;
2760 return;
2761}
2762
2763extern "C" {
Douglas Gregor46766dc2010-01-26 19:19:08 +00002764void clang_getInstantiationLocation(CXSourceLocation location,
2765 CXFile *file,
2766 unsigned *line,
2767 unsigned *column,
2768 unsigned *offset) {
Douglas Gregor1db19de2010-01-19 21:36:55 +00002769 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2770
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002771 if (!location.ptr_data[0] || Loc.isInvalid()) {
Ted Kremenek9d5a1652011-03-23 02:16:44 +00002772 createNullLocation(file, line, column, offset);
Douglas Gregor46766dc2010-01-26 19:19:08 +00002773 return;
2774 }
2775
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002776 const SourceManager &SM =
2777 *static_cast<const SourceManager*>(location.ptr_data[0]);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002778 SourceLocation InstLoc = SM.getInstantiationLoc(Loc);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002779
Ted Kremenek9d5a1652011-03-23 02:16:44 +00002780 // Check that the FileID is invalid on the instantiation location.
2781 // This can manifest in invalid code.
2782 FileID fileID = SM.getFileID(InstLoc);
Douglas Gregore23ac652011-04-20 00:21:03 +00002783 bool Invalid = false;
2784 const SrcMgr::SLocEntry &sloc = SM.getSLocEntry(fileID, &Invalid);
2785 if (!sloc.isFile() || Invalid) {
Ted Kremenek9d5a1652011-03-23 02:16:44 +00002786 createNullLocation(file, line, column, offset);
2787 return;
2788 }
2789
Douglas Gregor1db19de2010-01-19 21:36:55 +00002790 if (file)
Ted Kremenek9d5a1652011-03-23 02:16:44 +00002791 *file = (void *)SM.getFileEntryForSLocEntry(sloc);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002792 if (line)
2793 *line = SM.getInstantiationLineNumber(InstLoc);
2794 if (column)
2795 *column = SM.getInstantiationColumnNumber(InstLoc);
Douglas Gregore69517c2010-01-26 03:07:15 +00002796 if (offset)
Douglas Gregor46766dc2010-01-26 19:19:08 +00002797 *offset = SM.getDecomposedLoc(InstLoc).second;
Douglas Gregore69517c2010-01-26 03:07:15 +00002798}
2799
Douglas Gregora9b06d42010-11-09 06:24:54 +00002800void clang_getSpellingLocation(CXSourceLocation location,
2801 CXFile *file,
2802 unsigned *line,
2803 unsigned *column,
2804 unsigned *offset) {
2805 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2806
2807 if (!location.ptr_data[0] || Loc.isInvalid()) {
2808 if (file)
2809 *file = 0;
2810 if (line)
2811 *line = 0;
2812 if (column)
2813 *column = 0;
2814 if (offset)
2815 *offset = 0;
2816 return;
2817 }
2818
2819 const SourceManager &SM =
2820 *static_cast<const SourceManager*>(location.ptr_data[0]);
2821 SourceLocation SpellLoc = Loc;
2822 if (SpellLoc.isMacroID()) {
2823 SourceLocation SimpleSpellingLoc = SM.getImmediateSpellingLoc(SpellLoc);
2824 if (SimpleSpellingLoc.isFileID() &&
2825 SM.getFileEntryForID(SM.getDecomposedLoc(SimpleSpellingLoc).first))
2826 SpellLoc = SimpleSpellingLoc;
2827 else
2828 SpellLoc = SM.getInstantiationLoc(SpellLoc);
2829 }
2830
2831 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(SpellLoc);
2832 FileID FID = LocInfo.first;
2833 unsigned FileOffset = LocInfo.second;
2834
2835 if (file)
2836 *file = (void *)SM.getFileEntryForID(FID);
2837 if (line)
2838 *line = SM.getLineNumber(FID, FileOffset);
2839 if (column)
2840 *column = SM.getColumnNumber(FID, FileOffset);
2841 if (offset)
2842 *offset = FileOffset;
2843}
2844
Douglas Gregor1db19de2010-01-19 21:36:55 +00002845CXSourceLocation clang_getRangeStart(CXSourceRange range) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002846 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002847 range.begin_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002848 return Result;
2849}
2850
2851CXSourceLocation clang_getRangeEnd(CXSourceRange range) {
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002852 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002853 range.end_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002854 return Result;
2855}
2856
Douglas Gregorb9790342010-01-22 21:44:22 +00002857} // end: extern "C"
2858
Douglas Gregor1db19de2010-01-19 21:36:55 +00002859//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00002860// CXFile Operations.
2861//===----------------------------------------------------------------------===//
2862
2863extern "C" {
Ted Kremenek74844072010-02-17 00:41:20 +00002864CXString clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002865 if (!SFile)
Ted Kremeneka60ed472010-11-16 08:15:36 +00002866 return createCXString((const char*)NULL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002867
Steve Naroff88145032009-10-27 14:35:18 +00002868 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Ted Kremenek74844072010-02-17 00:41:20 +00002869 return createCXString(FEnt->getName());
Steve Naroff88145032009-10-27 14:35:18 +00002870}
2871
2872time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002873 if (!SFile)
2874 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002875
Steve Naroff88145032009-10-27 14:35:18 +00002876 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
2877 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +00002878}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002879
Douglas Gregorb9790342010-01-22 21:44:22 +00002880CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
2881 if (!tu)
2882 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002883
Ted Kremeneka60ed472010-11-16 08:15:36 +00002884 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002885
Douglas Gregorb9790342010-01-22 21:44:22 +00002886 FileManager &FMgr = CXXUnit->getFileManager();
Chris Lattner39b49bc2010-11-23 08:35:12 +00002887 return const_cast<FileEntry *>(FMgr.getFile(file_name));
Douglas Gregorb9790342010-01-22 21:44:22 +00002888}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002889
Ted Kremenekfb480492010-01-13 21:46:36 +00002890} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +00002891
Ted Kremenekfb480492010-01-13 21:46:36 +00002892//===----------------------------------------------------------------------===//
2893// CXCursor Operations.
2894//===----------------------------------------------------------------------===//
2895
Ted Kremenekfb480492010-01-13 21:46:36 +00002896static Decl *getDeclFromExpr(Stmt *E) {
Douglas Gregordb1314e2010-10-01 21:11:22 +00002897 if (CastExpr *CE = dyn_cast<CastExpr>(E))
2898 return getDeclFromExpr(CE->getSubExpr());
2899
Ted Kremenekfb480492010-01-13 21:46:36 +00002900 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
2901 return RefExpr->getDecl();
Douglas Gregor38f28c12010-10-22 22:24:08 +00002902 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2903 return RefExpr->getDecl();
Ted Kremenekfb480492010-01-13 21:46:36 +00002904 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
2905 return ME->getMemberDecl();
2906 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
2907 return RE->getDecl();
Douglas Gregordb1314e2010-10-01 21:11:22 +00002908 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E))
John McCall12f78a62010-12-02 01:19:52 +00002909 return PRE->isExplicitProperty() ? PRE->getExplicitProperty() : 0;
Douglas Gregordb1314e2010-10-01 21:11:22 +00002910
Ted Kremenekfb480492010-01-13 21:46:36 +00002911 if (CallExpr *CE = dyn_cast<CallExpr>(E))
2912 return getDeclFromExpr(CE->getCallee());
Douglas Gregor93798e22010-11-05 21:11:19 +00002913 if (CXXConstructExpr *CE = llvm::dyn_cast<CXXConstructExpr>(E))
2914 if (!CE->isElidable())
2915 return CE->getConstructor();
Ted Kremenekfb480492010-01-13 21:46:36 +00002916 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
2917 return OME->getMethodDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002918
Douglas Gregordb1314e2010-10-01 21:11:22 +00002919 if (ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
2920 return PE->getProtocol();
Douglas Gregorc7793c72011-01-15 01:15:58 +00002921 if (SubstNonTypeTemplateParmPackExpr *NTTP
2922 = dyn_cast<SubstNonTypeTemplateParmPackExpr>(E))
2923 return NTTP->getParameterPack();
Douglas Gregor94d96292011-01-19 20:34:17 +00002924 if (SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
2925 if (isa<NonTypeTemplateParmDecl>(SizeOfPack->getPack()) ||
2926 isa<ParmVarDecl>(SizeOfPack->getPack()))
2927 return SizeOfPack->getPack();
Douglas Gregordb1314e2010-10-01 21:11:22 +00002928
Ted Kremenekfb480492010-01-13 21:46:36 +00002929 return 0;
2930}
2931
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002932static SourceLocation getLocationFromExpr(Expr *E) {
2933 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
2934 return /*FIXME:*/Msg->getLeftLoc();
2935 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
2936 return DRE->getLocation();
Douglas Gregor38f28c12010-10-22 22:24:08 +00002937 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2938 return RefExpr->getLocation();
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002939 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
2940 return Member->getMemberLoc();
2941 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
2942 return Ivar->getLocation();
Douglas Gregor94d96292011-01-19 20:34:17 +00002943 if (SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
2944 return SizeOfPack->getPackLoc();
2945
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002946 return E->getLocStart();
2947}
2948
Ted Kremenekfb480492010-01-13 21:46:36 +00002949extern "C" {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002950
2951unsigned clang_visitChildren(CXCursor parent,
Douglas Gregorb1373d02010-01-20 20:59:29 +00002952 CXCursorVisitor visitor,
2953 CXClientData client_data) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00002954 CursorVisitor CursorVis(getCursorTU(parent), visitor, client_data,
Douglas Gregor04a9eb32011-03-16 23:23:30 +00002955 getCursorASTUnit(parent)->getMaxPCHLevel(),
2956 false);
Douglas Gregorb1373d02010-01-20 20:59:29 +00002957 return CursorVis.VisitChildren(parent);
2958}
2959
David Chisnall3387c652010-11-03 14:12:26 +00002960#ifndef __has_feature
2961#define __has_feature(x) 0
2962#endif
2963#if __has_feature(blocks)
2964typedef enum CXChildVisitResult
2965 (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent);
2966
2967static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
2968 CXClientData client_data) {
2969 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
2970 return block(cursor, parent);
2971}
2972#else
2973// If we are compiled with a compiler that doesn't have native blocks support,
2974// define and call the block manually, so the
2975typedef struct _CXChildVisitResult
2976{
2977 void *isa;
2978 int flags;
2979 int reserved;
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002980 enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor,
2981 CXCursor);
David Chisnall3387c652010-11-03 14:12:26 +00002982} *CXCursorVisitorBlock;
2983
2984static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
2985 CXClientData client_data) {
2986 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
2987 return block->invoke(block, cursor, parent);
2988}
2989#endif
2990
2991
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002992unsigned clang_visitChildrenWithBlock(CXCursor parent,
2993 CXCursorVisitorBlock block) {
David Chisnall3387c652010-11-03 14:12:26 +00002994 return clang_visitChildren(parent, visitWithBlock, block);
2995}
2996
Douglas Gregor78205d42010-01-20 21:45:58 +00002997static CXString getDeclSpelling(Decl *D) {
2998 NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
Douglas Gregore3c60a72010-11-17 00:13:31 +00002999 if (!ND) {
3000 if (ObjCPropertyImplDecl *PropImpl =llvm::dyn_cast<ObjCPropertyImplDecl>(D))
3001 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
3002 return createCXString(Property->getIdentifier()->getName());
3003
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003004 return createCXString("");
Douglas Gregore3c60a72010-11-17 00:13:31 +00003005 }
3006
Douglas Gregor78205d42010-01-20 21:45:58 +00003007 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003008 return createCXString(OMD->getSelector().getAsString());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003009
Douglas Gregor78205d42010-01-20 21:45:58 +00003010 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
3011 // No, this isn't the same as the code below. getIdentifier() is non-virtual
3012 // and returns different names. NamedDecl returns the class name and
3013 // ObjCCategoryImplDecl returns the category name.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003014 return createCXString(CIMP->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003015
Douglas Gregor0a35bce2010-09-01 03:07:18 +00003016 if (isa<UsingDirectiveDecl>(D))
3017 return createCXString("");
3018
Ted Kremenek50aa6ac2010-05-19 21:51:10 +00003019 llvm::SmallString<1024> S;
3020 llvm::raw_svector_ostream os(S);
3021 ND->printName(os);
3022
3023 return createCXString(os.str());
Douglas Gregor78205d42010-01-20 21:45:58 +00003024}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003025
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003026CXString clang_getCursorSpelling(CXCursor C) {
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00003027 if (clang_isTranslationUnit(C.kind))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003028 return clang_getTranslationUnitSpelling(
3029 static_cast<CXTranslationUnit>(C.data[2]));
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00003030
Steve Narofff334b4e2009-09-02 18:26:48 +00003031 if (clang_isReference(C.kind)) {
3032 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00003033 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +00003034 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003035 return createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00003036 }
3037 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +00003038 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003039 return createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00003040 }
3041 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +00003042 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +00003043 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003044 return createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00003045 }
Ted Kremenek3064ef92010-08-27 21:34:58 +00003046 case CXCursor_CXXBaseSpecifier: {
3047 CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
3048 return createCXString(B->getType().getAsString());
3049 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003050 case CXCursor_TypeRef: {
3051 TypeDecl *Type = getCursorTypeRef(C).first;
3052 assert(Type && "Missing type decl");
3053
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003054 return createCXString(getCursorContext(C).getTypeDeclType(Type).
3055 getAsString());
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003056 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00003057 case CXCursor_TemplateRef: {
3058 TemplateDecl *Template = getCursorTemplateRef(C).first;
Douglas Gregor69319002010-08-31 23:48:11 +00003059 assert(Template && "Missing template decl");
Douglas Gregor0b36e612010-08-31 20:37:03 +00003060
3061 return createCXString(Template->getNameAsString());
3062 }
Douglas Gregor69319002010-08-31 23:48:11 +00003063
3064 case CXCursor_NamespaceRef: {
3065 NamedDecl *NS = getCursorNamespaceRef(C).first;
3066 assert(NS && "Missing namespace decl");
3067
3068 return createCXString(NS->getNameAsString());
3069 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003070
Douglas Gregora67e03f2010-09-09 21:42:20 +00003071 case CXCursor_MemberRef: {
3072 FieldDecl *Field = getCursorMemberRef(C).first;
3073 assert(Field && "Missing member decl");
3074
3075 return createCXString(Field->getNameAsString());
3076 }
3077
Douglas Gregor36897b02010-09-10 00:22:18 +00003078 case CXCursor_LabelRef: {
3079 LabelStmt *Label = getCursorLabelRef(C).first;
3080 assert(Label && "Missing label");
3081
Chris Lattnerad8dcf42011-02-17 07:39:24 +00003082 return createCXString(Label->getName());
Douglas Gregor36897b02010-09-10 00:22:18 +00003083 }
3084
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003085 case CXCursor_OverloadedDeclRef: {
3086 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
3087 if (Decl *D = Storage.dyn_cast<Decl *>()) {
3088 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
3089 return createCXString(ND->getNameAsString());
3090 return createCXString("");
3091 }
3092 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
3093 return createCXString(E->getName().getAsString());
3094 OverloadedTemplateStorage *Ovl
3095 = Storage.get<OverloadedTemplateStorage*>();
3096 if (Ovl->size() == 0)
3097 return createCXString("");
3098 return createCXString((*Ovl->begin())->getNameAsString());
3099 }
3100
Daniel Dunbaracca7252009-11-30 20:42:49 +00003101 default:
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003102 return createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +00003103 }
3104 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003105
3106 if (clang_isExpression(C.kind)) {
3107 Decl *D = getDeclFromExpr(getCursorExpr(C));
3108 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +00003109 return getDeclSpelling(D);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003110 return createCXString("");
Douglas Gregor97b98722010-01-19 23:20:36 +00003111 }
3112
Douglas Gregor36897b02010-09-10 00:22:18 +00003113 if (clang_isStatement(C.kind)) {
3114 Stmt *S = getCursorStmt(C);
3115 if (LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
Chris Lattnerad8dcf42011-02-17 07:39:24 +00003116 return createCXString(Label->getName());
Douglas Gregor36897b02010-09-10 00:22:18 +00003117
3118 return createCXString("");
3119 }
3120
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003121 if (C.kind == CXCursor_MacroInstantiation)
3122 return createCXString(getCursorMacroInstantiation(C)->getName()
3123 ->getNameStart());
3124
Douglas Gregor572feb22010-03-18 18:04:21 +00003125 if (C.kind == CXCursor_MacroDefinition)
3126 return createCXString(getCursorMacroDefinition(C)->getName()
3127 ->getNameStart());
3128
Douglas Gregorecdcb882010-10-20 22:00:55 +00003129 if (C.kind == CXCursor_InclusionDirective)
3130 return createCXString(getCursorInclusionDirective(C)->getFileName());
3131
Douglas Gregor60cbfac2010-01-25 16:56:17 +00003132 if (clang_isDeclaration(C.kind))
3133 return getDeclSpelling(getCursorDecl(C));
Ted Kremeneke68fff62010-02-17 00:41:32 +00003134
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003135 return createCXString("");
Steve Narofff334b4e2009-09-02 18:26:48 +00003136}
3137
Douglas Gregor358559d2010-10-02 22:49:11 +00003138CXString clang_getCursorDisplayName(CXCursor C) {
3139 if (!clang_isDeclaration(C.kind))
3140 return clang_getCursorSpelling(C);
3141
3142 Decl *D = getCursorDecl(C);
3143 if (!D)
3144 return createCXString("");
3145
3146 PrintingPolicy &Policy = getCursorContext(C).PrintingPolicy;
3147 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
3148 D = FunTmpl->getTemplatedDecl();
3149
3150 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
3151 llvm::SmallString<64> Str;
3152 llvm::raw_svector_ostream OS(Str);
3153 OS << Function->getNameAsString();
3154 if (Function->getPrimaryTemplate())
3155 OS << "<>";
3156 OS << "(";
3157 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
3158 if (I)
3159 OS << ", ";
3160 OS << Function->getParamDecl(I)->getType().getAsString(Policy);
3161 }
3162
3163 if (Function->isVariadic()) {
3164 if (Function->getNumParams())
3165 OS << ", ";
3166 OS << "...";
3167 }
3168 OS << ")";
3169 return createCXString(OS.str());
3170 }
3171
3172 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
3173 llvm::SmallString<64> Str;
3174 llvm::raw_svector_ostream OS(Str);
3175 OS << ClassTemplate->getNameAsString();
3176 OS << "<";
3177 TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
3178 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
3179 if (I)
3180 OS << ", ";
3181
3182 NamedDecl *Param = Params->getParam(I);
3183 if (Param->getIdentifier()) {
3184 OS << Param->getIdentifier()->getName();
3185 continue;
3186 }
3187
3188 // There is no parameter name, which makes this tricky. Try to come up
3189 // with something useful that isn't too long.
3190 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
3191 OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
3192 else if (NonTypeTemplateParmDecl *NTTP
3193 = dyn_cast<NonTypeTemplateParmDecl>(Param))
3194 OS << NTTP->getType().getAsString(Policy);
3195 else
3196 OS << "template<...> class";
3197 }
3198
3199 OS << ">";
3200 return createCXString(OS.str());
3201 }
3202
3203 if (ClassTemplateSpecializationDecl *ClassSpec
3204 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
3205 // If the type was explicitly written, use that.
3206 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
3207 return createCXString(TSInfo->getType().getAsString(Policy));
3208
3209 llvm::SmallString<64> Str;
3210 llvm::raw_svector_ostream OS(Str);
3211 OS << ClassSpec->getNameAsString();
3212 OS << TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor910f8002010-11-07 23:05:16 +00003213 ClassSpec->getTemplateArgs().data(),
3214 ClassSpec->getTemplateArgs().size(),
Douglas Gregor358559d2010-10-02 22:49:11 +00003215 Policy);
3216 return createCXString(OS.str());
3217 }
3218
3219 return clang_getCursorSpelling(C);
3220}
3221
Ted Kremeneke68fff62010-02-17 00:41:32 +00003222CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00003223 switch (Kind) {
Ted Kremeneke68fff62010-02-17 00:41:32 +00003224 case CXCursor_FunctionDecl:
3225 return createCXString("FunctionDecl");
3226 case CXCursor_TypedefDecl:
3227 return createCXString("TypedefDecl");
3228 case CXCursor_EnumDecl:
3229 return createCXString("EnumDecl");
3230 case CXCursor_EnumConstantDecl:
3231 return createCXString("EnumConstantDecl");
3232 case CXCursor_StructDecl:
3233 return createCXString("StructDecl");
3234 case CXCursor_UnionDecl:
3235 return createCXString("UnionDecl");
3236 case CXCursor_ClassDecl:
3237 return createCXString("ClassDecl");
3238 case CXCursor_FieldDecl:
3239 return createCXString("FieldDecl");
3240 case CXCursor_VarDecl:
3241 return createCXString("VarDecl");
3242 case CXCursor_ParmDecl:
3243 return createCXString("ParmDecl");
3244 case CXCursor_ObjCInterfaceDecl:
3245 return createCXString("ObjCInterfaceDecl");
3246 case CXCursor_ObjCCategoryDecl:
3247 return createCXString("ObjCCategoryDecl");
3248 case CXCursor_ObjCProtocolDecl:
3249 return createCXString("ObjCProtocolDecl");
3250 case CXCursor_ObjCPropertyDecl:
3251 return createCXString("ObjCPropertyDecl");
3252 case CXCursor_ObjCIvarDecl:
3253 return createCXString("ObjCIvarDecl");
3254 case CXCursor_ObjCInstanceMethodDecl:
3255 return createCXString("ObjCInstanceMethodDecl");
3256 case CXCursor_ObjCClassMethodDecl:
3257 return createCXString("ObjCClassMethodDecl");
3258 case CXCursor_ObjCImplementationDecl:
3259 return createCXString("ObjCImplementationDecl");
3260 case CXCursor_ObjCCategoryImplDecl:
3261 return createCXString("ObjCCategoryImplDecl");
Ted Kremenek8bd5a692010-04-13 23:39:06 +00003262 case CXCursor_CXXMethod:
3263 return createCXString("CXXMethod");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003264 case CXCursor_UnexposedDecl:
3265 return createCXString("UnexposedDecl");
3266 case CXCursor_ObjCSuperClassRef:
3267 return createCXString("ObjCSuperClassRef");
3268 case CXCursor_ObjCProtocolRef:
3269 return createCXString("ObjCProtocolRef");
3270 case CXCursor_ObjCClassRef:
3271 return createCXString("ObjCClassRef");
3272 case CXCursor_TypeRef:
3273 return createCXString("TypeRef");
Douglas Gregor0b36e612010-08-31 20:37:03 +00003274 case CXCursor_TemplateRef:
3275 return createCXString("TemplateRef");
Douglas Gregor69319002010-08-31 23:48:11 +00003276 case CXCursor_NamespaceRef:
3277 return createCXString("NamespaceRef");
Douglas Gregora67e03f2010-09-09 21:42:20 +00003278 case CXCursor_MemberRef:
3279 return createCXString("MemberRef");
Douglas Gregor36897b02010-09-10 00:22:18 +00003280 case CXCursor_LabelRef:
3281 return createCXString("LabelRef");
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003282 case CXCursor_OverloadedDeclRef:
3283 return createCXString("OverloadedDeclRef");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003284 case CXCursor_UnexposedExpr:
3285 return createCXString("UnexposedExpr");
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00003286 case CXCursor_BlockExpr:
3287 return createCXString("BlockExpr");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003288 case CXCursor_DeclRefExpr:
3289 return createCXString("DeclRefExpr");
3290 case CXCursor_MemberRefExpr:
3291 return createCXString("MemberRefExpr");
3292 case CXCursor_CallExpr:
3293 return createCXString("CallExpr");
3294 case CXCursor_ObjCMessageExpr:
3295 return createCXString("ObjCMessageExpr");
3296 case CXCursor_UnexposedStmt:
3297 return createCXString("UnexposedStmt");
Douglas Gregor36897b02010-09-10 00:22:18 +00003298 case CXCursor_LabelStmt:
3299 return createCXString("LabelStmt");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003300 case CXCursor_InvalidFile:
3301 return createCXString("InvalidFile");
Ted Kremenek292db642010-03-19 20:39:05 +00003302 case CXCursor_InvalidCode:
3303 return createCXString("InvalidCode");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003304 case CXCursor_NoDeclFound:
3305 return createCXString("NoDeclFound");
3306 case CXCursor_NotImplemented:
3307 return createCXString("NotImplemented");
3308 case CXCursor_TranslationUnit:
3309 return createCXString("TranslationUnit");
Ted Kremeneke77f4432010-02-18 03:09:07 +00003310 case CXCursor_UnexposedAttr:
3311 return createCXString("UnexposedAttr");
3312 case CXCursor_IBActionAttr:
3313 return createCXString("attribute(ibaction)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003314 case CXCursor_IBOutletAttr:
3315 return createCXString("attribute(iboutlet)");
Ted Kremenek857e9182010-05-19 17:38:06 +00003316 case CXCursor_IBOutletCollectionAttr:
3317 return createCXString("attribute(iboutletcollection)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003318 case CXCursor_PreprocessingDirective:
3319 return createCXString("preprocessing directive");
Douglas Gregor572feb22010-03-18 18:04:21 +00003320 case CXCursor_MacroDefinition:
3321 return createCXString("macro definition");
Douglas Gregor48072312010-03-18 15:23:44 +00003322 case CXCursor_MacroInstantiation:
3323 return createCXString("macro instantiation");
Douglas Gregorecdcb882010-10-20 22:00:55 +00003324 case CXCursor_InclusionDirective:
3325 return createCXString("inclusion directive");
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00003326 case CXCursor_Namespace:
3327 return createCXString("Namespace");
Ted Kremeneka0536d82010-05-07 01:04:29 +00003328 case CXCursor_LinkageSpec:
3329 return createCXString("LinkageSpec");
Ted Kremenek3064ef92010-08-27 21:34:58 +00003330 case CXCursor_CXXBaseSpecifier:
3331 return createCXString("C++ base class specifier");
Douglas Gregor01829d32010-08-31 14:41:23 +00003332 case CXCursor_Constructor:
3333 return createCXString("CXXConstructor");
3334 case CXCursor_Destructor:
3335 return createCXString("CXXDestructor");
3336 case CXCursor_ConversionFunction:
3337 return createCXString("CXXConversion");
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00003338 case CXCursor_TemplateTypeParameter:
3339 return createCXString("TemplateTypeParameter");
3340 case CXCursor_NonTypeTemplateParameter:
3341 return createCXString("NonTypeTemplateParameter");
3342 case CXCursor_TemplateTemplateParameter:
3343 return createCXString("TemplateTemplateParameter");
3344 case CXCursor_FunctionTemplate:
3345 return createCXString("FunctionTemplate");
Douglas Gregor39d6f072010-08-31 19:02:00 +00003346 case CXCursor_ClassTemplate:
3347 return createCXString("ClassTemplate");
Douglas Gregor74dbe642010-08-31 19:31:58 +00003348 case CXCursor_ClassTemplatePartialSpecialization:
3349 return createCXString("ClassTemplatePartialSpecialization");
Douglas Gregor69319002010-08-31 23:48:11 +00003350 case CXCursor_NamespaceAlias:
3351 return createCXString("NamespaceAlias");
Douglas Gregor0a35bce2010-09-01 03:07:18 +00003352 case CXCursor_UsingDirective:
3353 return createCXString("UsingDirective");
Douglas Gregor7e242562010-09-01 19:52:22 +00003354 case CXCursor_UsingDeclaration:
3355 return createCXString("UsingDeclaration");
Richard Smith162e1c12011-04-15 14:24:37 +00003356 case CXCursor_TypeAliasDecl:
3357 return createCXString("TypeAliasDecl");
Steve Naroff89922f82009-08-31 00:59:03 +00003358 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00003359
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00003360 llvm_unreachable("Unhandled CXCursorKind");
Ted Kremeneka60ed472010-11-16 08:15:36 +00003361 return createCXString((const char*) 0);
Steve Naroff600866c2009-08-27 19:51:58 +00003362}
Steve Naroff89922f82009-08-31 00:59:03 +00003363
Ted Kremeneke68fff62010-02-17 00:41:32 +00003364enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
3365 CXCursor parent,
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003366 CXClientData client_data) {
3367 CXCursor *BestCursor = static_cast<CXCursor *>(client_data);
Douglas Gregor93798e22010-11-05 21:11:19 +00003368
3369 // If our current best cursor is the construction of a temporary object,
3370 // don't replace that cursor with a type reference, because we want
3371 // clang_getCursor() to point at the constructor.
3372 if (clang_isExpression(BestCursor->kind) &&
3373 isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
3374 cursor.kind == CXCursor_TypeRef)
3375 return CXChildVisit_Recurse;
3376
Douglas Gregor85fe1562010-12-10 07:23:11 +00003377 // Don't override a preprocessing cursor with another preprocessing
3378 // cursor; we want the outermost preprocessing cursor.
3379 if (clang_isPreprocessing(cursor.kind) &&
3380 clang_isPreprocessing(BestCursor->kind))
3381 return CXChildVisit_Recurse;
3382
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003383 *BestCursor = cursor;
3384 return CXChildVisit_Recurse;
3385}
Ted Kremeneke68fff62010-02-17 00:41:32 +00003386
Douglas Gregorb9790342010-01-22 21:44:22 +00003387CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
3388 if (!TU)
Ted Kremenekf4629892010-01-14 01:51:23 +00003389 return clang_getNullCursor();
Ted Kremeneke68fff62010-02-17 00:41:32 +00003390
Ted Kremeneka60ed472010-11-16 08:15:36 +00003391 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorbdf60622010-03-05 21:16:25 +00003392 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3393
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003394 // Translate the given source location to make it point at the beginning of
3395 // the token under the cursor.
Ted Kremeneka297de22010-01-25 22:34:44 +00003396 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
Ted Kremeneka629ea42010-07-29 00:52:07 +00003397
3398 // Guard against an invalid SourceLocation, or we may assert in one
3399 // of the following calls.
3400 if (SLoc.isInvalid())
3401 return clang_getNullCursor();
3402
Douglas Gregor40749ee2010-11-03 00:35:38 +00003403 bool Logging = getenv("LIBCLANG_LOGGING");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003404 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
3405 CXXUnit->getASTContext().getLangOptions());
3406
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003407 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
3408 if (SLoc.isValid()) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003409 // FIXME: Would be great to have a "hint" cursor, then walk from that
3410 // hint cursor upward until we find a cursor whose source range encloses
3411 // the region of interest, rather than starting from the translation unit.
Ted Kremeneka60ed472010-11-16 08:15:36 +00003412 CXCursor Parent = clang_getTranslationUnitCursor(TU);
3413 CursorVisitor CursorVis(TU, GetCursorVisitor, &Result,
Douglas Gregor04a9eb32011-03-16 23:23:30 +00003414 Decl::MaxPCHLevel, true, SourceLocation(SLoc));
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003415 CursorVis.VisitChildren(Parent);
Steve Naroff77128dd2009-09-15 20:25:34 +00003416 }
Douglas Gregor40749ee2010-11-03 00:35:38 +00003417
3418 if (Logging) {
3419 CXFile SearchFile;
3420 unsigned SearchLine, SearchColumn;
3421 CXFile ResultFile;
3422 unsigned ResultLine, ResultColumn;
Douglas Gregor66537982010-11-17 17:14:07 +00003423 CXString SearchFileName, ResultFileName, KindSpelling, USR;
3424 const char *IsDef = clang_isCursorDefinition(Result)? " (Definition)" : "";
Douglas Gregor40749ee2010-11-03 00:35:38 +00003425 CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
3426
3427 clang_getInstantiationLocation(Loc, &SearchFile, &SearchLine, &SearchColumn,
3428 0);
3429 clang_getInstantiationLocation(ResultLoc, &ResultFile, &ResultLine,
3430 &ResultColumn, 0);
3431 SearchFileName = clang_getFileName(SearchFile);
3432 ResultFileName = clang_getFileName(ResultFile);
3433 KindSpelling = clang_getCursorKindSpelling(Result.kind);
Douglas Gregor66537982010-11-17 17:14:07 +00003434 USR = clang_getCursorUSR(Result);
3435 fprintf(stderr, "clang_getCursor(%s:%d:%d) = %s(%s:%d:%d):%s%s\n",
Douglas Gregor40749ee2010-11-03 00:35:38 +00003436 clang_getCString(SearchFileName), SearchLine, SearchColumn,
3437 clang_getCString(KindSpelling),
Douglas Gregor66537982010-11-17 17:14:07 +00003438 clang_getCString(ResultFileName), ResultLine, ResultColumn,
3439 clang_getCString(USR), IsDef);
Douglas Gregor40749ee2010-11-03 00:35:38 +00003440 clang_disposeString(SearchFileName);
3441 clang_disposeString(ResultFileName);
3442 clang_disposeString(KindSpelling);
Douglas Gregor66537982010-11-17 17:14:07 +00003443 clang_disposeString(USR);
Douglas Gregor0aefbd82010-12-10 01:45:00 +00003444
3445 CXCursor Definition = clang_getCursorDefinition(Result);
3446 if (!clang_equalCursors(Definition, clang_getNullCursor())) {
3447 CXSourceLocation DefinitionLoc = clang_getCursorLocation(Definition);
3448 CXString DefinitionKindSpelling
3449 = clang_getCursorKindSpelling(Definition.kind);
3450 CXFile DefinitionFile;
3451 unsigned DefinitionLine, DefinitionColumn;
3452 clang_getInstantiationLocation(DefinitionLoc, &DefinitionFile,
3453 &DefinitionLine, &DefinitionColumn, 0);
3454 CXString DefinitionFileName = clang_getFileName(DefinitionFile);
3455 fprintf(stderr, " -> %s(%s:%d:%d)\n",
3456 clang_getCString(DefinitionKindSpelling),
3457 clang_getCString(DefinitionFileName),
3458 DefinitionLine, DefinitionColumn);
3459 clang_disposeString(DefinitionFileName);
3460 clang_disposeString(DefinitionKindSpelling);
3461 }
Douglas Gregor40749ee2010-11-03 00:35:38 +00003462 }
3463
Ted Kremeneke68fff62010-02-17 00:41:32 +00003464 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00003465}
3466
Ted Kremenek73885552009-11-17 19:28:59 +00003467CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00003468 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00003469}
3470
3471unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00003472 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00003473}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00003474
Douglas Gregor9ce55842010-11-20 00:09:34 +00003475unsigned clang_hashCursor(CXCursor C) {
3476 unsigned Index = 0;
3477 if (clang_isExpression(C.kind) || clang_isStatement(C.kind))
3478 Index = 1;
3479
3480 return llvm::DenseMapInfo<std::pair<unsigned, void*> >::getHashValue(
3481 std::make_pair(C.kind, C.data[Index]));
3482}
3483
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003484unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00003485 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
3486}
3487
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003488unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +00003489 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
3490}
Steve Naroff2d4d6292009-08-31 14:26:51 +00003491
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003492unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00003493 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
3494}
3495
Douglas Gregor97b98722010-01-19 23:20:36 +00003496unsigned clang_isExpression(enum CXCursorKind K) {
3497 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
3498}
3499
3500unsigned clang_isStatement(enum CXCursorKind K) {
3501 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
3502}
3503
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00003504unsigned clang_isTranslationUnit(enum CXCursorKind K) {
3505 return K == CXCursor_TranslationUnit;
3506}
3507
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003508unsigned clang_isPreprocessing(enum CXCursorKind K) {
3509 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
3510}
3511
Ted Kremenekad6eff62010-03-08 21:17:29 +00003512unsigned clang_isUnexposed(enum CXCursorKind K) {
3513 switch (K) {
3514 case CXCursor_UnexposedDecl:
3515 case CXCursor_UnexposedExpr:
3516 case CXCursor_UnexposedStmt:
3517 case CXCursor_UnexposedAttr:
3518 return true;
3519 default:
3520 return false;
3521 }
3522}
3523
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003524CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00003525 return C.kind;
3526}
3527
Douglas Gregor98258af2010-01-18 22:46:11 +00003528CXSourceLocation clang_getCursorLocation(CXCursor C) {
3529 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003530 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003531 case CXCursor_ObjCSuperClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003532 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3533 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003534 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003535 }
3536
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003537 case CXCursor_ObjCProtocolRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003538 std::pair<ObjCProtocolDecl *, SourceLocation> P
3539 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003540 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003541 }
3542
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003543 case CXCursor_ObjCClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003544 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3545 = getCursorObjCClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003546 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003547 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003548
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003549 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003550 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003551 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003552 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00003553
3554 case CXCursor_TemplateRef: {
3555 std::pair<TemplateDecl *, SourceLocation> P = getCursorTemplateRef(C);
3556 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3557 }
3558
Douglas Gregor69319002010-08-31 23:48:11 +00003559 case CXCursor_NamespaceRef: {
3560 std::pair<NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
3561 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3562 }
3563
Douglas Gregora67e03f2010-09-09 21:42:20 +00003564 case CXCursor_MemberRef: {
3565 std::pair<FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
3566 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3567 }
3568
Ted Kremenek3064ef92010-08-27 21:34:58 +00003569 case CXCursor_CXXBaseSpecifier: {
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003570 CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
3571 if (!BaseSpec)
3572 return clang_getNullLocation();
3573
3574 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
3575 return cxloc::translateSourceLocation(getCursorContext(C),
3576 TSInfo->getTypeLoc().getBeginLoc());
3577
3578 return cxloc::translateSourceLocation(getCursorContext(C),
3579 BaseSpec->getSourceRange().getBegin());
Ted Kremenek3064ef92010-08-27 21:34:58 +00003580 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003581
Douglas Gregor36897b02010-09-10 00:22:18 +00003582 case CXCursor_LabelRef: {
3583 std::pair<LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
3584 return cxloc::translateSourceLocation(getCursorContext(C), P.second);
3585 }
3586
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003587 case CXCursor_OverloadedDeclRef:
3588 return cxloc::translateSourceLocation(getCursorContext(C),
3589 getCursorOverloadedDeclRef(C).second);
3590
Douglas Gregorf46034a2010-01-18 23:41:10 +00003591 default:
3592 // FIXME: Need a way to enumerate all non-reference cases.
3593 llvm_unreachable("Missed a reference kind");
3594 }
Douglas Gregor98258af2010-01-18 22:46:11 +00003595 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003596
3597 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003598 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00003599 getLocationFromExpr(getCursorExpr(C)));
3600
Douglas Gregor36897b02010-09-10 00:22:18 +00003601 if (clang_isStatement(C.kind))
3602 return cxloc::translateSourceLocation(getCursorContext(C),
3603 getCursorStmt(C)->getLocStart());
3604
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003605 if (C.kind == CXCursor_PreprocessingDirective) {
3606 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
3607 return cxloc::translateSourceLocation(getCursorContext(C), L);
3608 }
Douglas Gregor48072312010-03-18 15:23:44 +00003609
3610 if (C.kind == CXCursor_MacroInstantiation) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003611 SourceLocation L
3612 = cxcursor::getCursorMacroInstantiation(C)->getSourceRange().getBegin();
Douglas Gregor48072312010-03-18 15:23:44 +00003613 return cxloc::translateSourceLocation(getCursorContext(C), L);
3614 }
Douglas Gregor572feb22010-03-18 18:04:21 +00003615
3616 if (C.kind == CXCursor_MacroDefinition) {
3617 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
3618 return cxloc::translateSourceLocation(getCursorContext(C), L);
3619 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003620
3621 if (C.kind == CXCursor_InclusionDirective) {
3622 SourceLocation L
3623 = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
3624 return cxloc::translateSourceLocation(getCursorContext(C), L);
3625 }
3626
Ted Kremenek9a700d22010-05-12 06:16:13 +00003627 if (C.kind < CXCursor_FirstDecl || C.kind > CXCursor_LastDecl)
Douglas Gregor5352ac02010-01-28 00:27:43 +00003628 return clang_getNullLocation();
Douglas Gregor98258af2010-01-18 22:46:11 +00003629
Douglas Gregorf46034a2010-01-18 23:41:10 +00003630 Decl *D = getCursorDecl(C);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003631 SourceLocation Loc = D->getLocation();
3632 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
3633 Loc = Class->getClassLoc();
Ted Kremenek007a7c92010-11-01 23:26:51 +00003634 // FIXME: Multiple variables declared in a single declaration
3635 // currently lack the information needed to correctly determine their
3636 // ranges when accounting for the type-specifier. We use context
3637 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3638 // and if so, whether it is the first decl.
3639 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3640 if (!cxcursor::isFirstInDeclGroup(C))
3641 Loc = VD->getLocation();
3642 }
3643
Douglas Gregor2ca54fe2010-03-22 15:53:50 +00003644 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00003645}
Douglas Gregora7bde202010-01-19 00:34:46 +00003646
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003647} // end extern "C"
3648
3649static SourceRange getRawCursorExtent(CXCursor C) {
Douglas Gregora7bde202010-01-19 00:34:46 +00003650 if (clang_isReference(C.kind)) {
3651 switch (C.kind) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003652 case CXCursor_ObjCSuperClassRef:
3653 return getCursorObjCSuperClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003654
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003655 case CXCursor_ObjCProtocolRef:
3656 return getCursorObjCProtocolRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003657
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003658 case CXCursor_ObjCClassRef:
3659 return getCursorObjCClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003660
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003661 case CXCursor_TypeRef:
3662 return getCursorTypeRef(C).second;
Douglas Gregor0b36e612010-08-31 20:37:03 +00003663
3664 case CXCursor_TemplateRef:
3665 return getCursorTemplateRef(C).second;
3666
Douglas Gregor69319002010-08-31 23:48:11 +00003667 case CXCursor_NamespaceRef:
3668 return getCursorNamespaceRef(C).second;
Douglas Gregora67e03f2010-09-09 21:42:20 +00003669
3670 case CXCursor_MemberRef:
3671 return getCursorMemberRef(C).second;
3672
Ted Kremenek3064ef92010-08-27 21:34:58 +00003673 case CXCursor_CXXBaseSpecifier:
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003674 return getCursorCXXBaseSpecifier(C)->getSourceRange();
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003675
Douglas Gregor36897b02010-09-10 00:22:18 +00003676 case CXCursor_LabelRef:
3677 return getCursorLabelRef(C).second;
3678
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003679 case CXCursor_OverloadedDeclRef:
3680 return getCursorOverloadedDeclRef(C).second;
3681
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003682 default:
3683 // FIXME: Need a way to enumerate all non-reference cases.
3684 llvm_unreachable("Missed a reference kind");
Douglas Gregora7bde202010-01-19 00:34:46 +00003685 }
3686 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003687
3688 if (clang_isExpression(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003689 return getCursorExpr(C)->getSourceRange();
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003690
3691 if (clang_isStatement(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003692 return getCursorStmt(C)->getSourceRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003693
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003694 if (C.kind == CXCursor_PreprocessingDirective)
3695 return cxcursor::getCursorPreprocessingDirective(C);
Douglas Gregor48072312010-03-18 15:23:44 +00003696
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003697 if (C.kind == CXCursor_MacroInstantiation)
3698 return cxcursor::getCursorMacroInstantiation(C)->getSourceRange();
Douglas Gregor572feb22010-03-18 18:04:21 +00003699
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003700 if (C.kind == CXCursor_MacroDefinition)
3701 return cxcursor::getCursorMacroDefinition(C)->getSourceRange();
Douglas Gregorecdcb882010-10-20 22:00:55 +00003702
3703 if (C.kind == CXCursor_InclusionDirective)
3704 return cxcursor::getCursorInclusionDirective(C)->getSourceRange();
3705
Ted Kremenek007a7c92010-11-01 23:26:51 +00003706 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
3707 Decl *D = cxcursor::getCursorDecl(C);
3708 SourceRange R = D->getSourceRange();
3709 // FIXME: Multiple variables declared in a single declaration
3710 // currently lack the information needed to correctly determine their
3711 // ranges when accounting for the type-specifier. We use context
3712 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3713 // and if so, whether it is the first decl.
3714 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3715 if (!cxcursor::isFirstInDeclGroup(C))
3716 R.setBegin(VD->getLocation());
3717 }
3718 return R;
3719 }
Douglas Gregor66537982010-11-17 17:14:07 +00003720 return SourceRange();
3721}
3722
3723/// \brief Retrieves the "raw" cursor extent, which is then extended to include
3724/// the decl-specifier-seq for declarations.
3725static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr) {
3726 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
3727 Decl *D = cxcursor::getCursorDecl(C);
3728 SourceRange R = D->getSourceRange();
Douglas Gregor66537982010-11-17 17:14:07 +00003729
Douglas Gregor2494dd02011-03-01 01:34:45 +00003730 // Adjust the start of the location for declarations preceded by
3731 // declaration specifiers.
3732 SourceLocation StartLoc;
3733 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
3734 if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
3735 StartLoc = TI->getTypeLoc().getSourceRange().getBegin();
3736 } else if (TypedefDecl *Typedef = dyn_cast<TypedefDecl>(D)) {
3737 if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
3738 StartLoc = TI->getTypeLoc().getSourceRange().getBegin();
3739 }
3740
3741 if (StartLoc.isValid() && R.getBegin().isValid() &&
3742 SrcMgr.isBeforeInTranslationUnit(StartLoc, R.getBegin()))
3743 R.setBegin(StartLoc);
3744
3745 // FIXME: Multiple variables declared in a single declaration
3746 // currently lack the information needed to correctly determine their
3747 // ranges when accounting for the type-specifier. We use context
3748 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3749 // and if so, whether it is the first decl.
3750 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3751 if (!cxcursor::isFirstInDeclGroup(C))
3752 R.setBegin(VD->getLocation());
Douglas Gregor66537982010-11-17 17:14:07 +00003753 }
3754
3755 return R;
3756 }
3757
3758 return getRawCursorExtent(C);
3759}
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003760
3761extern "C" {
3762
3763CXSourceRange clang_getCursorExtent(CXCursor C) {
3764 SourceRange R = getRawCursorExtent(C);
3765 if (R.isInvalid())
Douglas Gregor5352ac02010-01-28 00:27:43 +00003766 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003767
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003768 return cxloc::translateSourceRange(getCursorContext(C), R);
Douglas Gregora7bde202010-01-19 00:34:46 +00003769}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003770
3771CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003772 if (clang_isInvalid(C.kind))
3773 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003774
Ted Kremeneka60ed472010-11-16 08:15:36 +00003775 CXTranslationUnit tu = getCursorTU(C);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003776 if (clang_isDeclaration(C.kind)) {
3777 Decl *D = getCursorDecl(C);
3778 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003779 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003780 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003781 return MakeCursorOverloadedDeclRef(Classes, D->getLocation(), tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003782 if (ObjCForwardProtocolDecl *Protocols
3783 = dyn_cast<ObjCForwardProtocolDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003784 return MakeCursorOverloadedDeclRef(Protocols, D->getLocation(), tu);
Douglas Gregore3c60a72010-11-17 00:13:31 +00003785 if (ObjCPropertyImplDecl *PropImpl =llvm::dyn_cast<ObjCPropertyImplDecl>(D))
3786 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
3787 return MakeCXCursor(Property, tu);
3788
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003789 return C;
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003790 }
3791
Douglas Gregor97b98722010-01-19 23:20:36 +00003792 if (clang_isExpression(C.kind)) {
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003793 Expr *E = getCursorExpr(C);
3794 Decl *D = getDeclFromExpr(E);
Douglas Gregor97b98722010-01-19 23:20:36 +00003795 if (D)
Ted Kremeneka60ed472010-11-16 08:15:36 +00003796 return MakeCXCursor(D, tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003797
3798 if (OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003799 return MakeCursorOverloadedDeclRef(Ovl, tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003800
Douglas Gregor97b98722010-01-19 23:20:36 +00003801 return clang_getNullCursor();
3802 }
3803
Douglas Gregor36897b02010-09-10 00:22:18 +00003804 if (clang_isStatement(C.kind)) {
3805 Stmt *S = getCursorStmt(C);
3806 if (GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
Ted Kremenek37c2e962011-03-15 23:47:49 +00003807 if (LabelDecl *label = Goto->getLabel())
3808 if (LabelStmt *labelS = label->getStmt())
3809 return MakeCXCursor(labelS, getCursorDecl(C), tu);
Douglas Gregor36897b02010-09-10 00:22:18 +00003810
3811 return clang_getNullCursor();
3812 }
3813
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003814 if (C.kind == CXCursor_MacroInstantiation) {
3815 if (MacroDefinition *Def = getCursorMacroInstantiation(C)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003816 return MakeMacroDefinitionCursor(Def, tu);
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003817 }
3818
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003819 if (!clang_isReference(C.kind))
3820 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003821
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003822 switch (C.kind) {
3823 case CXCursor_ObjCSuperClassRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003824 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003825
3826 case CXCursor_ObjCProtocolRef: {
Ted Kremeneka60ed472010-11-16 08:15:36 +00003827 return MakeCXCursor(getCursorObjCProtocolRef(C).first, tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003828
3829 case CXCursor_ObjCClassRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003830 return MakeCXCursor(getCursorObjCClassRef(C).first, tu );
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003831
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003832 case CXCursor_TypeRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003833 return MakeCXCursor(getCursorTypeRef(C).first, tu );
Douglas Gregor0b36e612010-08-31 20:37:03 +00003834
3835 case CXCursor_TemplateRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003836 return MakeCXCursor(getCursorTemplateRef(C).first, tu );
Douglas Gregor0b36e612010-08-31 20:37:03 +00003837
Douglas Gregor69319002010-08-31 23:48:11 +00003838 case CXCursor_NamespaceRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003839 return MakeCXCursor(getCursorNamespaceRef(C).first, tu );
Douglas Gregor69319002010-08-31 23:48:11 +00003840
Douglas Gregora67e03f2010-09-09 21:42:20 +00003841 case CXCursor_MemberRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003842 return MakeCXCursor(getCursorMemberRef(C).first, tu );
Douglas Gregora67e03f2010-09-09 21:42:20 +00003843
Ted Kremenek3064ef92010-08-27 21:34:58 +00003844 case CXCursor_CXXBaseSpecifier: {
3845 CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
3846 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003847 tu ));
Ted Kremenek3064ef92010-08-27 21:34:58 +00003848 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003849
Douglas Gregor36897b02010-09-10 00:22:18 +00003850 case CXCursor_LabelRef:
3851 // FIXME: We end up faking the "parent" declaration here because we
3852 // don't want to make CXCursor larger.
3853 return MakeCXCursor(getCursorLabelRef(C).first,
Ted Kremeneka60ed472010-11-16 08:15:36 +00003854 static_cast<ASTUnit*>(tu->TUData)->getASTContext()
3855 .getTranslationUnitDecl(),
3856 tu);
Douglas Gregor36897b02010-09-10 00:22:18 +00003857
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003858 case CXCursor_OverloadedDeclRef:
3859 return C;
3860
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003861 default:
3862 // We would prefer to enumerate all non-reference cursor kinds here.
3863 llvm_unreachable("Unhandled reference cursor kind");
3864 break;
3865 }
3866 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003867
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003868 return clang_getNullCursor();
3869}
3870
Douglas Gregorb6998662010-01-19 19:34:47 +00003871CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003872 if (clang_isInvalid(C.kind))
3873 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003874
Ted Kremeneka60ed472010-11-16 08:15:36 +00003875 CXTranslationUnit TU = getCursorTU(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003876
Douglas Gregorb6998662010-01-19 19:34:47 +00003877 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00003878 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00003879 C = clang_getCursorReferenced(C);
3880 WasReference = true;
3881 }
3882
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003883 if (C.kind == CXCursor_MacroInstantiation)
3884 return clang_getCursorReferenced(C);
3885
Douglas Gregorb6998662010-01-19 19:34:47 +00003886 if (!clang_isDeclaration(C.kind))
3887 return clang_getNullCursor();
3888
3889 Decl *D = getCursorDecl(C);
3890 if (!D)
3891 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003892
Douglas Gregorb6998662010-01-19 19:34:47 +00003893 switch (D->getKind()) {
3894 // Declaration kinds that don't really separate the notions of
3895 // declaration and definition.
3896 case Decl::Namespace:
3897 case Decl::Typedef:
Richard Smith162e1c12011-04-15 14:24:37 +00003898 case Decl::TypeAlias:
Douglas Gregorb6998662010-01-19 19:34:47 +00003899 case Decl::TemplateTypeParm:
3900 case Decl::EnumConstant:
3901 case Decl::Field:
Benjamin Kramerd9811462010-11-21 14:11:41 +00003902 case Decl::IndirectField:
Douglas Gregorb6998662010-01-19 19:34:47 +00003903 case Decl::ObjCIvar:
3904 case Decl::ObjCAtDefsField:
3905 case Decl::ImplicitParam:
3906 case Decl::ParmVar:
3907 case Decl::NonTypeTemplateParm:
3908 case Decl::TemplateTemplateParm:
3909 case Decl::ObjCCategoryImpl:
3910 case Decl::ObjCImplementation:
Abramo Bagnara6206d532010-06-05 05:09:32 +00003911 case Decl::AccessSpec:
Douglas Gregorb6998662010-01-19 19:34:47 +00003912 case Decl::LinkageSpec:
3913 case Decl::ObjCPropertyImpl:
3914 case Decl::FileScopeAsm:
3915 case Decl::StaticAssert:
3916 case Decl::Block:
Chris Lattnerad8dcf42011-02-17 07:39:24 +00003917 case Decl::Label: // FIXME: Is this right??
Douglas Gregorb6998662010-01-19 19:34:47 +00003918 return C;
3919
3920 // Declaration kinds that don't make any sense here, but are
3921 // nonetheless harmless.
3922 case Decl::TranslationUnit:
Douglas Gregorb6998662010-01-19 19:34:47 +00003923 break;
3924
3925 // Declaration kinds for which the definition is not resolvable.
3926 case Decl::UnresolvedUsingTypename:
3927 case Decl::UnresolvedUsingValue:
3928 break;
3929
3930 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003931 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003932 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003933
3934 case Decl::NamespaceAlias:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003935 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003936
3937 case Decl::Enum:
3938 case Decl::Record:
3939 case Decl::CXXRecord:
3940 case Decl::ClassTemplateSpecialization:
3941 case Decl::ClassTemplatePartialSpecialization:
Douglas Gregor952b0172010-02-11 01:04:33 +00003942 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003943 return MakeCXCursor(Def, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003944 return clang_getNullCursor();
3945
3946 case Decl::Function:
3947 case Decl::CXXMethod:
3948 case Decl::CXXConstructor:
3949 case Decl::CXXDestructor:
3950 case Decl::CXXConversion: {
3951 const FunctionDecl *Def = 0;
3952 if (cast<FunctionDecl>(D)->getBody(Def))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003953 return MakeCXCursor(const_cast<FunctionDecl *>(Def), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003954 return clang_getNullCursor();
3955 }
3956
3957 case Decl::Var: {
Sebastian Redl31310a22010-02-01 20:16:42 +00003958 // Ask the variable if it has a definition.
3959 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003960 return MakeCXCursor(Def, TU);
Sebastian Redl31310a22010-02-01 20:16:42 +00003961 return clang_getNullCursor();
Douglas Gregorb6998662010-01-19 19:34:47 +00003962 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003963
Douglas Gregorb6998662010-01-19 19:34:47 +00003964 case Decl::FunctionTemplate: {
3965 const FunctionDecl *Def = 0;
3966 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003967 return MakeCXCursor(Def->getDescribedFunctionTemplate(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003968 return clang_getNullCursor();
3969 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003970
Douglas Gregorb6998662010-01-19 19:34:47 +00003971 case Decl::ClassTemplate: {
3972 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
Douglas Gregor952b0172010-02-11 01:04:33 +00003973 ->getDefinition())
Douglas Gregor0b36e612010-08-31 20:37:03 +00003974 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003975 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003976 return clang_getNullCursor();
3977 }
3978
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003979 case Decl::Using:
3980 return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003981 D->getLocation(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003982
3983 case Decl::UsingShadow:
3984 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003985 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003986 TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00003987
3988 case Decl::ObjCMethod: {
3989 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
3990 if (Method->isThisDeclarationADefinition())
3991 return C;
3992
3993 // Dig out the method definition in the associated
3994 // @implementation, if we have it.
3995 // FIXME: The ASTs should make finding the definition easier.
3996 if (ObjCInterfaceDecl *Class
3997 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
3998 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
3999 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
4000 Method->isInstanceMethod()))
4001 if (Def->isThisDeclarationADefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004002 return MakeCXCursor(Def, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004003
4004 return clang_getNullCursor();
4005 }
4006
4007 case Decl::ObjCCategory:
4008 if (ObjCCategoryImplDecl *Impl
4009 = cast<ObjCCategoryDecl>(D)->getImplementation())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004010 return MakeCXCursor(Impl, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004011 return clang_getNullCursor();
4012
4013 case Decl::ObjCProtocol:
4014 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
4015 return C;
4016 return clang_getNullCursor();
4017
4018 case Decl::ObjCInterface:
4019 // There are two notions of a "definition" for an Objective-C
4020 // class: the interface and its implementation. When we resolved a
4021 // reference to an Objective-C class, produce the @interface as
4022 // the definition; when we were provided with the interface,
4023 // produce the @implementation as the definition.
4024 if (WasReference) {
4025 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
4026 return C;
4027 } else if (ObjCImplementationDecl *Impl
4028 = cast<ObjCInterfaceDecl>(D)->getImplementation())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004029 return MakeCXCursor(Impl, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004030 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004031
Douglas Gregorb6998662010-01-19 19:34:47 +00004032 case Decl::ObjCProperty:
4033 // FIXME: We don't really know where to find the
4034 // ObjCPropertyImplDecls that implement this property.
4035 return clang_getNullCursor();
4036
4037 case Decl::ObjCCompatibleAlias:
4038 if (ObjCInterfaceDecl *Class
4039 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
4040 if (!Class->isForwardDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004041 return MakeCXCursor(Class, TU);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004042
Douglas Gregorb6998662010-01-19 19:34:47 +00004043 return clang_getNullCursor();
4044
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004045 case Decl::ObjCForwardProtocol:
4046 return MakeCursorOverloadedDeclRef(cast<ObjCForwardProtocolDecl>(D),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004047 D->getLocation(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004048
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004049 case Decl::ObjCClass:
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00004050 return MakeCursorOverloadedDeclRef(cast<ObjCClassDecl>(D), D->getLocation(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004051 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004052
4053 case Decl::Friend:
4054 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004055 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00004056 return clang_getNullCursor();
4057
4058 case Decl::FriendTemplate:
4059 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004060 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00004061 return clang_getNullCursor();
4062 }
4063
4064 return clang_getNullCursor();
4065}
4066
4067unsigned clang_isCursorDefinition(CXCursor C) {
4068 if (!clang_isDeclaration(C.kind))
4069 return 0;
4070
4071 return clang_getCursorDefinition(C) == C;
4072}
4073
Douglas Gregor1a9d0502010-11-19 23:44:15 +00004074CXCursor clang_getCanonicalCursor(CXCursor C) {
4075 if (!clang_isDeclaration(C.kind))
4076 return C;
4077
4078 if (Decl *D = getCursorDecl(C))
4079 return MakeCXCursor(D->getCanonicalDecl(), getCursorTU(C));
4080
4081 return C;
4082}
4083
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004084unsigned clang_getNumOverloadedDecls(CXCursor C) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00004085 if (C.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004086 return 0;
4087
4088 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
4089 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
4090 return E->getNumDecls();
4091
4092 if (OverloadedTemplateStorage *S
4093 = Storage.dyn_cast<OverloadedTemplateStorage*>())
4094 return S->size();
4095
4096 Decl *D = Storage.get<Decl*>();
4097 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
Argyrios Kyrtzidis826faa22010-11-10 05:40:41 +00004098 return Using->shadow_size();
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004099 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
4100 return Classes->size();
4101 if (ObjCForwardProtocolDecl *Protocols =dyn_cast<ObjCForwardProtocolDecl>(D))
4102 return Protocols->protocol_size();
4103
4104 return 0;
4105}
4106
4107CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00004108 if (cursor.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004109 return clang_getNullCursor();
4110
4111 if (index >= clang_getNumOverloadedDecls(cursor))
4112 return clang_getNullCursor();
4113
Ted Kremeneka60ed472010-11-16 08:15:36 +00004114 CXTranslationUnit TU = getCursorTU(cursor);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004115 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
4116 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004117 return MakeCXCursor(E->decls_begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004118
4119 if (OverloadedTemplateStorage *S
4120 = Storage.dyn_cast<OverloadedTemplateStorage*>())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004121 return MakeCXCursor(S->begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004122
4123 Decl *D = Storage.get<Decl*>();
4124 if (UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
4125 // FIXME: This is, unfortunately, linear time.
4126 UsingDecl::shadow_iterator Pos = Using->shadow_begin();
4127 std::advance(Pos, index);
Ted Kremeneka60ed472010-11-16 08:15:36 +00004128 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004129 }
4130
4131 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004132 return MakeCXCursor(Classes->begin()[index].getInterface(), TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004133
4134 if (ObjCForwardProtocolDecl *Protocols = dyn_cast<ObjCForwardProtocolDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004135 return MakeCXCursor(Protocols->protocol_begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004136
4137 return clang_getNullCursor();
4138}
4139
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00004140void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00004141 const char **startBuf,
4142 const char **endBuf,
4143 unsigned *startLine,
4144 unsigned *startColumn,
4145 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00004146 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00004147 assert(getCursorDecl(C) && "CXCursor has null decl");
4148 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00004149 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
4150 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004151
Steve Naroff4ade6d62009-09-23 17:52:52 +00004152 SourceManager &SM = FD->getASTContext().getSourceManager();
4153 *startBuf = SM.getCharacterData(Body->getLBracLoc());
4154 *endBuf = SM.getCharacterData(Body->getRBracLoc());
4155 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
4156 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
4157 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
4158 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
4159}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004160
Douglas Gregor0a812cf2010-02-18 23:07:20 +00004161void clang_enableStackTraces(void) {
4162 llvm::sys::PrintStackTraceOnErrorSignal();
4163}
4164
Daniel Dunbar995aaf92010-11-04 01:26:29 +00004165void clang_executeOnThread(void (*fn)(void*), void *user_data,
4166 unsigned stack_size) {
4167 llvm::llvm_execute_on_thread(fn, user_data, stack_size);
4168}
4169
Ted Kremenekfb480492010-01-13 21:46:36 +00004170} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00004171
Ted Kremenekfb480492010-01-13 21:46:36 +00004172//===----------------------------------------------------------------------===//
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004173// Token-based Operations.
4174//===----------------------------------------------------------------------===//
4175
4176/* CXToken layout:
4177 * int_data[0]: a CXTokenKind
4178 * int_data[1]: starting token location
4179 * int_data[2]: token length
4180 * int_data[3]: reserved
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004181 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004182 * otherwise unused.
4183 */
4184extern "C" {
4185
4186CXTokenKind clang_getTokenKind(CXToken CXTok) {
4187 return static_cast<CXTokenKind>(CXTok.int_data[0]);
4188}
4189
4190CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
4191 switch (clang_getTokenKind(CXTok)) {
4192 case CXToken_Identifier:
4193 case CXToken_Keyword:
4194 // We know we have an IdentifierInfo*, so use that.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004195 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
4196 ->getNameStart());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004197
4198 case CXToken_Literal: {
4199 // We have stashed the starting pointer in the ptr_data field. Use it.
4200 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004201 return createCXString(llvm::StringRef(Text, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004202 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004203
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004204 case CXToken_Punctuation:
4205 case CXToken_Comment:
4206 break;
4207 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004208
4209 // We have to find the starting buffer pointer the hard way, by
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004210 // deconstructing the source location.
Ted Kremeneka60ed472010-11-16 08:15:36 +00004211 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004212 if (!CXXUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004213 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004214
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004215 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
4216 std::pair<FileID, unsigned> LocInfo
4217 = CXXUnit->getSourceManager().getDecomposedLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +00004218 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004219 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00004220 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
4221 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00004222 return createCXString("");
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004223
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004224 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004225}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004226
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004227CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00004228 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004229 if (!CXXUnit)
4230 return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004231
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004232 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
4233 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
4234}
4235
4236CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00004237 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor5352ac02010-01-28 00:27:43 +00004238 if (!CXXUnit)
4239 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004240
4241 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004242 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
4243}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004244
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004245void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
4246 CXToken **Tokens, unsigned *NumTokens) {
4247 if (Tokens)
4248 *Tokens = 0;
4249 if (NumTokens)
4250 *NumTokens = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004251
Ted Kremeneka60ed472010-11-16 08:15:36 +00004252 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004253 if (!CXXUnit || !Tokens || !NumTokens)
4254 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004255
Douglas Gregorbdf60622010-03-05 21:16:25 +00004256 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
4257
Daniel Dunbar85b988f2010-02-14 08:31:57 +00004258 SourceRange R = cxloc::translateCXSourceRange(Range);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004259 if (R.isInvalid())
4260 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004261
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004262 SourceManager &SourceMgr = CXXUnit->getSourceManager();
4263 std::pair<FileID, unsigned> BeginLocInfo
4264 = SourceMgr.getDecomposedLoc(R.getBegin());
4265 std::pair<FileID, unsigned> EndLocInfo
4266 = SourceMgr.getDecomposedLoc(R.getEnd());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004267
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004268 // Cannot tokenize across files.
4269 if (BeginLocInfo.first != EndLocInfo.first)
4270 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004271
4272 // Create a lexer
Douglas Gregorf715ca12010-03-16 00:06:06 +00004273 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004274 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00004275 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
Douglas Gregor47a3fcd2010-03-16 20:26:15 +00004276 if (Invalid)
4277 return;
Douglas Gregoraea67db2010-03-15 22:54:52 +00004278
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004279 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
4280 CXXUnit->getASTContext().getLangOptions(),
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004281 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004282 Lex.SetCommentRetentionState(true);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004283
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004284 // Lex tokens until we hit the end of the range.
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004285 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004286 llvm::SmallVector<CXToken, 32> CXTokens;
4287 Token Tok;
David Chisnall096428b2010-10-13 21:44:48 +00004288 bool previousWasAt = false;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004289 do {
4290 // Lex the next token
4291 Lex.LexFromRawLexer(Tok);
4292 if (Tok.is(tok::eof))
4293 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004294
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004295 // Initialize the CXToken.
4296 CXToken CXTok;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004297
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004298 // - Common fields
4299 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
4300 CXTok.int_data[2] = Tok.getLength();
4301 CXTok.int_data[3] = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004302
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004303 // - Kind-specific fields
4304 if (Tok.isLiteral()) {
4305 CXTok.int_data[0] = CXToken_Literal;
4306 CXTok.ptr_data = (void *)Tok.getLiteralData();
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00004307 } else if (Tok.is(tok::raw_identifier)) {
Douglas Gregoraea67db2010-03-15 22:54:52 +00004308 // Lookup the identifier to determine whether we have a keyword.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004309 IdentifierInfo *II
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00004310 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok);
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004311
David Chisnall096428b2010-10-13 21:44:48 +00004312 if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004313 CXTok.int_data[0] = CXToken_Keyword;
4314 }
4315 else {
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00004316 CXTok.int_data[0] = Tok.is(tok::identifier)
4317 ? CXToken_Identifier
4318 : CXToken_Keyword;
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004319 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004320 CXTok.ptr_data = II;
4321 } else if (Tok.is(tok::comment)) {
4322 CXTok.int_data[0] = CXToken_Comment;
4323 CXTok.ptr_data = 0;
4324 } else {
4325 CXTok.int_data[0] = CXToken_Punctuation;
4326 CXTok.ptr_data = 0;
4327 }
4328 CXTokens.push_back(CXTok);
David Chisnall096428b2010-10-13 21:44:48 +00004329 previousWasAt = Tok.is(tok::at);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004330 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004331
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004332 if (CXTokens.empty())
4333 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004334
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004335 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
4336 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
4337 *NumTokens = CXTokens.size();
4338}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004339
Ted Kremenek6db61092010-05-05 00:55:15 +00004340void clang_disposeTokens(CXTranslationUnit TU,
4341 CXToken *Tokens, unsigned NumTokens) {
4342 free(Tokens);
4343}
4344
4345} // end: extern "C"
4346
4347//===----------------------------------------------------------------------===//
4348// Token annotation APIs.
4349//===----------------------------------------------------------------------===//
4350
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004351typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004352static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
4353 CXCursor parent,
4354 CXClientData client_data);
Ted Kremenek6db61092010-05-05 00:55:15 +00004355namespace {
4356class AnnotateTokensWorker {
4357 AnnotateTokensData &Annotated;
Ted Kremenek11949cb2010-05-05 00:55:17 +00004358 CXToken *Tokens;
4359 CXCursor *Cursors;
4360 unsigned NumTokens;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004361 unsigned TokIdx;
Douglas Gregor4419b672010-10-21 06:10:04 +00004362 unsigned PreprocessingTokIdx;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004363 CursorVisitor AnnotateVis;
4364 SourceManager &SrcMgr;
Douglas Gregorf5251602011-03-08 17:10:18 +00004365 bool HasContextSensitiveKeywords;
4366
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004367 bool MoreTokens() const { return TokIdx < NumTokens; }
4368 unsigned NextToken() const { return TokIdx; }
4369 void AdvanceToken() { ++TokIdx; }
4370 SourceLocation GetTokenLoc(unsigned tokI) {
4371 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
4372 }
4373
Ted Kremenek6db61092010-05-05 00:55:15 +00004374public:
Ted Kremenek11949cb2010-05-05 00:55:17 +00004375 AnnotateTokensWorker(AnnotateTokensData &annotated,
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004376 CXToken *tokens, CXCursor *cursors, unsigned numTokens,
Ted Kremeneka60ed472010-11-16 08:15:36 +00004377 CXTranslationUnit tu, SourceRange RegionOfInterest)
Ted Kremenek11949cb2010-05-05 00:55:17 +00004378 : Annotated(annotated), Tokens(tokens), Cursors(cursors),
Douglas Gregor4419b672010-10-21 06:10:04 +00004379 NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004380 AnnotateVis(tu,
4381 AnnotateTokensVisitor, this,
Douglas Gregor04a9eb32011-03-16 23:23:30 +00004382 Decl::MaxPCHLevel, true, RegionOfInterest),
Douglas Gregorf5251602011-03-08 17:10:18 +00004383 SrcMgr(static_cast<ASTUnit*>(tu->TUData)->getSourceManager()),
4384 HasContextSensitiveKeywords(false) { }
Ted Kremenek11949cb2010-05-05 00:55:17 +00004385
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004386 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
Ted Kremenek6db61092010-05-05 00:55:15 +00004387 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004388 void AnnotateTokens(CXCursor parent);
Ted Kremenekab979612010-11-11 08:05:23 +00004389 void AnnotateTokens() {
Ted Kremeneka60ed472010-11-16 08:15:36 +00004390 AnnotateTokens(clang_getTranslationUnitCursor(AnnotateVis.getTU()));
Ted Kremenekab979612010-11-11 08:05:23 +00004391 }
Douglas Gregorf5251602011-03-08 17:10:18 +00004392
4393 /// \brief Determine whether the annotator saw any cursors that have
4394 /// context-sensitive keywords.
4395 bool hasContextSensitiveKeywords() const {
4396 return HasContextSensitiveKeywords;
4397 }
Ted Kremenek6db61092010-05-05 00:55:15 +00004398};
4399}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004400
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004401void AnnotateTokensWorker::AnnotateTokens(CXCursor parent) {
4402 // Walk the AST within the region of interest, annotating tokens
4403 // along the way.
4404 VisitChildren(parent);
Ted Kremenek11949cb2010-05-05 00:55:17 +00004405
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004406 for (unsigned I = 0 ; I < TokIdx ; ++I) {
4407 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
Douglas Gregor4419b672010-10-21 06:10:04 +00004408 if (Pos != Annotated.end() &&
4409 (clang_isInvalid(Cursors[I].kind) ||
4410 Pos->second.kind != CXCursor_PreprocessingDirective))
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004411 Cursors[I] = Pos->second;
4412 }
4413
4414 // Finish up annotating any tokens left.
4415 if (!MoreTokens())
4416 return;
4417
4418 const CXCursor &C = clang_getNullCursor();
4419 for (unsigned I = TokIdx ; I < NumTokens ; ++I) {
4420 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
4421 Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second;
Ted Kremenek11949cb2010-05-05 00:55:17 +00004422 }
4423}
4424
Ted Kremenek6db61092010-05-05 00:55:15 +00004425enum CXChildVisitResult
Douglas Gregor4419b672010-10-21 06:10:04 +00004426AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004427 CXSourceLocation Loc = clang_getCursorLocation(cursor);
Douglas Gregor4419b672010-10-21 06:10:04 +00004428 SourceRange cursorRange = getRawCursorExtent(cursor);
Douglas Gregor81d3c042010-11-01 20:13:04 +00004429 if (cursorRange.isInvalid())
4430 return CXChildVisit_Recurse;
Douglas Gregorf5251602011-03-08 17:10:18 +00004431
4432 if (!HasContextSensitiveKeywords) {
4433 // Objective-C properties can have context-sensitive keywords.
4434 if (cursor.kind == CXCursor_ObjCPropertyDecl) {
4435 if (ObjCPropertyDecl *Property
4436 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(cursor)))
4437 HasContextSensitiveKeywords = Property->getPropertyAttributesAsWritten() != 0;
4438 }
4439 // Objective-C methods can have context-sensitive keywords.
4440 else if (cursor.kind == CXCursor_ObjCInstanceMethodDecl ||
4441 cursor.kind == CXCursor_ObjCClassMethodDecl) {
4442 if (ObjCMethodDecl *Method
4443 = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
4444 if (Method->getObjCDeclQualifier())
4445 HasContextSensitiveKeywords = true;
4446 else {
4447 for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
4448 PEnd = Method->param_end();
4449 P != PEnd; ++P) {
4450 if ((*P)->getObjCDeclQualifier()) {
4451 HasContextSensitiveKeywords = true;
4452 break;
4453 }
4454 }
4455 }
4456 }
4457 }
4458 // C++ methods can have context-sensitive keywords.
4459 else if (cursor.kind == CXCursor_CXXMethod) {
4460 if (CXXMethodDecl *Method
4461 = dyn_cast_or_null<CXXMethodDecl>(getCursorDecl(cursor))) {
4462 if (Method->hasAttr<FinalAttr>() || Method->hasAttr<OverrideAttr>())
4463 HasContextSensitiveKeywords = true;
4464 }
4465 }
4466 // C++ classes can have context-sensitive keywords.
4467 else if (cursor.kind == CXCursor_StructDecl ||
4468 cursor.kind == CXCursor_ClassDecl ||
4469 cursor.kind == CXCursor_ClassTemplate ||
4470 cursor.kind == CXCursor_ClassTemplatePartialSpecialization) {
4471 if (Decl *D = getCursorDecl(cursor))
4472 if (D->hasAttr<FinalAttr>())
4473 HasContextSensitiveKeywords = true;
4474 }
4475 }
4476
Douglas Gregor4419b672010-10-21 06:10:04 +00004477 if (clang_isPreprocessing(cursor.kind)) {
4478 // For macro instantiations, just note where the beginning of the macro
4479 // instantiation occurs.
4480 if (cursor.kind == CXCursor_MacroInstantiation) {
4481 Annotated[Loc.int_data] = cursor;
4482 return CXChildVisit_Recurse;
4483 }
4484
Douglas Gregor4419b672010-10-21 06:10:04 +00004485 // Items in the preprocessing record are kept separate from items in
4486 // declarations, so we keep a separate token index.
4487 unsigned SavedTokIdx = TokIdx;
4488 TokIdx = PreprocessingTokIdx;
4489
4490 // Skip tokens up until we catch up to the beginning of the preprocessing
4491 // entry.
4492 while (MoreTokens()) {
4493 const unsigned I = NextToken();
4494 SourceLocation TokLoc = GetTokenLoc(I);
4495 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4496 case RangeBefore:
4497 AdvanceToken();
4498 continue;
4499 case RangeAfter:
4500 case RangeOverlap:
4501 break;
4502 }
4503 break;
4504 }
4505
4506 // Look at all of the tokens within this range.
4507 while (MoreTokens()) {
4508 const unsigned I = NextToken();
4509 SourceLocation TokLoc = GetTokenLoc(I);
4510 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4511 case RangeBefore:
4512 assert(0 && "Infeasible");
4513 case RangeAfter:
4514 break;
4515 case RangeOverlap:
4516 Cursors[I] = cursor;
4517 AdvanceToken();
4518 continue;
4519 }
4520 break;
4521 }
4522
4523 // Save the preprocessing token index; restore the non-preprocessing
4524 // token index.
4525 PreprocessingTokIdx = TokIdx;
4526 TokIdx = SavedTokIdx;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004527 return CXChildVisit_Recurse;
4528 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004529
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004530 if (cursorRange.isInvalid())
4531 return CXChildVisit_Continue;
Ted Kremeneka333c662010-05-12 05:29:33 +00004532
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004533 SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data);
4534
Ted Kremeneka333c662010-05-12 05:29:33 +00004535 // Adjust the annotated range based specific declarations.
4536 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
4537 if (cursorK >= CXCursor_FirstDecl && cursorK <= CXCursor_LastDecl) {
Ted Kremenek23173d72010-05-18 21:09:07 +00004538 Decl *D = cxcursor::getCursorDecl(cursor);
4539 // Don't visit synthesized ObjC methods, since they have no syntatic
4540 // representation in the source.
4541 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
4542 if (MD->isSynthesized())
4543 return CXChildVisit_Continue;
4544 }
Douglas Gregor2494dd02011-03-01 01:34:45 +00004545
4546 SourceLocation StartLoc;
Ted Kremenek23173d72010-05-18 21:09:07 +00004547 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
Douglas Gregor2494dd02011-03-01 01:34:45 +00004548 if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
4549 StartLoc = TI->getTypeLoc().getSourceRange().getBegin();
4550 } else if (TypedefDecl *Typedef = dyn_cast<TypedefDecl>(D)) {
4551 if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
4552 StartLoc = TI->getTypeLoc().getSourceRange().getBegin();
Ted Kremeneka333c662010-05-12 05:29:33 +00004553 }
Douglas Gregor2494dd02011-03-01 01:34:45 +00004554
4555 if (StartLoc.isValid() && L.isValid() &&
4556 SrcMgr.isBeforeInTranslationUnit(StartLoc, L))
4557 cursorRange.setBegin(StartLoc);
Ted Kremeneka333c662010-05-12 05:29:33 +00004558 }
Douglas Gregor81d3c042010-11-01 20:13:04 +00004559
Ted Kremenek3f404602010-08-14 01:14:06 +00004560 // If the location of the cursor occurs within a macro instantiation, record
4561 // the spelling location of the cursor in our annotation map. We can then
4562 // paper over the token labelings during a post-processing step to try and
4563 // get cursor mappings for tokens that are the *arguments* of a macro
4564 // instantiation.
4565 if (L.isMacroID()) {
4566 unsigned rawEncoding = SrcMgr.getSpellingLoc(L).getRawEncoding();
4567 // Only invalidate the old annotation if it isn't part of a preprocessing
4568 // directive. Here we assume that the default construction of CXCursor
4569 // results in CXCursor.kind being an initialized value (i.e., 0). If
4570 // this isn't the case, we can fix by doing lookup + insertion.
Douglas Gregor4419b672010-10-21 06:10:04 +00004571
Ted Kremenek3f404602010-08-14 01:14:06 +00004572 CXCursor &oldC = Annotated[rawEncoding];
4573 if (!clang_isPreprocessing(oldC.kind))
4574 oldC = cursor;
4575 }
4576
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004577 const enum CXCursorKind K = clang_getCursorKind(parent);
4578 const CXCursor updateC =
Ted Kremenekd8b0a842010-08-25 22:16:02 +00004579 (clang_isInvalid(K) || K == CXCursor_TranslationUnit)
4580 ? clang_getNullCursor() : parent;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004581
4582 while (MoreTokens()) {
4583 const unsigned I = NextToken();
4584 SourceLocation TokLoc = GetTokenLoc(I);
4585 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4586 case RangeBefore:
4587 Cursors[I] = updateC;
4588 AdvanceToken();
4589 continue;
4590 case RangeAfter:
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004591 case RangeOverlap:
4592 break;
4593 }
4594 break;
4595 }
4596
4597 // Visit children to get their cursor information.
4598 const unsigned BeforeChildren = NextToken();
4599 VisitChildren(cursor);
4600 const unsigned AfterChildren = NextToken();
4601
4602 // Adjust 'Last' to the last token within the extent of the cursor.
4603 while (MoreTokens()) {
4604 const unsigned I = NextToken();
4605 SourceLocation TokLoc = GetTokenLoc(I);
4606 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4607 case RangeBefore:
4608 assert(0 && "Infeasible");
4609 case RangeAfter:
4610 break;
4611 case RangeOverlap:
4612 Cursors[I] = updateC;
4613 AdvanceToken();
4614 continue;
4615 }
4616 break;
4617 }
4618 const unsigned Last = NextToken();
Ted Kremenek6db61092010-05-05 00:55:15 +00004619
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004620 // Scan the tokens that are at the beginning of the cursor, but are not
4621 // capture by the child cursors.
4622
4623 // For AST elements within macros, rely on a post-annotate pass to
4624 // to correctly annotate the tokens with cursors. Otherwise we can
4625 // get confusing results of having tokens that map to cursors that really
4626 // are expanded by an instantiation.
4627 if (L.isMacroID())
4628 cursor = clang_getNullCursor();
4629
4630 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
4631 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
4632 break;
Douglas Gregor4419b672010-10-21 06:10:04 +00004633
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004634 Cursors[I] = cursor;
4635 }
4636 // Scan the tokens that are at the end of the cursor, but are not captured
4637 // but the child cursors.
4638 for (unsigned I = AfterChildren; I != Last; ++I)
4639 Cursors[I] = cursor;
4640
4641 TokIdx = Last;
4642 return CXChildVisit_Continue;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004643}
4644
Ted Kremenek6db61092010-05-05 00:55:15 +00004645static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
4646 CXCursor parent,
4647 CXClientData client_data) {
4648 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
4649}
4650
Ted Kremenek6628a612011-03-18 22:51:30 +00004651namespace {
4652 struct clang_annotateTokens_Data {
4653 CXTranslationUnit TU;
4654 ASTUnit *CXXUnit;
4655 CXToken *Tokens;
4656 unsigned NumTokens;
4657 CXCursor *Cursors;
4658 };
4659}
4660
Ted Kremenekab979612010-11-11 08:05:23 +00004661// This gets run a separate thread to avoid stack blowout.
Ted Kremenek6628a612011-03-18 22:51:30 +00004662static void clang_annotateTokensImpl(void *UserData) {
4663 CXTranslationUnit TU = ((clang_annotateTokens_Data*)UserData)->TU;
4664 ASTUnit *CXXUnit = ((clang_annotateTokens_Data*)UserData)->CXXUnit;
4665 CXToken *Tokens = ((clang_annotateTokens_Data*)UserData)->Tokens;
4666 const unsigned NumTokens = ((clang_annotateTokens_Data*)UserData)->NumTokens;
4667 CXCursor *Cursors = ((clang_annotateTokens_Data*)UserData)->Cursors;
4668
4669 // Determine the region of interest, which contains all of the tokens.
4670 SourceRange RegionOfInterest;
4671 RegionOfInterest.setBegin(
4672 cxloc::translateSourceLocation(clang_getTokenLocation(TU, Tokens[0])));
4673 RegionOfInterest.setEnd(
4674 cxloc::translateSourceLocation(clang_getTokenLocation(TU,
4675 Tokens[NumTokens-1])));
4676
4677 // A mapping from the source locations found when re-lexing or traversing the
4678 // region of interest to the corresponding cursors.
4679 AnnotateTokensData Annotated;
4680
4681 // Relex the tokens within the source range to look for preprocessing
4682 // directives.
4683 SourceManager &SourceMgr = CXXUnit->getSourceManager();
4684 std::pair<FileID, unsigned> BeginLocInfo
4685 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
4686 std::pair<FileID, unsigned> EndLocInfo
4687 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
4688
4689 llvm::StringRef Buffer;
4690 bool Invalid = false;
4691 if (BeginLocInfo.first == EndLocInfo.first &&
4692 ((Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid)),true) &&
4693 !Invalid) {
4694 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
4695 CXXUnit->getASTContext().getLangOptions(),
4696 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
4697 Buffer.end());
4698 Lex.SetCommentRetentionState(true);
4699
4700 // Lex tokens in raw mode until we hit the end of the range, to avoid
4701 // entering #includes or expanding macros.
4702 while (true) {
4703 Token Tok;
4704 Lex.LexFromRawLexer(Tok);
4705
4706 reprocess:
4707 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
4708 // We have found a preprocessing directive. Gobble it up so that we
4709 // don't see it while preprocessing these tokens later, but keep track
4710 // of all of the token locations inside this preprocessing directive so
4711 // that we can annotate them appropriately.
4712 //
4713 // FIXME: Some simple tests here could identify macro definitions and
4714 // #undefs, to provide specific cursor kinds for those.
4715 llvm::SmallVector<SourceLocation, 32> Locations;
4716 do {
4717 Locations.push_back(Tok.getLocation());
4718 Lex.LexFromRawLexer(Tok);
4719 } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
4720
4721 using namespace cxcursor;
4722 CXCursor Cursor
4723 = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
4724 Locations.back()),
4725 TU);
4726 for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
4727 Annotated[Locations[I].getRawEncoding()] = Cursor;
4728 }
4729
4730 if (Tok.isAtStartOfLine())
4731 goto reprocess;
4732
4733 continue;
4734 }
4735
4736 if (Tok.is(tok::eof))
4737 break;
4738 }
4739 }
4740
4741 // Annotate all of the source locations in the region of interest that map to
4742 // a specific cursor.
4743 AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens,
4744 TU, RegionOfInterest);
4745
4746 // FIXME: We use a ridiculous stack size here because the data-recursion
4747 // algorithm uses a large stack frame than the non-data recursive version,
4748 // and AnnotationTokensWorker currently transforms the data-recursion
4749 // algorithm back into a traditional recursion by explicitly calling
4750 // VisitChildren(). We will need to remove this explicit recursive call.
4751 W.AnnotateTokens();
4752
4753 // If we ran into any entities that involve context-sensitive keywords,
4754 // take another pass through the tokens to mark them as such.
4755 if (W.hasContextSensitiveKeywords()) {
4756 for (unsigned I = 0; I != NumTokens; ++I) {
4757 if (clang_getTokenKind(Tokens[I]) != CXToken_Identifier)
4758 continue;
4759
4760 if (Cursors[I].kind == CXCursor_ObjCPropertyDecl) {
4761 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
4762 if (ObjCPropertyDecl *Property
4763 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(Cursors[I]))) {
4764 if (Property->getPropertyAttributesAsWritten() != 0 &&
4765 llvm::StringSwitch<bool>(II->getName())
4766 .Case("readonly", true)
4767 .Case("assign", true)
4768 .Case("readwrite", true)
4769 .Case("retain", true)
4770 .Case("copy", true)
4771 .Case("nonatomic", true)
4772 .Case("atomic", true)
4773 .Case("getter", true)
4774 .Case("setter", true)
4775 .Default(false))
4776 Tokens[I].int_data[0] = CXToken_Keyword;
4777 }
4778 continue;
4779 }
4780
4781 if (Cursors[I].kind == CXCursor_ObjCInstanceMethodDecl ||
4782 Cursors[I].kind == CXCursor_ObjCClassMethodDecl) {
4783 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
4784 if (llvm::StringSwitch<bool>(II->getName())
4785 .Case("in", true)
4786 .Case("out", true)
4787 .Case("inout", true)
4788 .Case("oneway", true)
4789 .Case("bycopy", true)
4790 .Case("byref", true)
4791 .Default(false))
4792 Tokens[I].int_data[0] = CXToken_Keyword;
4793 continue;
4794 }
4795
4796 if (Cursors[I].kind == CXCursor_CXXMethod) {
4797 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
4798 if (CXXMethodDecl *Method
4799 = dyn_cast_or_null<CXXMethodDecl>(getCursorDecl(Cursors[I]))) {
4800 if ((Method->hasAttr<FinalAttr>() ||
4801 Method->hasAttr<OverrideAttr>()) &&
4802 Method->getLocation().getRawEncoding() != Tokens[I].int_data[1] &&
4803 llvm::StringSwitch<bool>(II->getName())
4804 .Case("final", true)
4805 .Case("override", true)
4806 .Default(false))
4807 Tokens[I].int_data[0] = CXToken_Keyword;
4808 }
4809 continue;
4810 }
4811
4812 if (Cursors[I].kind == CXCursor_ClassDecl ||
4813 Cursors[I].kind == CXCursor_StructDecl ||
4814 Cursors[I].kind == CXCursor_ClassTemplate) {
4815 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
4816 if (II->getName() == "final") {
4817 // We have to be careful with 'final', since it could be the name
4818 // of a member class rather than the context-sensitive keyword.
4819 // So, check whether the cursor associated with this
4820 Decl *D = getCursorDecl(Cursors[I]);
4821 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(D)) {
4822 if ((Record->hasAttr<FinalAttr>()) &&
4823 Record->getIdentifier() != II)
4824 Tokens[I].int_data[0] = CXToken_Keyword;
4825 } else if (ClassTemplateDecl *ClassTemplate
4826 = dyn_cast_or_null<ClassTemplateDecl>(D)) {
4827 CXXRecordDecl *Record = ClassTemplate->getTemplatedDecl();
4828 if ((Record->hasAttr<FinalAttr>()) &&
4829 Record->getIdentifier() != II)
4830 Tokens[I].int_data[0] = CXToken_Keyword;
4831 }
4832 }
4833 continue;
4834 }
4835 }
4836 }
Ted Kremenekab979612010-11-11 08:05:23 +00004837}
4838
Ted Kremenek6db61092010-05-05 00:55:15 +00004839extern "C" {
4840
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004841void clang_annotateTokens(CXTranslationUnit TU,
4842 CXToken *Tokens, unsigned NumTokens,
4843 CXCursor *Cursors) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004844
4845 if (NumTokens == 0 || !Tokens || !Cursors)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004846 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004847
Douglas Gregor4419b672010-10-21 06:10:04 +00004848 // Any token we don't specifically annotate will have a NULL cursor.
4849 CXCursor C = clang_getNullCursor();
4850 for (unsigned I = 0; I != NumTokens; ++I)
4851 Cursors[I] = C;
4852
Ted Kremeneka60ed472010-11-16 08:15:36 +00004853 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor4419b672010-10-21 06:10:04 +00004854 if (!CXXUnit)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004855 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004856
Douglas Gregorbdf60622010-03-05 21:16:25 +00004857 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ted Kremenek6628a612011-03-18 22:51:30 +00004858
4859 clang_annotateTokens_Data data = { TU, CXXUnit, Tokens, NumTokens, Cursors };
Ted Kremenekab979612010-11-11 08:05:23 +00004860 llvm::CrashRecoveryContext CRC;
Ted Kremenek6628a612011-03-18 22:51:30 +00004861 if (!RunSafely(CRC, clang_annotateTokensImpl, &data,
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00004862 GetSafetyThreadStackSize() * 2)) {
Ted Kremenekab979612010-11-11 08:05:23 +00004863 fprintf(stderr, "libclang: crash detected while annotating tokens\n");
4864 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004865}
Ted Kremenek6628a612011-03-18 22:51:30 +00004866
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004867} // end: extern "C"
4868
4869//===----------------------------------------------------------------------===//
Ted Kremenek16b42592010-03-03 06:36:57 +00004870// Operations for querying linkage of a cursor.
4871//===----------------------------------------------------------------------===//
4872
4873extern "C" {
4874CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
Douglas Gregor0396f462010-03-19 05:22:59 +00004875 if (!clang_isDeclaration(cursor.kind))
4876 return CXLinkage_Invalid;
4877
Ted Kremenek16b42592010-03-03 06:36:57 +00004878 Decl *D = cxcursor::getCursorDecl(cursor);
4879 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
4880 switch (ND->getLinkage()) {
4881 case NoLinkage: return CXLinkage_NoLinkage;
4882 case InternalLinkage: return CXLinkage_Internal;
4883 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
4884 case ExternalLinkage: return CXLinkage_External;
4885 };
4886
4887 return CXLinkage_Invalid;
4888}
4889} // end: extern "C"
4890
4891//===----------------------------------------------------------------------===//
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004892// Operations for querying language of a cursor.
4893//===----------------------------------------------------------------------===//
4894
4895static CXLanguageKind getDeclLanguage(const Decl *D) {
4896 switch (D->getKind()) {
4897 default:
4898 break;
4899 case Decl::ImplicitParam:
4900 case Decl::ObjCAtDefsField:
4901 case Decl::ObjCCategory:
4902 case Decl::ObjCCategoryImpl:
4903 case Decl::ObjCClass:
4904 case Decl::ObjCCompatibleAlias:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004905 case Decl::ObjCForwardProtocol:
4906 case Decl::ObjCImplementation:
4907 case Decl::ObjCInterface:
4908 case Decl::ObjCIvar:
4909 case Decl::ObjCMethod:
4910 case Decl::ObjCProperty:
4911 case Decl::ObjCPropertyImpl:
4912 case Decl::ObjCProtocol:
4913 return CXLanguage_ObjC;
4914 case Decl::CXXConstructor:
4915 case Decl::CXXConversion:
4916 case Decl::CXXDestructor:
4917 case Decl::CXXMethod:
4918 case Decl::CXXRecord:
4919 case Decl::ClassTemplate:
4920 case Decl::ClassTemplatePartialSpecialization:
4921 case Decl::ClassTemplateSpecialization:
4922 case Decl::Friend:
4923 case Decl::FriendTemplate:
4924 case Decl::FunctionTemplate:
4925 case Decl::LinkageSpec:
4926 case Decl::Namespace:
4927 case Decl::NamespaceAlias:
4928 case Decl::NonTypeTemplateParm:
4929 case Decl::StaticAssert:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004930 case Decl::TemplateTemplateParm:
4931 case Decl::TemplateTypeParm:
4932 case Decl::UnresolvedUsingTypename:
4933 case Decl::UnresolvedUsingValue:
4934 case Decl::Using:
4935 case Decl::UsingDirective:
4936 case Decl::UsingShadow:
4937 return CXLanguage_CPlusPlus;
4938 }
4939
4940 return CXLanguage_C;
4941}
4942
4943extern "C" {
Douglas Gregor58ddb602010-08-23 23:00:57 +00004944
4945enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
4946 if (clang_isDeclaration(cursor.kind))
4947 if (Decl *D = cxcursor::getCursorDecl(cursor)) {
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00004948 if (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted())
Douglas Gregor58ddb602010-08-23 23:00:57 +00004949 return CXAvailability_Available;
4950
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00004951 switch (D->getAvailability()) {
4952 case AR_Available:
4953 case AR_NotYetIntroduced:
4954 return CXAvailability_Available;
4955
4956 case AR_Deprecated:
Douglas Gregor58ddb602010-08-23 23:00:57 +00004957 return CXAvailability_Deprecated;
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00004958
4959 case AR_Unavailable:
4960 return CXAvailability_NotAvailable;
4961 }
Douglas Gregor58ddb602010-08-23 23:00:57 +00004962 }
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00004963
Douglas Gregor58ddb602010-08-23 23:00:57 +00004964 return CXAvailability_Available;
4965}
4966
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004967CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
4968 if (clang_isDeclaration(cursor.kind))
4969 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
4970
4971 return CXLanguage_Invalid;
4972}
Douglas Gregor3910cfd2010-12-21 07:55:45 +00004973
4974 /// \brief If the given cursor is the "templated" declaration
4975 /// descibing a class or function template, return the class or
4976 /// function template.
4977static Decl *maybeGetTemplateCursor(Decl *D) {
4978 if (!D)
4979 return 0;
4980
4981 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
4982 if (FunctionTemplateDecl *FunTmpl = FD->getDescribedFunctionTemplate())
4983 return FunTmpl;
4984
4985 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
4986 if (ClassTemplateDecl *ClassTmpl = RD->getDescribedClassTemplate())
4987 return ClassTmpl;
4988
4989 return D;
4990}
4991
Douglas Gregor2be5bc92010-09-22 21:22:29 +00004992CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
4993 if (clang_isDeclaration(cursor.kind)) {
4994 if (Decl *D = getCursorDecl(cursor)) {
4995 DeclContext *DC = D->getDeclContext();
Douglas Gregor3910cfd2010-12-21 07:55:45 +00004996 if (!DC)
4997 return clang_getNullCursor();
4998
4999 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
5000 getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005001 }
5002 }
5003
5004 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
5005 if (Decl *D = getCursorDecl(cursor))
Ted Kremeneka60ed472010-11-16 08:15:36 +00005006 return MakeCXCursor(D, getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005007 }
5008
5009 return clang_getNullCursor();
5010}
5011
5012CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
5013 if (clang_isDeclaration(cursor.kind)) {
5014 if (Decl *D = getCursorDecl(cursor)) {
5015 DeclContext *DC = D->getLexicalDeclContext();
Douglas Gregor3910cfd2010-12-21 07:55:45 +00005016 if (!DC)
5017 return clang_getNullCursor();
5018
5019 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
5020 getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005021 }
5022 }
5023
5024 // FIXME: Note that we can't easily compute the lexical context of a
5025 // statement or expression, so we return nothing.
5026 return clang_getNullCursor();
5027}
5028
Douglas Gregor9f592342010-10-01 20:25:15 +00005029static void CollectOverriddenMethods(DeclContext *Ctx,
5030 ObjCMethodDecl *Method,
5031 llvm::SmallVectorImpl<ObjCMethodDecl *> &Methods) {
5032 if (!Ctx)
5033 return;
5034
5035 // If we have a class or category implementation, jump straight to the
5036 // interface.
5037 if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(Ctx))
5038 return CollectOverriddenMethods(Impl->getClassInterface(), Method, Methods);
5039
5040 ObjCContainerDecl *Container = dyn_cast<ObjCContainerDecl>(Ctx);
5041 if (!Container)
5042 return;
5043
5044 // Check whether we have a matching method at this level.
5045 if (ObjCMethodDecl *Overridden = Container->getMethod(Method->getSelector(),
5046 Method->isInstanceMethod()))
5047 if (Method != Overridden) {
5048 // We found an override at this level; there is no need to look
5049 // into other protocols or categories.
5050 Methods.push_back(Overridden);
5051 return;
5052 }
5053
5054 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
5055 for (ObjCProtocolDecl::protocol_iterator P = Protocol->protocol_begin(),
5056 PEnd = Protocol->protocol_end();
5057 P != PEnd; ++P)
5058 CollectOverriddenMethods(*P, Method, Methods);
5059 }
5060
5061 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Container)) {
5062 for (ObjCCategoryDecl::protocol_iterator P = Category->protocol_begin(),
5063 PEnd = Category->protocol_end();
5064 P != PEnd; ++P)
5065 CollectOverriddenMethods(*P, Method, Methods);
5066 }
5067
5068 if (ObjCInterfaceDecl *Interface = dyn_cast<ObjCInterfaceDecl>(Container)) {
5069 for (ObjCInterfaceDecl::protocol_iterator P = Interface->protocol_begin(),
5070 PEnd = Interface->protocol_end();
5071 P != PEnd; ++P)
5072 CollectOverriddenMethods(*P, Method, Methods);
5073
5074 for (ObjCCategoryDecl *Category = Interface->getCategoryList();
5075 Category; Category = Category->getNextClassCategory())
5076 CollectOverriddenMethods(Category, Method, Methods);
5077
5078 // We only look into the superclass if we haven't found anything yet.
5079 if (Methods.empty())
5080 if (ObjCInterfaceDecl *Super = Interface->getSuperClass())
5081 return CollectOverriddenMethods(Super, Method, Methods);
5082 }
5083}
5084
5085void clang_getOverriddenCursors(CXCursor cursor,
5086 CXCursor **overridden,
5087 unsigned *num_overridden) {
5088 if (overridden)
5089 *overridden = 0;
5090 if (num_overridden)
5091 *num_overridden = 0;
5092 if (!overridden || !num_overridden)
5093 return;
5094
5095 if (!clang_isDeclaration(cursor.kind))
5096 return;
5097
5098 Decl *D = getCursorDecl(cursor);
5099 if (!D)
5100 return;
5101
5102 // Handle C++ member functions.
Ted Kremeneka60ed472010-11-16 08:15:36 +00005103 CXTranslationUnit TU = getCursorTU(cursor);
Douglas Gregor9f592342010-10-01 20:25:15 +00005104 if (CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
5105 *num_overridden = CXXMethod->size_overridden_methods();
5106 if (!*num_overridden)
5107 return;
5108
5109 *overridden = new CXCursor [*num_overridden];
5110 unsigned I = 0;
5111 for (CXXMethodDecl::method_iterator
5112 M = CXXMethod->begin_overridden_methods(),
5113 MEnd = CXXMethod->end_overridden_methods();
5114 M != MEnd; (void)++M, ++I)
Ted Kremeneka60ed472010-11-16 08:15:36 +00005115 (*overridden)[I] = MakeCXCursor(const_cast<CXXMethodDecl*>(*M), TU);
Douglas Gregor9f592342010-10-01 20:25:15 +00005116 return;
5117 }
5118
5119 ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
5120 if (!Method)
5121 return;
5122
5123 // Handle Objective-C methods.
5124 llvm::SmallVector<ObjCMethodDecl *, 4> Methods;
5125 CollectOverriddenMethods(Method->getDeclContext(), Method, Methods);
5126
5127 if (Methods.empty())
5128 return;
5129
5130 *num_overridden = Methods.size();
5131 *overridden = new CXCursor [Methods.size()];
5132 for (unsigned I = 0, N = Methods.size(); I != N; ++I)
Ted Kremeneka60ed472010-11-16 08:15:36 +00005133 (*overridden)[I] = MakeCXCursor(Methods[I], TU);
Douglas Gregor9f592342010-10-01 20:25:15 +00005134}
5135
5136void clang_disposeOverriddenCursors(CXCursor *overridden) {
5137 delete [] overridden;
5138}
5139
Douglas Gregorecdcb882010-10-20 22:00:55 +00005140CXFile clang_getIncludedFile(CXCursor cursor) {
5141 if (cursor.kind != CXCursor_InclusionDirective)
5142 return 0;
5143
5144 InclusionDirective *ID = getCursorInclusionDirective(cursor);
5145 return (void *)ID->getFile();
5146}
5147
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005148} // end: extern "C"
5149
Ted Kremenek9ada39a2010-05-17 20:06:56 +00005150
5151//===----------------------------------------------------------------------===//
5152// C++ AST instrospection.
5153//===----------------------------------------------------------------------===//
5154
5155extern "C" {
5156unsigned clang_CXXMethod_isStatic(CXCursor C) {
5157 if (!clang_isDeclaration(C.kind))
5158 return 0;
Douglas Gregor49f6f542010-08-31 22:12:17 +00005159
5160 CXXMethodDecl *Method = 0;
5161 Decl *D = cxcursor::getCursorDecl(C);
5162 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
5163 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
5164 else
5165 Method = dyn_cast_or_null<CXXMethodDecl>(D);
5166 return (Method && Method->isStatic()) ? 1 : 0;
Ted Kremenek40b492a2010-05-17 20:12:45 +00005167}
Ted Kremenekb12903e2010-05-18 22:32:15 +00005168
Ted Kremenek9ada39a2010-05-17 20:06:56 +00005169} // end: extern "C"
5170
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005171//===----------------------------------------------------------------------===//
Ted Kremenek95f33552010-08-26 01:42:22 +00005172// Attribute introspection.
5173//===----------------------------------------------------------------------===//
5174
5175extern "C" {
5176CXType clang_getIBOutletCollectionType(CXCursor C) {
5177 if (C.kind != CXCursor_IBOutletCollectionAttr)
Ted Kremeneka60ed472010-11-16 08:15:36 +00005178 return cxtype::MakeCXType(QualType(), cxcursor::getCursorTU(C));
Ted Kremenek95f33552010-08-26 01:42:22 +00005179
5180 IBOutletCollectionAttr *A =
5181 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
5182
Douglas Gregor841b2382011-03-06 18:55:32 +00005183 return cxtype::MakeCXType(A->getInterFace(), cxcursor::getCursorTU(C));
Ted Kremenek95f33552010-08-26 01:42:22 +00005184}
5185} // end: extern "C"
5186
5187//===----------------------------------------------------------------------===//
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005188// Inspecting memory usage.
5189//===----------------------------------------------------------------------===//
5190
Ted Kremenekf7870022011-04-20 16:41:07 +00005191typedef std::vector<CXTUResourceUsageEntry> MemUsageEntries;
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005192
Ted Kremenekf7870022011-04-20 16:41:07 +00005193static inline void createCXTUResourceUsageEntry(MemUsageEntries &entries,
5194 enum CXTUResourceUsageKind k,
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005195 double amount) {
Ted Kremenekf7870022011-04-20 16:41:07 +00005196 CXTUResourceUsageEntry entry = { k, amount };
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005197 entries.push_back(entry);
5198}
5199
5200extern "C" {
5201
Ted Kremenekf7870022011-04-20 16:41:07 +00005202const char *clang_getTUResourceUsageName(CXTUResourceUsageKind kind) {
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005203 const char *str = "";
5204 switch (kind) {
Ted Kremenekf7870022011-04-20 16:41:07 +00005205 case CXTUResourceUsage_AST:
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005206 str = "ASTContext: expressions, declarations, and types";
5207 break;
Ted Kremenekf7870022011-04-20 16:41:07 +00005208 case CXTUResourceUsage_Identifiers:
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005209 str = "ASTContext: identifiers";
5210 break;
Ted Kremenekf7870022011-04-20 16:41:07 +00005211 case CXTUResourceUsage_Selectors:
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005212 str = "ASTContext: selectors";
Ted Kremeneke294ab72011-04-19 04:36:17 +00005213 break;
Ted Kremenekf7870022011-04-20 16:41:07 +00005214 case CXTUResourceUsage_GlobalCompletionResults:
Ted Kremenek4e6a3f72011-04-18 23:42:53 +00005215 str = "Code completion: cached global results";
Ted Kremeneke294ab72011-04-19 04:36:17 +00005216 break;
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005217 }
5218 return str;
5219}
5220
Ted Kremenekf7870022011-04-20 16:41:07 +00005221CXTUResourceUsage clang_getCXTUResourceUsage(CXTranslationUnit TU) {
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005222 if (!TU) {
Ted Kremenekf7870022011-04-20 16:41:07 +00005223 CXTUResourceUsage usage = { (void*) 0, 0, 0 };
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005224 return usage;
5225 }
5226
5227 ASTUnit *astUnit = static_cast<ASTUnit*>(TU->TUData);
5228 llvm::OwningPtr<MemUsageEntries> entries(new MemUsageEntries());
5229 ASTContext &astContext = astUnit->getASTContext();
5230
5231 // How much memory is used by AST nodes and types?
Ted Kremenekf7870022011-04-20 16:41:07 +00005232 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST,
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005233 (unsigned long) astContext.getTotalAllocatedMemory());
5234
5235 // How much memory is used by identifiers?
Ted Kremenekf7870022011-04-20 16:41:07 +00005236 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Identifiers,
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005237 (unsigned long) astContext.Idents.getAllocator().getTotalMemory());
5238
5239 // How much memory is used for selectors?
Ted Kremenekf7870022011-04-20 16:41:07 +00005240 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Selectors,
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005241 (unsigned long) astContext.Selectors.getTotalMemory());
5242
Ted Kremenek4e6a3f72011-04-18 23:42:53 +00005243 // How much memory is used for caching global code completion results?
5244 unsigned long completionBytes = 0;
5245 if (GlobalCodeCompletionAllocator *completionAllocator =
5246 astUnit->getCachedCompletionAllocator().getPtr()) {
5247 completionBytes = completionAllocator-> getTotalMemory();
5248 }
Ted Kremenekf7870022011-04-20 16:41:07 +00005249 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_GlobalCompletionResults,
Ted Kremenek4e6a3f72011-04-18 23:42:53 +00005250 completionBytes);
5251
5252
Ted Kremenekf7870022011-04-20 16:41:07 +00005253 CXTUResourceUsage usage = { (void*) entries.get(),
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005254 (unsigned) entries->size(),
5255 entries->size() ? &(*entries)[0] : 0 };
5256 entries.take();
5257 return usage;
5258}
5259
Ted Kremenekf7870022011-04-20 16:41:07 +00005260void clang_disposeCXTUResourceUsage(CXTUResourceUsage usage) {
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005261 if (usage.data)
5262 delete (MemUsageEntries*) usage.data;
5263}
5264
5265} // end extern "C"
5266
5267//===----------------------------------------------------------------------===//
Ted Kremenek04bb7162010-01-22 22:44:15 +00005268// Misc. utility functions.
5269//===----------------------------------------------------------------------===//
Ted Kremenekf0e23e82010-02-17 00:41:40 +00005270
Daniel Dunbarabdce7a2010-11-05 17:21:46 +00005271/// Default to using an 8 MB stack size on "safety" threads.
5272static unsigned SafetyStackThreadSize = 8 << 20;
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00005273
5274namespace clang {
5275
5276bool RunSafely(llvm::CrashRecoveryContext &CRC,
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00005277 void (*Fn)(void*), void *UserData,
5278 unsigned Size) {
5279 if (!Size)
5280 Size = GetSafetyThreadStackSize();
5281 if (Size)
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00005282 return CRC.RunSafelyOnThread(Fn, UserData, Size);
5283 return CRC.RunSafely(Fn, UserData);
5284}
5285
5286unsigned GetSafetyThreadStackSize() {
5287 return SafetyStackThreadSize;
5288}
5289
5290void SetSafetyThreadStackSize(unsigned Value) {
5291 SafetyStackThreadSize = Value;
5292}
5293
5294}
5295
Ted Kremenek04bb7162010-01-22 22:44:15 +00005296extern "C" {
5297
Ted Kremeneka2a9d6e2010-02-12 22:54:40 +00005298CXString clang_getClangVersion() {
Ted Kremenekee4db4f2010-02-17 00:41:08 +00005299 return createCXString(getClangFullVersion());
Ted Kremenek04bb7162010-01-22 22:44:15 +00005300}
5301
5302} // end: extern "C"
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005303