blob: 563dd6b0277dbc72892718625ad5d21194938b99 [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 Kremeneka297de22010-01-25 22:34:44 +000017#include "CXSourceLocation.h"
Douglas Gregor5352ac02010-01-28 00:27:43 +000018#include "CIndexDiagnostic.h"
Ted Kremenekab188932010-01-05 19:32:54 +000019
Ted Kremenek04bb7162010-01-22 22:44:15 +000020#include "clang/Basic/Version.h"
Douglas Gregor936ea3b2010-01-28 00:56:43 +000021
Steve Naroff50398192009-08-28 15:28:48 +000022#include "clang/AST/DeclVisitor.h"
Steve Narofffb570422009-09-22 19:25:29 +000023#include "clang/AST/StmtVisitor.h"
Douglas Gregor7d0d40e2010-01-21 16:28:34 +000024#include "clang/AST/TypeLocVisitor.h"
Benjamin Kramerb846deb2010-04-12 19:45:50 +000025#include "clang/Basic/Diagnostic.h"
26#include "clang/Frontend/ASTUnit.h"
27#include "clang/Frontend/CompilerInstance.h"
Douglas Gregor936ea3b2010-01-28 00:56:43 +000028#include "clang/Frontend/FrontendDiagnostic.h"
Ted Kremenekd8210652010-01-06 23:43:31 +000029#include "clang/Lex/Lexer.h"
Benjamin Kramerb846deb2010-04-12 19:45:50 +000030#include "clang/Lex/PreprocessingRecord.h"
Douglas Gregor33e9abd2010-01-22 19:49:59 +000031#include "clang/Lex/Preprocessor.h"
Douglas Gregor02465752009-10-16 21:24:31 +000032#include "llvm/Support/MemoryBuffer.h"
Benjamin Kramer0829a832009-10-18 11:19:36 +000033#include "llvm/System/Program.h"
Douglas Gregor0a812cf2010-02-18 23:07:20 +000034#include "llvm/System/Signals.h"
Ted Kremenekfc062212009-10-19 21:44:57 +000035
Benjamin Kramerc2a98162010-03-13 21:22:49 +000036// Needed to define L_TMPNAM on some systems.
37#include <cstdio>
38
Steve Naroff50398192009-08-28 15:28:48 +000039using namespace clang;
Ted Kremenek16c440a2010-01-15 20:35:54 +000040using namespace clang::cxcursor;
Ted Kremenekee4db4f2010-02-17 00:41:08 +000041using namespace clang::cxstring;
Steve Naroff50398192009-08-28 15:28:48 +000042
Ted Kremenek8a8da7d2010-01-06 03:42:32 +000043//===----------------------------------------------------------------------===//
44// Crash Reporting.
45//===----------------------------------------------------------------------===//
46
47#ifdef __APPLE__
Ted Kremenek29b72842010-01-07 22:49:05 +000048#define USE_CRASHTRACER
Ted Kremenek8a8da7d2010-01-06 03:42:32 +000049#include "clang/Analysis/Support/SaveAndRestore.h"
50// Integrate with crash reporter.
51extern "C" const char *__crashreporter_info__;
Ted Kremenek6b569992010-02-17 21:12:23 +000052#define NUM_CRASH_STRINGS 32
Ted Kremenek29b72842010-01-07 22:49:05 +000053static unsigned crashtracer_counter = 0;
Ted Kremenek254ba7c2010-01-07 23:13:53 +000054static unsigned crashtracer_counter_id[NUM_CRASH_STRINGS] = { 0 };
Ted Kremenek29b72842010-01-07 22:49:05 +000055static const char *crashtracer_strings[NUM_CRASH_STRINGS] = { 0 };
56static const char *agg_crashtracer_strings[NUM_CRASH_STRINGS] = { 0 };
57
58static unsigned SetCrashTracerInfo(const char *str,
59 llvm::SmallString<1024> &AggStr) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +000060
Ted Kremenek254ba7c2010-01-07 23:13:53 +000061 unsigned slot = 0;
Ted Kremenek29b72842010-01-07 22:49:05 +000062 while (crashtracer_strings[slot]) {
63 if (++slot == NUM_CRASH_STRINGS)
64 slot = 0;
65 }
66 crashtracer_strings[slot] = str;
Ted Kremenek254ba7c2010-01-07 23:13:53 +000067 crashtracer_counter_id[slot] = ++crashtracer_counter;
Ted Kremenek29b72842010-01-07 22:49:05 +000068
69 // We need to create an aggregate string because multiple threads
70 // may be in this method at one time. The crash reporter string
71 // will attempt to overapproximate the set of in-flight invocations
72 // of this function. Race conditions can still cause this goal
73 // to not be achieved.
74 {
Ted Kremenekf0e23e82010-02-17 00:41:40 +000075 llvm::raw_svector_ostream Out(AggStr);
Ted Kremenek29b72842010-01-07 22:49:05 +000076 for (unsigned i = 0; i < NUM_CRASH_STRINGS; ++i)
77 if (crashtracer_strings[i]) Out << crashtracer_strings[i] << '\n';
78 }
79 __crashreporter_info__ = agg_crashtracer_strings[slot] = AggStr.c_str();
80 return slot;
81}
82
83static void ResetCrashTracerInfo(unsigned slot) {
Ted Kremenek254ba7c2010-01-07 23:13:53 +000084 unsigned max_slot = 0;
85 unsigned max_value = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +000086
Ted Kremenek254ba7c2010-01-07 23:13:53 +000087 crashtracer_strings[slot] = agg_crashtracer_strings[slot] = 0;
88
89 for (unsigned i = 0 ; i < NUM_CRASH_STRINGS; ++i)
90 if (agg_crashtracer_strings[i] &&
91 crashtracer_counter_id[i] > max_value) {
92 max_slot = i;
93 max_value = crashtracer_counter_id[i];
Ted Kremenek29b72842010-01-07 22:49:05 +000094 }
Ted Kremenek254ba7c2010-01-07 23:13:53 +000095
96 __crashreporter_info__ = agg_crashtracer_strings[max_slot];
Ted Kremenek29b72842010-01-07 22:49:05 +000097}
98
99namespace {
100class ArgsCrashTracerInfo {
101 llvm::SmallString<1024> CrashString;
102 llvm::SmallString<1024> AggregateString;
103 unsigned crashtracerSlot;
104public:
105 ArgsCrashTracerInfo(llvm::SmallVectorImpl<const char*> &Args)
106 : crashtracerSlot(0)
107 {
108 {
109 llvm::raw_svector_ostream Out(CrashString);
Ted Kremenek0baa9522010-03-05 22:43:25 +0000110 Out << "ClangCIndex [" << getClangFullVersion() << "]"
111 << "[createTranslationUnitFromSourceFile]: clang";
Ted Kremenek29b72842010-01-07 22:49:05 +0000112 for (llvm::SmallVectorImpl<const char*>::iterator I=Args.begin(),
113 E=Args.end(); I!=E; ++I)
114 Out << ' ' << *I;
115 }
116 crashtracerSlot = SetCrashTracerInfo(CrashString.c_str(),
117 AggregateString);
118 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000119
Ted Kremenek29b72842010-01-07 22:49:05 +0000120 ~ArgsCrashTracerInfo() {
121 ResetCrashTracerInfo(crashtracerSlot);
122 }
123};
124}
125#endif
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000126
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000127/// \brief The result of comparing two source ranges.
128enum RangeComparisonResult {
129 /// \brief Either the ranges overlap or one of the ranges is invalid.
130 RangeOverlap,
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000131
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000132 /// \brief The first range ends before the second range starts.
133 RangeBefore,
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000134
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000135 /// \brief The first range starts after the second range ends.
136 RangeAfter
137};
138
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000139/// \brief Compare two source ranges to determine their relative position in
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000140/// the translation unit.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000141static RangeComparisonResult RangeCompare(SourceManager &SM,
142 SourceRange R1,
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000143 SourceRange R2) {
144 assert(R1.isValid() && "First range is invalid?");
145 assert(R2.isValid() && "Second range is invalid?");
Daniel Dunbard52864b2010-02-14 10:02:57 +0000146 if (R1.getEnd() == R2.getBegin() ||
147 SM.isBeforeInTranslationUnit(R1.getEnd(), R2.getBegin()))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000148 return RangeBefore;
Daniel Dunbard52864b2010-02-14 10:02:57 +0000149 if (R2.getEnd() == R1.getBegin() ||
150 SM.isBeforeInTranslationUnit(R2.getEnd(), R1.getBegin()))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000151 return RangeAfter;
152 return RangeOverlap;
153}
154
Ted Kremenekfbd84ca2010-05-05 00:55:23 +0000155/// \brief Determine if a source location falls within, before, or after a
156/// a given source range.
157static RangeComparisonResult LocationCompare(SourceManager &SM,
158 SourceLocation L, SourceRange R) {
159 assert(R.isValid() && "First range is invalid?");
160 assert(L.isValid() && "Second range is invalid?");
161 if (L == R.getBegin())
162 return RangeOverlap;
163 if (L == R.getEnd())
164 return RangeAfter;
165 if (SM.isBeforeInTranslationUnit(L, R.getBegin()))
166 return RangeBefore;
167 if (SM.isBeforeInTranslationUnit(R.getEnd(), L))
168 return RangeAfter;
169 return RangeOverlap;
170}
171
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000172/// \brief Translate a Clang source range into a CIndex source range.
173///
174/// Clang internally represents ranges where the end location points to the
175/// start of the token at the end. However, for external clients it is more
176/// useful to have a CXSourceRange be a proper half-open interval. This routine
177/// does the appropriate translation.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000178CXSourceRange cxloc::translateSourceRange(const SourceManager &SM,
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000179 const LangOptions &LangOpts,
180 SourceRange R) {
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000181 // We want the last character in this location, so we will adjust the
Douglas Gregor6a5a23f2010-03-19 21:51:54 +0000182 // location accordingly.
183 // FIXME: How do do this with a macro instantiation location?
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000184 SourceLocation EndLoc = R.getEnd();
Douglas Gregor6a5a23f2010-03-19 21:51:54 +0000185 if (!EndLoc.isInvalid() && EndLoc.isFileID()) {
186 unsigned Length = Lexer::MeasureTokenLength(EndLoc, SM, LangOpts);
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000187 EndLoc = EndLoc.getFileLocWithOffset(Length);
188 }
189
190 CXSourceRange Result = { { (void *)&SM, (void *)&LangOpts },
191 R.getBegin().getRawEncoding(),
192 EndLoc.getRawEncoding() };
193 return Result;
194}
Douglas Gregor1db19de2010-01-19 21:36:55 +0000195
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000196//===----------------------------------------------------------------------===//
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000197// Cursor visitor.
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000198//===----------------------------------------------------------------------===//
199
Steve Naroff89922f82009-08-31 00:59:03 +0000200namespace {
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000201
Douglas Gregorb1373d02010-01-20 20:59:29 +0000202// Cursor visitor.
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000203class CursorVisitor : public DeclVisitor<CursorVisitor, bool>,
Douglas Gregora59e3902010-01-21 23:27:09 +0000204 public TypeLocVisitor<CursorVisitor, bool>,
205 public StmtVisitor<CursorVisitor, bool>
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000206{
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000207 /// \brief The translation unit we are traversing.
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000208 ASTUnit *TU;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000209
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000210 /// \brief The parent cursor whose children we are traversing.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000211 CXCursor Parent;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000212
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000213 /// \brief The declaration that serves at the parent of any statement or
214 /// expression nodes.
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000215 Decl *StmtParent;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000216
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000217 /// \brief The visitor function.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000218 CXCursorVisitor Visitor;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000219
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000220 /// \brief The opaque client data, to be passed along to the visitor.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000221 CXClientData ClientData;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000222
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000223 // MaxPCHLevel - the maximum PCH level of declarations that we will pass on
224 // to the visitor. Declarations with a PCH level greater than this value will
225 // be suppressed.
226 unsigned MaxPCHLevel;
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000227
228 /// \brief When valid, a source range to which the cursor should restrict
229 /// its search.
230 SourceRange RegionOfInterest;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000231
Douglas Gregorb1373d02010-01-20 20:59:29 +0000232 using DeclVisitor<CursorVisitor, bool>::Visit;
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000233 using TypeLocVisitor<CursorVisitor, bool>::Visit;
Douglas Gregora59e3902010-01-21 23:27:09 +0000234 using StmtVisitor<CursorVisitor, bool>::Visit;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000235
236 /// \brief Determine whether this particular source range comes before, comes
237 /// after, or overlaps the region of interest.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000238 ///
Daniel Dunbard52864b2010-02-14 10:02:57 +0000239 /// \param R a half-open source range retrieved from the abstract syntax tree.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000240 RangeComparisonResult CompareRegionOfInterest(SourceRange R);
241
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000242 class SetParentRAII {
243 CXCursor &Parent;
244 Decl *&StmtParent;
245 CXCursor OldParent;
246
247 public:
248 SetParentRAII(CXCursor &Parent, Decl *&StmtParent, CXCursor NewParent)
249 : Parent(Parent), StmtParent(StmtParent), OldParent(Parent)
250 {
251 Parent = NewParent;
252 if (clang_isDeclaration(Parent.kind))
253 StmtParent = getCursorDecl(Parent);
254 }
255
256 ~SetParentRAII() {
257 Parent = OldParent;
258 if (clang_isDeclaration(Parent.kind))
259 StmtParent = getCursorDecl(Parent);
260 }
261 };
262
Steve Naroff89922f82009-08-31 00:59:03 +0000263public:
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000264 CursorVisitor(ASTUnit *TU, CXCursorVisitor Visitor, CXClientData ClientData,
265 unsigned MaxPCHLevel,
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000266 SourceRange RegionOfInterest = SourceRange())
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000267 : TU(TU), Visitor(Visitor), ClientData(ClientData),
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000268 MaxPCHLevel(MaxPCHLevel), RegionOfInterest(RegionOfInterest)
Douglas Gregorb1373d02010-01-20 20:59:29 +0000269 {
270 Parent.kind = CXCursor_NoDeclFound;
271 Parent.data[0] = 0;
272 Parent.data[1] = 0;
273 Parent.data[2] = 0;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000274 StmtParent = 0;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000275 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000276
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000277 bool Visit(CXCursor Cursor, bool CheckedRegionOfInterest = false);
Douglas Gregor788f5a12010-03-20 00:41:21 +0000278
279 std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
280 getPreprocessedEntities();
281
Douglas Gregorb1373d02010-01-20 20:59:29 +0000282 bool VisitChildren(CXCursor Parent);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000283
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000284 // Declaration visitors
Ted Kremenek09dfa372010-02-18 05:46:33 +0000285 bool VisitAttributes(Decl *D);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000286 bool VisitBlockDecl(BlockDecl *B);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000287 bool VisitDeclContext(DeclContext *DC);
Ted Kremenek4540c9c2010-02-18 18:47:08 +0000288 bool VisitTranslationUnitDecl(TranslationUnitDecl *D);
289 bool VisitTypedefDecl(TypedefDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000290 bool VisitTagDecl(TagDecl *D);
291 bool VisitEnumConstantDecl(EnumConstantDecl *D);
292 bool VisitDeclaratorDecl(DeclaratorDecl *DD);
293 bool VisitFunctionDecl(FunctionDecl *ND);
294 bool VisitFieldDecl(FieldDecl *D);
Ted Kremenek4540c9c2010-02-18 18:47:08 +0000295 bool VisitVarDecl(VarDecl *);
Ted Kremenek79758f62010-02-18 22:36:18 +0000296 bool VisitObjCMethodDecl(ObjCMethodDecl *ND);
297 bool VisitObjCContainerDecl(ObjCContainerDecl *D);
298 bool VisitObjCCategoryDecl(ObjCCategoryDecl *ND);
299 bool VisitObjCProtocolDecl(ObjCProtocolDecl *PID);
Ted Kremenek23173d72010-05-18 21:09:07 +0000300 bool VisitObjCPropertyDecl(ObjCPropertyDecl *PD);
Ted Kremenek79758f62010-02-18 22:36:18 +0000301 bool VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
302 bool VisitObjCImplDecl(ObjCImplDecl *D);
303 bool VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
304 bool VisitObjCImplementationDecl(ObjCImplementationDecl *D);
305 // FIXME: ObjCPropertyDecl requires TypeSourceInfo, getter/setter locations,
306 // etc.
307 // FIXME: ObjCCompatibleAliasDecl requires aliased-class locations.
308 bool VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D);
309 bool VisitObjCClassDecl(ObjCClassDecl *D);
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 Gregor7d0d40e2010-01-21 16:28:34 +0000312
313 // Type visitors
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000314 // FIXME: QualifiedTypeLoc doesn't provide any location information
315 bool VisitBuiltinTypeLoc(BuiltinTypeLoc TL);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000316 bool VisitTypedefTypeLoc(TypedefTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000317 bool VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL);
318 bool VisitTagTypeLoc(TagTypeLoc TL);
319 // FIXME: TemplateTypeParmTypeLoc doesn't provide any location information
320 bool VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL);
John McCallc12c5bb2010-05-15 11:32:37 +0000321 bool VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000322 bool VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL);
323 bool VisitPointerTypeLoc(PointerTypeLoc TL);
324 bool VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL);
325 bool VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL);
326 bool VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL);
327 bool VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL);
328 bool VisitFunctionTypeLoc(FunctionTypeLoc TL);
329 bool VisitArrayTypeLoc(ArrayTypeLoc TL);
Douglas Gregor2332c112010-01-21 20:48:56 +0000330 // FIXME: Implement for TemplateSpecializationTypeLoc
331 // FIXME: Implement visitors here when the unimplemented TypeLocs get
332 // implemented
333 bool VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL);
334 bool VisitTypeOfTypeLoc(TypeOfTypeLoc TL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000335
Douglas Gregora59e3902010-01-21 23:27:09 +0000336 // Statement visitors
337 bool VisitStmt(Stmt *S);
338 bool VisitDeclStmt(DeclStmt *S);
Douglas Gregorf5bab412010-01-22 01:00:11 +0000339 // FIXME: LabelStmt label?
340 bool VisitIfStmt(IfStmt *S);
341 bool VisitSwitchStmt(SwitchStmt *S);
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000342 bool VisitCaseStmt(CaseStmt *S);
Douglas Gregor263b47b2010-01-25 16:12:32 +0000343 bool VisitWhileStmt(WhileStmt *S);
344 bool VisitForStmt(ForStmt *S);
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000345// bool VisitSwitchCase(SwitchCase *S);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000346
Douglas Gregor336fd812010-01-23 00:40:08 +0000347 // Expression visitors
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000348 bool VisitBlockExpr(BlockExpr *B);
Douglas Gregor336fd812010-01-23 00:40:08 +0000349 bool VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000350 bool VisitExplicitCastExpr(ExplicitCastExpr *E);
Douglas Gregorc2350e52010-03-08 16:40:19 +0000351 bool VisitObjCMessageExpr(ObjCMessageExpr *E);
Douglas Gregor81d34662010-04-20 15:39:42 +0000352 bool VisitObjCEncodeExpr(ObjCEncodeExpr *E);
Douglas Gregor8ecdb652010-04-28 22:16:22 +0000353 bool VisitOffsetOfExpr(OffsetOfExpr *E);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000354 bool VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E);
Steve Naroff89922f82009-08-31 00:59:03 +0000355};
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000356
Ted Kremenekab188932010-01-05 19:32:54 +0000357} // end anonymous namespace
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000358
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000359RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000360 return RangeCompare(TU->getSourceManager(), R, RegionOfInterest);
361}
362
Douglas Gregorb1373d02010-01-20 20:59:29 +0000363/// \brief Visit the given cursor and, if requested by the visitor,
364/// its children.
365///
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000366/// \param Cursor the cursor to visit.
367///
368/// \param CheckRegionOfInterest if true, then the caller already checked that
369/// this cursor is within the region of interest.
370///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000371/// \returns true if the visitation should be aborted, false if it
372/// should continue.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000373bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
Douglas Gregorb1373d02010-01-20 20:59:29 +0000374 if (clang_isInvalid(Cursor.kind))
375 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000376
Douglas Gregorb1373d02010-01-20 20:59:29 +0000377 if (clang_isDeclaration(Cursor.kind)) {
378 Decl *D = getCursorDecl(Cursor);
379 assert(D && "Invalid declaration cursor");
380 if (D->getPCHLevel() > MaxPCHLevel)
381 return false;
382
383 if (D->isImplicit())
384 return false;
385 }
386
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000387 // If we have a range of interest, and this cursor doesn't intersect with it,
388 // we're done.
389 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
Daniel Dunbarf408f322010-02-14 08:32:05 +0000390 SourceRange Range =
391 cxloc::translateCXSourceRange(clang_getCursorExtent(Cursor));
392 if (Range.isInvalid() || CompareRegionOfInterest(Range))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000393 return false;
394 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000395
Douglas Gregorb1373d02010-01-20 20:59:29 +0000396 switch (Visitor(Cursor, Parent, ClientData)) {
397 case CXChildVisit_Break:
398 return true;
399
400 case CXChildVisit_Continue:
401 return false;
402
403 case CXChildVisit_Recurse:
404 return VisitChildren(Cursor);
405 }
406
Douglas Gregorfd643772010-01-25 16:45:46 +0000407 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000408}
409
Douglas Gregor788f5a12010-03-20 00:41:21 +0000410std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
411CursorVisitor::getPreprocessedEntities() {
412 PreprocessingRecord &PPRec
413 = *TU->getPreprocessor().getPreprocessingRecord();
414
415 bool OnlyLocalDecls
416 = !TU->isMainFileAST() && TU->getOnlyLocalDecls();
417
418 // There is no region of interest; we have to walk everything.
419 if (RegionOfInterest.isInvalid())
420 return std::make_pair(PPRec.begin(OnlyLocalDecls),
421 PPRec.end(OnlyLocalDecls));
422
423 // Find the file in which the region of interest lands.
424 SourceManager &SM = TU->getSourceManager();
425 std::pair<FileID, unsigned> Begin
426 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getBegin());
427 std::pair<FileID, unsigned> End
428 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getEnd());
429
430 // The region of interest spans files; we have to walk everything.
431 if (Begin.first != End.first)
432 return std::make_pair(PPRec.begin(OnlyLocalDecls),
433 PPRec.end(OnlyLocalDecls));
434
435 ASTUnit::PreprocessedEntitiesByFileMap &ByFileMap
436 = TU->getPreprocessedEntitiesByFile();
437 if (ByFileMap.empty()) {
438 // Build the mapping from files to sets of preprocessed entities.
439 for (PreprocessingRecord::iterator E = PPRec.begin(OnlyLocalDecls),
440 EEnd = PPRec.end(OnlyLocalDecls);
441 E != EEnd; ++E) {
442 std::pair<FileID, unsigned> P
443 = SM.getDecomposedInstantiationLoc((*E)->getSourceRange().getBegin());
444 ByFileMap[P.first].push_back(*E);
445 }
446 }
447
448 return std::make_pair(ByFileMap[Begin.first].begin(),
449 ByFileMap[Begin.first].end());
450}
451
Douglas Gregorb1373d02010-01-20 20:59:29 +0000452/// \brief Visit the children of the given cursor.
453///
454/// \returns true if the visitation should be aborted, false if it
455/// should continue.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000456bool CursorVisitor::VisitChildren(CXCursor Cursor) {
Douglas Gregora59e3902010-01-21 23:27:09 +0000457 if (clang_isReference(Cursor.kind)) {
458 // By definition, references have no children.
459 return false;
460 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000461
462 // Set the Parent field to Cursor, then back to its old value once we're
Douglas Gregorb1373d02010-01-20 20:59:29 +0000463 // done.
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000464 SetParentRAII SetParent(Parent, StmtParent, Cursor);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000465
Douglas Gregorb1373d02010-01-20 20:59:29 +0000466 if (clang_isDeclaration(Cursor.kind)) {
467 Decl *D = getCursorDecl(Cursor);
468 assert(D && "Invalid declaration cursor");
Ted Kremenek539311e2010-02-18 18:47:01 +0000469 return VisitAttributes(D) || Visit(D);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000470 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000471
Douglas Gregora59e3902010-01-21 23:27:09 +0000472 if (clang_isStatement(Cursor.kind))
473 return Visit(getCursorStmt(Cursor));
474 if (clang_isExpression(Cursor.kind))
475 return Visit(getCursorExpr(Cursor));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000476
Douglas Gregorb1373d02010-01-20 20:59:29 +0000477 if (clang_isTranslationUnit(Cursor.kind)) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000478 ASTUnit *CXXUnit = getCursorASTUnit(Cursor);
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000479 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
480 RegionOfInterest.isInvalid()) {
Douglas Gregor7b691f332010-01-20 21:13:59 +0000481 const std::vector<Decl*> &TLDs = CXXUnit->getTopLevelDecls();
482 for (std::vector<Decl*>::const_iterator it = TLDs.begin(),
483 ie = TLDs.end(); it != ie; ++it) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000484 if (Visit(MakeCXCursor(*it, CXXUnit), true))
Douglas Gregor7b691f332010-01-20 21:13:59 +0000485 return true;
486 }
Douglas Gregor0396f462010-03-19 05:22:59 +0000487 } else if (VisitDeclContext(
488 CXXUnit->getASTContext().getTranslationUnitDecl()))
489 return true;
Bob Wilson3178cb62010-03-19 03:57:57 +0000490
Douglas Gregor0396f462010-03-19 05:22:59 +0000491 // Walk the preprocessing record.
Daniel Dunbar8de30ff2010-03-20 01:11:56 +0000492 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000493 // FIXME: Once we have the ability to deserialize a preprocessing record,
494 // do so.
Douglas Gregor788f5a12010-03-20 00:41:21 +0000495 PreprocessingRecord::iterator E, EEnd;
496 for (llvm::tie(E, EEnd) = getPreprocessedEntities(); E != EEnd; ++E) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000497 if (MacroInstantiation *MI = dyn_cast<MacroInstantiation>(*E)) {
498 if (Visit(MakeMacroInstantiationCursor(MI, CXXUnit)))
499 return true;
Douglas Gregor788f5a12010-03-20 00:41:21 +0000500
Douglas Gregor0396f462010-03-19 05:22:59 +0000501 continue;
502 }
503
504 if (MacroDefinition *MD = dyn_cast<MacroDefinition>(*E)) {
505 if (Visit(MakeMacroDefinitionCursor(MD, CXXUnit)))
506 return true;
507
508 continue;
509 }
510 }
511 }
Douglas Gregor7b691f332010-01-20 21:13:59 +0000512 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000513 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000514
Douglas Gregorb1373d02010-01-20 20:59:29 +0000515 // Nothing to visit at the moment.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000516 return false;
517}
518
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000519bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
520 for (BlockDecl::param_iterator I=B->param_begin(), E=B->param_end(); I!=E;++I)
521 if (Decl *D = *I)
522 if (Visit(D))
523 return true;
524
525 return Visit(MakeCXCursor(B->getBody(), StmtParent, TU));
526}
527
Douglas Gregorb1373d02010-01-20 20:59:29 +0000528bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000529 for (DeclContext::decl_iterator
Douglas Gregorb1373d02010-01-20 20:59:29 +0000530 I = DC->decls_begin(), E = DC->decls_end(); I != E; ++I) {
Ted Kremenek09dfa372010-02-18 05:46:33 +0000531
Ted Kremenek23173d72010-05-18 21:09:07 +0000532 Decl *D = *I;
533 if (D->getLexicalDeclContext() != DC)
534 continue;
535
536 CXCursor Cursor = MakeCXCursor(D, TU);
Daniel Dunbard52864b2010-02-14 10:02:57 +0000537
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000538 if (RegionOfInterest.isValid()) {
Daniel Dunbard52864b2010-02-14 10:02:57 +0000539 SourceRange Range =
540 cxloc::translateCXSourceRange(clang_getCursorExtent(Cursor));
541 if (Range.isInvalid())
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000542 continue;
Daniel Dunbard52864b2010-02-14 10:02:57 +0000543
544 switch (CompareRegionOfInterest(Range)) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000545 case RangeBefore:
546 // This declaration comes before the region of interest; skip it.
547 continue;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000548
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000549 case RangeAfter:
550 // This declaration comes after the region of interest; we're done.
551 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000552
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000553 case RangeOverlap:
554 // This declaration overlaps the region of interest; visit it.
555 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000556 }
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000557 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000558
Daniel Dunbard52864b2010-02-14 10:02:57 +0000559 if (Visit(Cursor, true))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000560 return true;
561 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000562
Douglas Gregorb1373d02010-01-20 20:59:29 +0000563 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000564}
565
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000566bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
567 llvm_unreachable("Translation units are visited directly by Visit()");
568 return false;
569}
570
571bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
572 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
573 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000574
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000575 return false;
576}
577
578bool CursorVisitor::VisitTagDecl(TagDecl *D) {
579 return VisitDeclContext(D);
580}
581
582bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
583 if (Expr *Init = D->getInitExpr())
584 return Visit(MakeCXCursor(Init, StmtParent, TU));
585 return false;
586}
587
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000588bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
589 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
590 if (Visit(TSInfo->getTypeLoc()))
591 return true;
592
593 return false;
594}
595
Douglas Gregorb1373d02010-01-20 20:59:29 +0000596bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000597 if (VisitDeclaratorDecl(ND))
598 return true;
599
Douglas Gregora59e3902010-01-21 23:27:09 +0000600 if (ND->isThisDeclarationADefinition() &&
601 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
602 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000603
Douglas Gregorb1373d02010-01-20 20:59:29 +0000604 return false;
605}
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000606
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000607bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
608 if (VisitDeclaratorDecl(D))
609 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000610
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000611 if (Expr *BitWidth = D->getBitWidth())
612 return Visit(MakeCXCursor(BitWidth, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000613
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000614 return false;
615}
616
617bool CursorVisitor::VisitVarDecl(VarDecl *D) {
618 if (VisitDeclaratorDecl(D))
619 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000620
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000621 if (Expr *Init = D->getInit())
622 return Visit(MakeCXCursor(Init, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000623
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000624 return false;
625}
626
627bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
Douglas Gregor4bc1cb62010-03-08 14:59:44 +0000628 if (TypeSourceInfo *TSInfo = ND->getResultTypeSourceInfo())
629 if (Visit(TSInfo->getTypeLoc()))
630 return true;
631
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000632 for (ObjCMethodDecl::param_iterator P = ND->param_begin(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000633 PEnd = ND->param_end();
634 P != PEnd; ++P) {
635 if (Visit(MakeCXCursor(*P, TU)))
636 return true;
637 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000638
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000639 if (ND->isThisDeclarationADefinition() &&
640 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
641 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000642
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000643 return false;
644}
645
Douglas Gregora59e3902010-01-21 23:27:09 +0000646bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
647 return VisitDeclContext(D);
648}
649
Douglas Gregorb1373d02010-01-20 20:59:29 +0000650bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000651 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
652 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000653 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000654
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000655 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
656 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
657 E = ND->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000658 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000659 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000660
Douglas Gregora59e3902010-01-21 23:27:09 +0000661 return VisitObjCContainerDecl(ND);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000662}
663
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000664bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
665 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
666 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
667 E = PID->protocol_end(); I != E; ++I, ++PL)
668 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
669 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000670
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000671 return VisitObjCContainerDecl(PID);
672}
673
Ted Kremenek23173d72010-05-18 21:09:07 +0000674bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
675 // FIXME: This implements a workaround with @property declarations also being
676 // installed in the DeclContext for the @interface. Eventually this code
677 // should be removed.
678 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
679 if (!CDecl || !CDecl->IsClassExtension())
680 return false;
681
682 ObjCInterfaceDecl *ID = CDecl->getClassInterface();
683 if (!ID)
684 return false;
685
686 IdentifierInfo *PropertyId = PD->getIdentifier();
687 ObjCPropertyDecl *prevDecl =
688 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId);
689
690 if (!prevDecl)
691 return false;
692
693 // Visit synthesized methods since they will be skipped when visiting
694 // the @interface.
695 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
696 if (MD->isSynthesized())
697 if (Visit(MakeCXCursor(MD, TU)))
698 return true;
699
700 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
701 if (MD->isSynthesized())
702 if (Visit(MakeCXCursor(MD, TU)))
703 return true;
704
705 return false;
706}
707
Douglas Gregorb1373d02010-01-20 20:59:29 +0000708bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000709 // Issue callbacks for super class.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000710 if (D->getSuperClass() &&
711 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000712 D->getSuperClassLoc(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000713 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000714 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000715
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000716 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
717 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
718 E = D->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000719 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000720 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000721
Douglas Gregora59e3902010-01-21 23:27:09 +0000722 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000723}
724
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000725bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
726 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000727}
728
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000729bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
Ted Kremenekebfa3392010-03-19 20:39:03 +0000730 // 'ID' could be null when dealing with invalid code.
731 if (ObjCInterfaceDecl *ID = D->getClassInterface())
732 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
733 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000734
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000735 return VisitObjCImplDecl(D);
736}
737
738bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
739#if 0
740 // Issue callbacks for super class.
741 // FIXME: No source location information!
742 if (D->getSuperClass() &&
743 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000744 D->getSuperClassLoc(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000745 TU)))
746 return true;
747#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000748
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000749 return VisitObjCImplDecl(D);
750}
751
752bool CursorVisitor::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D) {
753 ObjCForwardProtocolDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
754 for (ObjCForwardProtocolDecl::protocol_iterator I = D->protocol_begin(),
755 E = D->protocol_end();
756 I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000757 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000758 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000759
760 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000761}
762
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000763bool CursorVisitor::VisitObjCClassDecl(ObjCClassDecl *D) {
764 for (ObjCClassDecl::iterator C = D->begin(), CEnd = D->end(); C != CEnd; ++C)
765 if (Visit(MakeCursorObjCClassRef(C->getInterface(), C->getLocation(), TU)))
766 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000767
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000768 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000769}
770
Ted Kremenek8f06e0e2010-05-06 23:38:21 +0000771bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
772 return VisitDeclContext(D);
773}
774
Ted Kremeneka0536d82010-05-07 01:04:29 +0000775bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
776 return VisitDeclContext(D);
777}
778
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000779bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
780 ASTContext &Context = TU->getASTContext();
781
782 // Some builtin types (such as Objective-C's "id", "sel", and
783 // "Class") have associated declarations. Create cursors for those.
784 QualType VisitType;
785 switch (TL.getType()->getAs<BuiltinType>()->getKind()) {
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000786 case BuiltinType::Void:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000787 case BuiltinType::Bool:
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000788 case BuiltinType::Char_U:
789 case BuiltinType::UChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000790 case BuiltinType::Char16:
791 case BuiltinType::Char32:
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000792 case BuiltinType::UShort:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000793 case BuiltinType::UInt:
794 case BuiltinType::ULong:
795 case BuiltinType::ULongLong:
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000796 case BuiltinType::UInt128:
797 case BuiltinType::Char_S:
798 case BuiltinType::SChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000799 case BuiltinType::WChar:
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000800 case BuiltinType::Short:
801 case BuiltinType::Int:
802 case BuiltinType::Long:
803 case BuiltinType::LongLong:
804 case BuiltinType::Int128:
805 case BuiltinType::Float:
806 case BuiltinType::Double:
807 case BuiltinType::LongDouble:
808 case BuiltinType::NullPtr:
809 case BuiltinType::Overload:
810 case BuiltinType::Dependent:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000811 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000812
813 case BuiltinType::UndeducedAuto: // FIXME: Deserves a cursor?
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000814 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000815
Ted Kremenekc4174cc2010-02-18 18:52:18 +0000816 case BuiltinType::ObjCId:
817 VisitType = Context.getObjCIdType();
818 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000819
820 case BuiltinType::ObjCClass:
821 VisitType = Context.getObjCClassType();
822 break;
823
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000824 case BuiltinType::ObjCSel:
825 VisitType = Context.getObjCSelType();
826 break;
827 }
828
829 if (!VisitType.isNull()) {
830 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000831 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000832 TU));
833 }
834
835 return false;
836}
837
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000838bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
839 return Visit(MakeCursorTypeRef(TL.getTypedefDecl(), TL.getNameLoc(), TU));
840}
841
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000842bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
843 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
844}
845
846bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
847 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
848}
849
850bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
851 if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
852 return true;
853
John McCallc12c5bb2010-05-15 11:32:37 +0000854 return false;
855}
856
857bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
858 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
859 return true;
860
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000861 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
862 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
863 TU)))
864 return true;
865 }
866
867 return false;
868}
869
870bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
John McCallc12c5bb2010-05-15 11:32:37 +0000871 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000872}
873
874bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
875 return Visit(TL.getPointeeLoc());
876}
877
878bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
879 return Visit(TL.getPointeeLoc());
880}
881
882bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
883 return Visit(TL.getPointeeLoc());
884}
885
886bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000887 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000888}
889
890bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000891 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000892}
893
894bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
895 if (Visit(TL.getResultLoc()))
896 return true;
897
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000898 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
Ted Kremenek5dbacb42010-04-07 00:27:13 +0000899 if (Decl *D = TL.getArg(I))
900 if (Visit(MakeCXCursor(D, TU)))
901 return true;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000902
903 return false;
904}
905
906bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
907 if (Visit(TL.getElementLoc()))
908 return true;
909
910 if (Expr *Size = TL.getSizeExpr())
911 return Visit(MakeCXCursor(Size, StmtParent, TU));
912
913 return false;
914}
915
Douglas Gregor2332c112010-01-21 20:48:56 +0000916bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
917 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
918}
919
920bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
921 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
922 return Visit(TSInfo->getTypeLoc());
923
924 return false;
925}
926
Douglas Gregora59e3902010-01-21 23:27:09 +0000927bool CursorVisitor::VisitStmt(Stmt *S) {
928 for (Stmt::child_iterator Child = S->child_begin(), ChildEnd = S->child_end();
929 Child != ChildEnd; ++Child) {
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000930 if (Stmt *C = *Child)
931 if (Visit(MakeCXCursor(C, StmtParent, TU)))
932 return true;
Douglas Gregora59e3902010-01-21 23:27:09 +0000933 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000934
Douglas Gregora59e3902010-01-21 23:27:09 +0000935 return false;
936}
937
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000938bool CursorVisitor::VisitCaseStmt(CaseStmt *S) {
939 // Specially handle CaseStmts because they can be nested, e.g.:
940 //
941 // case 1:
942 // case 2:
943 //
944 // In this case the second CaseStmt is the child of the first. Walking
945 // these recursively can blow out the stack.
946 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU);
947 while (true) {
948 // Set the Parent field to Cursor, then back to its old value once we're
949 // done.
950 SetParentRAII SetParent(Parent, StmtParent, Cursor);
951
952 if (Stmt *LHS = S->getLHS())
953 if (Visit(MakeCXCursor(LHS, StmtParent, TU)))
954 return true;
955 if (Stmt *RHS = S->getRHS())
956 if (Visit(MakeCXCursor(RHS, StmtParent, TU)))
957 return true;
958 if (Stmt *SubStmt = S->getSubStmt()) {
959 if (!isa<CaseStmt>(SubStmt))
960 return Visit(MakeCXCursor(SubStmt, StmtParent, TU));
961
962 // Specially handle 'CaseStmt' so that we don't blow out the stack.
963 CaseStmt *CS = cast<CaseStmt>(SubStmt);
964 Cursor = MakeCXCursor(CS, StmtParent, TU);
965 if (RegionOfInterest.isValid()) {
966 SourceRange Range = CS->getSourceRange();
967 if (Range.isInvalid() || CompareRegionOfInterest(Range))
968 return false;
969 }
970
971 switch (Visitor(Cursor, Parent, ClientData)) {
972 case CXChildVisit_Break: return true;
973 case CXChildVisit_Continue: return false;
974 case CXChildVisit_Recurse:
975 // Perform tail-recursion manually.
976 S = CS;
977 continue;
978 }
979 }
980 return false;
981 }
982}
983
Douglas Gregora59e3902010-01-21 23:27:09 +0000984bool CursorVisitor::VisitDeclStmt(DeclStmt *S) {
985 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
986 D != DEnd; ++D) {
Douglas Gregor263b47b2010-01-25 16:12:32 +0000987 if (*D && Visit(MakeCXCursor(*D, TU)))
Douglas Gregora59e3902010-01-21 23:27:09 +0000988 return true;
989 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000990
Douglas Gregora59e3902010-01-21 23:27:09 +0000991 return false;
992}
993
Douglas Gregorf5bab412010-01-22 01:00:11 +0000994bool CursorVisitor::VisitIfStmt(IfStmt *S) {
995 if (VarDecl *Var = S->getConditionVariable()) {
996 if (Visit(MakeCXCursor(Var, TU)))
997 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000998 }
999
Douglas Gregor263b47b2010-01-25 16:12:32 +00001000 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1001 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +00001002 if (S->getThen() && Visit(MakeCXCursor(S->getThen(), StmtParent, TU)))
1003 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +00001004 if (S->getElse() && Visit(MakeCXCursor(S->getElse(), StmtParent, TU)))
1005 return true;
1006
1007 return false;
1008}
1009
1010bool CursorVisitor::VisitSwitchStmt(SwitchStmt *S) {
1011 if (VarDecl *Var = S->getConditionVariable()) {
1012 if (Visit(MakeCXCursor(Var, TU)))
1013 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001014 }
1015
Douglas Gregor263b47b2010-01-25 16:12:32 +00001016 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1017 return true;
1018 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
1019 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001020
Douglas Gregor263b47b2010-01-25 16:12:32 +00001021 return false;
1022}
1023
1024bool CursorVisitor::VisitWhileStmt(WhileStmt *S) {
1025 if (VarDecl *Var = S->getConditionVariable()) {
1026 if (Visit(MakeCXCursor(Var, TU)))
1027 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001028 }
1029
Douglas Gregor263b47b2010-01-25 16:12:32 +00001030 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1031 return true;
1032 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
Douglas Gregorf5bab412010-01-22 01:00:11 +00001033 return true;
1034
Douglas Gregor263b47b2010-01-25 16:12:32 +00001035 return false;
1036}
1037
1038bool CursorVisitor::VisitForStmt(ForStmt *S) {
1039 if (S->getInit() && Visit(MakeCXCursor(S->getInit(), StmtParent, TU)))
1040 return true;
1041 if (VarDecl *Var = S->getConditionVariable()) {
1042 if (Visit(MakeCXCursor(Var, TU)))
1043 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001044 }
1045
Douglas Gregor263b47b2010-01-25 16:12:32 +00001046 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1047 return true;
1048 if (S->getInc() && Visit(MakeCXCursor(S->getInc(), StmtParent, TU)))
1049 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +00001050 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
1051 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001052
Douglas Gregorf5bab412010-01-22 01:00:11 +00001053 return false;
1054}
1055
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00001056bool CursorVisitor::VisitBlockExpr(BlockExpr *B) {
1057 return Visit(B->getBlockDecl());
1058}
1059
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001060bool CursorVisitor::VisitOffsetOfExpr(OffsetOfExpr *E) {
1061 // FIXME: Visit fields as well?
1062 if (Visit(E->getTypeSourceInfo()->getTypeLoc()))
1063 return true;
1064
1065 return VisitExpr(E);
1066}
1067
Douglas Gregor336fd812010-01-23 00:40:08 +00001068bool CursorVisitor::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E) {
1069 if (E->isArgumentType()) {
1070 if (TypeSourceInfo *TSInfo = E->getArgumentTypeInfo())
1071 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001072
Douglas Gregor336fd812010-01-23 00:40:08 +00001073 return false;
1074 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001075
Douglas Gregor336fd812010-01-23 00:40:08 +00001076 return VisitExpr(E);
1077}
1078
1079bool CursorVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
1080 if (TypeSourceInfo *TSInfo = E->getTypeInfoAsWritten())
1081 if (Visit(TSInfo->getTypeLoc()))
1082 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001083
Douglas Gregor336fd812010-01-23 00:40:08 +00001084 return VisitCastExpr(E);
1085}
1086
1087bool CursorVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
1088 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
1089 if (Visit(TSInfo->getTypeLoc()))
1090 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001091
Douglas Gregor336fd812010-01-23 00:40:08 +00001092 return VisitExpr(E);
1093}
1094
Douglas Gregorc2350e52010-03-08 16:40:19 +00001095bool CursorVisitor::VisitObjCMessageExpr(ObjCMessageExpr *E) {
Douglas Gregor04badcf2010-04-21 00:45:42 +00001096 if (TypeSourceInfo *TSInfo = E->getClassReceiverTypeInfo())
1097 if (Visit(TSInfo->getTypeLoc()))
1098 return true;
Douglas Gregorc2350e52010-03-08 16:40:19 +00001099
1100 return VisitExpr(E);
1101}
1102
Douglas Gregor81d34662010-04-20 15:39:42 +00001103bool CursorVisitor::VisitObjCEncodeExpr(ObjCEncodeExpr *E) {
1104 return Visit(E->getEncodedTypeSourceInfo()->getTypeLoc());
1105}
1106
1107
Ted Kremenek09dfa372010-02-18 05:46:33 +00001108bool CursorVisitor::VisitAttributes(Decl *D) {
1109 for (const Attr *A = D->getAttrs(); A; A = A->getNext())
1110 if (Visit(MakeCXCursor(A, D, TU)))
1111 return true;
1112
1113 return false;
1114}
1115
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00001116extern "C" {
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001117CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
1118 int displayDiagnostics) {
Douglas Gregora030b7c2010-01-22 20:35:53 +00001119 CIndexer *CIdxr = new CIndexer();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001120 if (excludeDeclarationsFromPCH)
1121 CIdxr->setOnlyLocalDecls();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001122 if (displayDiagnostics)
1123 CIdxr->setDisplayDiagnostics();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001124 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +00001125}
1126
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001127void clang_disposeIndex(CXIndex CIdx) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001128 if (CIdx)
1129 delete static_cast<CIndexer *>(CIdx);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00001130}
1131
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001132void clang_setUseExternalASTGeneration(CXIndex CIdx, int value) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001133 if (CIdx) {
1134 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
1135 CXXIdx->setUseExternalASTGeneration(value);
1136 }
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001137}
1138
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001139CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
Douglas Gregora88084b2010-02-18 18:08:43 +00001140 const char *ast_filename) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001141 if (!CIdx)
1142 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001143
Douglas Gregor7d1d49d2009-10-16 20:01:17 +00001144 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001145
Douglas Gregor28019772010-04-05 23:52:57 +00001146 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
1147 return ASTUnit::LoadFromPCHFile(ast_filename, Diags,
Douglas Gregora88084b2010-02-18 18:08:43 +00001148 CXXIdx->getOnlyLocalDecls(),
1149 0, 0, true);
Steve Naroff600866c2009-08-27 19:51:58 +00001150}
1151
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001152CXTranslationUnit
1153clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
1154 const char *source_filename,
1155 int num_command_line_args,
Douglas Gregor4db64a42010-01-23 00:14:00 +00001156 const char **command_line_args,
1157 unsigned num_unsaved_files,
Douglas Gregora88084b2010-02-18 18:08:43 +00001158 struct CXUnsavedFile *unsaved_files) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001159 if (!CIdx)
1160 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001161
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001162 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
1163
Douglas Gregor5352ac02010-01-28 00:27:43 +00001164 // Configure the diagnostics.
1165 DiagnosticOptions DiagOpts;
Douglas Gregor28019772010-04-05 23:52:57 +00001166 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
1167 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001168
Douglas Gregor4db64a42010-01-23 00:14:00 +00001169 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
1170 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattnera0a270c2010-04-05 22:42:27 +00001171 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001172 const llvm::MemoryBuffer *Buffer
Chris Lattnera0a270c2010-04-05 22:42:27 +00001173 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregor4db64a42010-01-23 00:14:00 +00001174 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
1175 Buffer));
1176 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001177
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001178 if (!CXXIdx->getUseExternalASTGeneration()) {
1179 llvm::SmallVector<const char *, 16> Args;
1180
1181 // The 'source_filename' argument is optional. If the caller does not
1182 // specify it then it is assumed that the source file is specified
1183 // in the actual argument list.
1184 if (source_filename)
1185 Args.push_back(source_filename);
1186 Args.insert(Args.end(), command_line_args,
1187 command_line_args + num_command_line_args);
Douglas Gregor94dc8f62010-03-19 16:15:56 +00001188 Args.push_back("-Xclang");
1189 Args.push_back("-detailed-preprocessing-record");
Douglas Gregor5352ac02010-01-28 00:27:43 +00001190 unsigned NumErrors = Diags->getNumErrors();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001191
Ted Kremenek29b72842010-01-07 22:49:05 +00001192#ifdef USE_CRASHTRACER
1193 ArgsCrashTracerInfo ACTI(Args);
Ted Kremenek8a8da7d2010-01-06 03:42:32 +00001194#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001195
Daniel Dunbar94220972009-12-05 02:17:18 +00001196 llvm::OwningPtr<ASTUnit> Unit(
1197 ASTUnit::LoadFromCommandLine(Args.data(), Args.data() + Args.size(),
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001198 Diags,
Daniel Dunbar869824e2009-12-13 03:46:13 +00001199 CXXIdx->getClangResourcesPath(),
Daniel Dunbar94220972009-12-05 02:17:18 +00001200 CXXIdx->getOnlyLocalDecls(),
Douglas Gregor4db64a42010-01-23 00:14:00 +00001201 RemappedFiles.data(),
Douglas Gregora88084b2010-02-18 18:08:43 +00001202 RemappedFiles.size(),
Douglas Gregor94dc8f62010-03-19 16:15:56 +00001203 /*CaptureDiagnostics=*/true));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001204
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001205 if (NumErrors != Diags->getNumErrors()) {
Ted Kremenek34f6a322010-03-05 22:43:29 +00001206 // Make sure to check that 'Unit' is non-NULL.
1207 if (CXXIdx->getDisplayDiagnostics() && Unit.get()) {
Douglas Gregor405634b2010-04-05 18:10:21 +00001208 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
1209 DEnd = Unit->stored_diag_end();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001210 D != DEnd; ++D) {
1211 CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOptions());
Douglas Gregor274f1902010-02-22 23:17:23 +00001212 CXString Msg = clang_formatDiagnostic(&Diag,
1213 clang_defaultDiagnosticDisplayOptions());
1214 fprintf(stderr, "%s\n", clang_getCString(Msg));
1215 clang_disposeString(Msg);
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001216 }
Douglas Gregor274f1902010-02-22 23:17:23 +00001217#ifdef LLVM_ON_WIN32
1218 // On Windows, force a flush, since there may be multiple copies of
1219 // stderr and stdout in the file system, all with different buffers
1220 // but writing to the same device.
1221 fflush(stderr);
Ted Kremenek83c51842010-03-26 01:34:51 +00001222#endif
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001223 }
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001224 }
Daniel Dunbar94220972009-12-05 02:17:18 +00001225
1226 return Unit.take();
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001227 }
1228
Ted Kremenek139ba862009-10-22 00:03:57 +00001229 // Build up the arguments for invoking 'clang'.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001230 std::vector<const char *> argv;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001231
Ted Kremenek139ba862009-10-22 00:03:57 +00001232 // First add the complete path to the 'clang' executable.
1233 llvm::sys::Path ClangPath = static_cast<CIndexer *>(CIdx)->getClangPath();
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00001234 argv.push_back(ClangPath.c_str());
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001235
Ted Kremenek139ba862009-10-22 00:03:57 +00001236 // Add the '-emit-ast' option as our execution mode for 'clang'.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001237 argv.push_back("-emit-ast");
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001238
Ted Kremenek139ba862009-10-22 00:03:57 +00001239 // The 'source_filename' argument is optional. If the caller does not
1240 // specify it then it is assumed that the source file is specified
1241 // in the actual argument list.
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001242 if (source_filename)
1243 argv.push_back(source_filename);
Ted Kremenek139ba862009-10-22 00:03:57 +00001244
Steve Naroff37b5ac22009-10-15 20:50:09 +00001245 // Generate a temporary name for the AST file.
Ted Kremenek139ba862009-10-22 00:03:57 +00001246 argv.push_back("-o");
Benjamin Kramerc2a98162010-03-13 21:22:49 +00001247 char astTmpFile[L_tmpnam];
1248 argv.push_back(tmpnam(astTmpFile));
Ted Kremenek139ba862009-10-22 00:03:57 +00001249
Douglas Gregor4db64a42010-01-23 00:14:00 +00001250 // Remap any unsaved files to temporary files.
1251 std::vector<llvm::sys::Path> TemporaryFiles;
1252 std::vector<std::string> RemapArgs;
1253 if (RemapFiles(num_unsaved_files, unsaved_files, RemapArgs, TemporaryFiles))
1254 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001255
Douglas Gregor4db64a42010-01-23 00:14:00 +00001256 // The pointers into the elements of RemapArgs are stable because we
1257 // won't be adding anything to RemapArgs after this point.
1258 for (unsigned i = 0, e = RemapArgs.size(); i != e; ++i)
1259 argv.push_back(RemapArgs[i].c_str());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001260
Ted Kremenek139ba862009-10-22 00:03:57 +00001261 // Process the compiler options, stripping off '-o', '-c', '-fsyntax-only'.
1262 for (int i = 0; i < num_command_line_args; ++i)
1263 if (const char *arg = command_line_args[i]) {
1264 if (strcmp(arg, "-o") == 0) {
1265 ++i; // Also skip the matching argument.
1266 continue;
1267 }
1268 if (strcmp(arg, "-emit-ast") == 0 ||
1269 strcmp(arg, "-c") == 0 ||
1270 strcmp(arg, "-fsyntax-only") == 0) {
1271 continue;
1272 }
1273
1274 // Keep the argument.
1275 argv.push_back(arg);
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001276 }
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001277
Douglas Gregord93256e2010-01-28 06:00:51 +00001278 // Generate a temporary name for the diagnostics file.
Benjamin Kramerc2a98162010-03-13 21:22:49 +00001279 char tmpFileResults[L_tmpnam];
1280 char *tmpResultsFileName = tmpnam(tmpFileResults);
1281 llvm::sys::Path DiagnosticsFile(tmpResultsFileName);
Douglas Gregord93256e2010-01-28 06:00:51 +00001282 TemporaryFiles.push_back(DiagnosticsFile);
1283 argv.push_back("-fdiagnostics-binary");
1284
Douglas Gregor94dc8f62010-03-19 16:15:56 +00001285 argv.push_back("-Xclang");
1286 argv.push_back("-detailed-preprocessing-record");
1287
Ted Kremenek139ba862009-10-22 00:03:57 +00001288 // Add the null terminator.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001289 argv.push_back(NULL);
1290
Ted Kremenekfeb15e32009-10-26 22:14:08 +00001291 // Invoke 'clang'.
1292 llvm::sys::Path DevNull; // leave empty, causes redirection to /dev/null
1293 // on Unix or NUL (Windows).
Ted Kremenek379afec2009-10-22 03:24:01 +00001294 std::string ErrMsg;
Douglas Gregord93256e2010-01-28 06:00:51 +00001295 const llvm::sys::Path *Redirects[] = { &DevNull, &DevNull, &DiagnosticsFile,
1296 NULL };
Ted Kremenek379afec2009-10-22 03:24:01 +00001297 llvm::sys::Program::ExecuteAndWait(ClangPath, &argv[0], /* env */ NULL,
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001298 /* redirects */ &Redirects[0],
Ted Kremenek379afec2009-10-22 03:24:01 +00001299 /* secondsToWait */ 0, /* memoryLimits */ 0, &ErrMsg);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001300
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001301 if (!ErrMsg.empty()) {
1302 std::string AllArgs;
Ted Kremenek379afec2009-10-22 03:24:01 +00001303 for (std::vector<const char*>::iterator I = argv.begin(), E = argv.end();
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001304 I != E; ++I) {
1305 AllArgs += ' ';
Ted Kremenek779e5f42009-10-26 22:08:39 +00001306 if (*I)
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001307 AllArgs += *I;
Ted Kremenek779e5f42009-10-26 22:08:39 +00001308 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001309
Daniel Dunbar32141c82010-02-23 20:23:45 +00001310 Diags->Report(diag::err_fe_invoking) << AllArgs << ErrMsg;
Ted Kremenek379afec2009-10-22 03:24:01 +00001311 }
Benjamin Kramer0829a832009-10-18 11:19:36 +00001312
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001313 ASTUnit *ATU = ASTUnit::LoadFromPCHFile(astTmpFile, Diags,
Douglas Gregor4db64a42010-01-23 00:14:00 +00001314 CXXIdx->getOnlyLocalDecls(),
Douglas Gregor4db64a42010-01-23 00:14:00 +00001315 RemappedFiles.data(),
Douglas Gregora88084b2010-02-18 18:08:43 +00001316 RemappedFiles.size(),
1317 /*CaptureDiagnostics=*/true);
Douglas Gregora88084b2010-02-18 18:08:43 +00001318 if (ATU) {
1319 LoadSerializedDiagnostics(DiagnosticsFile,
1320 num_unsaved_files, unsaved_files,
1321 ATU->getFileManager(),
1322 ATU->getSourceManager(),
Douglas Gregor405634b2010-04-05 18:10:21 +00001323 ATU->getStoredDiagnostics());
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001324 } else if (CXXIdx->getDisplayDiagnostics()) {
1325 // We failed to load the ASTUnit, but we can still deserialize the
1326 // diagnostics and emit them.
1327 FileManager FileMgr;
Douglas Gregorf715ca12010-03-16 00:06:06 +00001328 Diagnostic Diag;
1329 SourceManager SourceMgr(Diag);
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001330 // FIXME: Faked LangOpts!
1331 LangOptions LangOpts;
1332 llvm::SmallVector<StoredDiagnostic, 4> Diags;
1333 LoadSerializedDiagnostics(DiagnosticsFile,
1334 num_unsaved_files, unsaved_files,
1335 FileMgr, SourceMgr, Diags);
1336 for (llvm::SmallVector<StoredDiagnostic, 4>::iterator D = Diags.begin(),
1337 DEnd = Diags.end();
1338 D != DEnd; ++D) {
1339 CXStoredDiagnostic Diag(*D, LangOpts);
Douglas Gregor274f1902010-02-22 23:17:23 +00001340 CXString Msg = clang_formatDiagnostic(&Diag,
1341 clang_defaultDiagnosticDisplayOptions());
1342 fprintf(stderr, "%s\n", clang_getCString(Msg));
1343 clang_disposeString(Msg);
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001344 }
Douglas Gregor274f1902010-02-22 23:17:23 +00001345
1346#ifdef LLVM_ON_WIN32
1347 // On Windows, force a flush, since there may be multiple copies of
1348 // stderr and stdout in the file system, all with different buffers
1349 // but writing to the same device.
1350 fflush(stderr);
1351#endif
Douglas Gregora88084b2010-02-18 18:08:43 +00001352 }
Douglas Gregord93256e2010-01-28 06:00:51 +00001353
Douglas Gregor313e26c2010-02-18 23:35:40 +00001354 if (ATU) {
1355 // Make the translation unit responsible for destroying all temporary files.
1356 for (unsigned i = 0, e = TemporaryFiles.size(); i != e; ++i)
1357 ATU->addTemporaryFile(TemporaryFiles[i]);
1358 ATU->addTemporaryFile(llvm::sys::Path(ATU->getPCHFileName()));
1359 } else {
1360 // Destroy all of the temporary files now; they can't be referenced any
1361 // longer.
1362 llvm::sys::Path(astTmpFile).eraseFromDisk();
1363 for (unsigned i = 0, e = TemporaryFiles.size(); i != e; ++i)
1364 TemporaryFiles[i].eraseFromDisk();
1365 }
1366
Steve Naroffe19944c2009-10-15 22:23:48 +00001367 return ATU;
Steve Naroff5b7d8e22009-10-15 20:04:39 +00001368}
1369
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001370void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001371 if (CTUnit)
1372 delete static_cast<ASTUnit *>(CTUnit);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00001373}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001374
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001375CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001376 if (!CTUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001377 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001378
Steve Naroff77accc12009-09-03 18:19:54 +00001379 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001380 return createCXString(CXXUnit->getOriginalSourceFileName(), true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +00001381}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +00001382
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001383CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001384 CXCursor Result = { CXCursor_TranslationUnit, { 0, 0, TU } };
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001385 return Result;
1386}
1387
Ted Kremenekfb480492010-01-13 21:46:36 +00001388} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +00001389
Ted Kremenekfb480492010-01-13 21:46:36 +00001390//===----------------------------------------------------------------------===//
Douglas Gregor1db19de2010-01-19 21:36:55 +00001391// CXSourceLocation and CXSourceRange Operations.
1392//===----------------------------------------------------------------------===//
1393
Douglas Gregorb9790342010-01-22 21:44:22 +00001394extern "C" {
1395CXSourceLocation clang_getNullLocation() {
Douglas Gregor5352ac02010-01-28 00:27:43 +00001396 CXSourceLocation Result = { { 0, 0 }, 0 };
Douglas Gregorb9790342010-01-22 21:44:22 +00001397 return Result;
1398}
1399
1400unsigned clang_equalLocations(CXSourceLocation loc1, CXSourceLocation loc2) {
Daniel Dunbar90a6b9e2010-01-30 23:58:27 +00001401 return (loc1.ptr_data[0] == loc2.ptr_data[0] &&
1402 loc1.ptr_data[1] == loc2.ptr_data[1] &&
1403 loc1.int_data == loc2.int_data);
Douglas Gregorb9790342010-01-22 21:44:22 +00001404}
1405
1406CXSourceLocation clang_getLocation(CXTranslationUnit tu,
1407 CXFile file,
1408 unsigned line,
1409 unsigned column) {
Douglas Gregor42748ec2010-04-30 19:45:53 +00001410 if (!tu || !file)
Douglas Gregorb9790342010-01-22 21:44:22 +00001411 return clang_getNullLocation();
Douglas Gregor42748ec2010-04-30 19:45:53 +00001412
Douglas Gregorb9790342010-01-22 21:44:22 +00001413 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
1414 SourceLocation SLoc
1415 = CXXUnit->getSourceManager().getLocation(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001416 static_cast<const FileEntry *>(file),
Douglas Gregorb9790342010-01-22 21:44:22 +00001417 line, column);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001418
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00001419 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
Douglas Gregorb9790342010-01-22 21:44:22 +00001420}
1421
Douglas Gregor5352ac02010-01-28 00:27:43 +00001422CXSourceRange clang_getNullRange() {
1423 CXSourceRange Result = { { 0, 0 }, 0, 0 };
1424 return Result;
1425}
Daniel Dunbard52864b2010-02-14 10:02:57 +00001426
Douglas Gregor5352ac02010-01-28 00:27:43 +00001427CXSourceRange clang_getRange(CXSourceLocation begin, CXSourceLocation end) {
1428 if (begin.ptr_data[0] != end.ptr_data[0] ||
1429 begin.ptr_data[1] != end.ptr_data[1])
1430 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001431
1432 CXSourceRange Result = { { begin.ptr_data[0], begin.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00001433 begin.int_data, end.int_data };
Douglas Gregorb9790342010-01-22 21:44:22 +00001434 return Result;
1435}
1436
Douglas Gregor46766dc2010-01-26 19:19:08 +00001437void clang_getInstantiationLocation(CXSourceLocation location,
1438 CXFile *file,
1439 unsigned *line,
1440 unsigned *column,
1441 unsigned *offset) {
Douglas Gregor1db19de2010-01-19 21:36:55 +00001442 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
1443
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00001444 if (!location.ptr_data[0] || Loc.isInvalid()) {
Douglas Gregor46766dc2010-01-26 19:19:08 +00001445 if (file)
1446 *file = 0;
1447 if (line)
1448 *line = 0;
1449 if (column)
1450 *column = 0;
1451 if (offset)
1452 *offset = 0;
1453 return;
1454 }
1455
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00001456 const SourceManager &SM =
1457 *static_cast<const SourceManager*>(location.ptr_data[0]);
Douglas Gregor1db19de2010-01-19 21:36:55 +00001458 SourceLocation InstLoc = SM.getInstantiationLoc(Loc);
Douglas Gregor1db19de2010-01-19 21:36:55 +00001459
1460 if (file)
1461 *file = (void *)SM.getFileEntryForID(SM.getFileID(InstLoc));
1462 if (line)
1463 *line = SM.getInstantiationLineNumber(InstLoc);
1464 if (column)
1465 *column = SM.getInstantiationColumnNumber(InstLoc);
Douglas Gregore69517c2010-01-26 03:07:15 +00001466 if (offset)
Douglas Gregor46766dc2010-01-26 19:19:08 +00001467 *offset = SM.getDecomposedLoc(InstLoc).second;
Douglas Gregore69517c2010-01-26 03:07:15 +00001468}
1469
Douglas Gregor1db19de2010-01-19 21:36:55 +00001470CXSourceLocation clang_getRangeStart(CXSourceRange range) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001471 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00001472 range.begin_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00001473 return Result;
1474}
1475
1476CXSourceLocation clang_getRangeEnd(CXSourceRange range) {
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00001477 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00001478 range.end_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00001479 return Result;
1480}
1481
Douglas Gregorb9790342010-01-22 21:44:22 +00001482} // end: extern "C"
1483
Douglas Gregor1db19de2010-01-19 21:36:55 +00001484//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00001485// CXFile Operations.
1486//===----------------------------------------------------------------------===//
1487
1488extern "C" {
Ted Kremenek74844072010-02-17 00:41:20 +00001489CXString clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00001490 if (!SFile)
Ted Kremenek74844072010-02-17 00:41:20 +00001491 return createCXString(NULL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001492
Steve Naroff88145032009-10-27 14:35:18 +00001493 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Ted Kremenek74844072010-02-17 00:41:20 +00001494 return createCXString(FEnt->getName());
Steve Naroff88145032009-10-27 14:35:18 +00001495}
1496
1497time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00001498 if (!SFile)
1499 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001500
Steve Naroff88145032009-10-27 14:35:18 +00001501 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
1502 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +00001503}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001504
Douglas Gregorb9790342010-01-22 21:44:22 +00001505CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
1506 if (!tu)
1507 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001508
Douglas Gregorb9790342010-01-22 21:44:22 +00001509 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001510
Douglas Gregorb9790342010-01-22 21:44:22 +00001511 FileManager &FMgr = CXXUnit->getFileManager();
1512 const FileEntry *File = FMgr.getFile(file_name, file_name+strlen(file_name));
1513 return const_cast<FileEntry *>(File);
1514}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001515
Ted Kremenekfb480492010-01-13 21:46:36 +00001516} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +00001517
Ted Kremenekfb480492010-01-13 21:46:36 +00001518//===----------------------------------------------------------------------===//
1519// CXCursor Operations.
1520//===----------------------------------------------------------------------===//
1521
Ted Kremenekfb480492010-01-13 21:46:36 +00001522static Decl *getDeclFromExpr(Stmt *E) {
1523 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
1524 return RefExpr->getDecl();
1525 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
1526 return ME->getMemberDecl();
1527 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
1528 return RE->getDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001529
Ted Kremenekfb480492010-01-13 21:46:36 +00001530 if (CallExpr *CE = dyn_cast<CallExpr>(E))
1531 return getDeclFromExpr(CE->getCallee());
1532 if (CastExpr *CE = dyn_cast<CastExpr>(E))
1533 return getDeclFromExpr(CE->getSubExpr());
1534 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
1535 return OME->getMethodDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001536
Ted Kremenekfb480492010-01-13 21:46:36 +00001537 return 0;
1538}
1539
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00001540static SourceLocation getLocationFromExpr(Expr *E) {
1541 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
1542 return /*FIXME:*/Msg->getLeftLoc();
1543 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
1544 return DRE->getLocation();
1545 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
1546 return Member->getMemberLoc();
1547 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
1548 return Ivar->getLocation();
1549 return E->getLocStart();
1550}
1551
Ted Kremenekfb480492010-01-13 21:46:36 +00001552extern "C" {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001553
1554unsigned clang_visitChildren(CXCursor parent,
Douglas Gregorb1373d02010-01-20 20:59:29 +00001555 CXCursorVisitor visitor,
1556 CXClientData client_data) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001557 ASTUnit *CXXUnit = getCursorASTUnit(parent);
Douglas Gregorb1373d02010-01-20 20:59:29 +00001558
1559 unsigned PCHLevel = Decl::MaxPCHLevel;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001560
Douglas Gregorb1373d02010-01-20 20:59:29 +00001561 // Set the PCHLevel to filter out unwanted decls if requested.
1562 if (CXXUnit->getOnlyLocalDecls()) {
1563 PCHLevel = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001564
Douglas Gregorb1373d02010-01-20 20:59:29 +00001565 // If the main input was an AST, bump the level.
1566 if (CXXUnit->isMainFileAST())
1567 ++PCHLevel;
1568 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001569
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001570 CursorVisitor CursorVis(CXXUnit, visitor, client_data, PCHLevel);
Douglas Gregorb1373d02010-01-20 20:59:29 +00001571 return CursorVis.VisitChildren(parent);
1572}
1573
Douglas Gregor78205d42010-01-20 21:45:58 +00001574static CXString getDeclSpelling(Decl *D) {
1575 NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
1576 if (!ND)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001577 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001578
Douglas Gregor78205d42010-01-20 21:45:58 +00001579 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001580 return createCXString(OMD->getSelector().getAsString());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001581
Douglas Gregor78205d42010-01-20 21:45:58 +00001582 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
1583 // No, this isn't the same as the code below. getIdentifier() is non-virtual
1584 // and returns different names. NamedDecl returns the class name and
1585 // ObjCCategoryImplDecl returns the category name.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001586 return createCXString(CIMP->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001587
Douglas Gregor78205d42010-01-20 21:45:58 +00001588 if (ND->getIdentifier())
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001589 return createCXString(ND->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001590
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001591 return createCXString("");
Douglas Gregor78205d42010-01-20 21:45:58 +00001592}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001593
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001594CXString clang_getCursorSpelling(CXCursor C) {
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001595 if (clang_isTranslationUnit(C.kind))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001596 return clang_getTranslationUnitSpelling(C.data[2]);
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001597
Steve Narofff334b4e2009-09-02 18:26:48 +00001598 if (clang_isReference(C.kind)) {
1599 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00001600 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +00001601 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001602 return createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00001603 }
1604 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +00001605 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001606 return createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00001607 }
1608 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +00001609 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +00001610 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001611 return createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00001612 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001613 case CXCursor_TypeRef: {
1614 TypeDecl *Type = getCursorTypeRef(C).first;
1615 assert(Type && "Missing type decl");
1616
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001617 return createCXString(getCursorContext(C).getTypeDeclType(Type).
1618 getAsString());
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001619 }
1620
Daniel Dunbaracca7252009-11-30 20:42:49 +00001621 default:
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001622 return createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +00001623 }
1624 }
Douglas Gregor97b98722010-01-19 23:20:36 +00001625
1626 if (clang_isExpression(C.kind)) {
1627 Decl *D = getDeclFromExpr(getCursorExpr(C));
1628 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +00001629 return getDeclSpelling(D);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001630 return createCXString("");
Douglas Gregor97b98722010-01-19 23:20:36 +00001631 }
1632
Douglas Gregor4ae8f292010-03-18 17:52:52 +00001633 if (C.kind == CXCursor_MacroInstantiation)
1634 return createCXString(getCursorMacroInstantiation(C)->getName()
1635 ->getNameStart());
1636
Douglas Gregor572feb22010-03-18 18:04:21 +00001637 if (C.kind == CXCursor_MacroDefinition)
1638 return createCXString(getCursorMacroDefinition(C)->getName()
1639 ->getNameStart());
1640
Douglas Gregor60cbfac2010-01-25 16:56:17 +00001641 if (clang_isDeclaration(C.kind))
1642 return getDeclSpelling(getCursorDecl(C));
Ted Kremeneke68fff62010-02-17 00:41:32 +00001643
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001644 return createCXString("");
Steve Narofff334b4e2009-09-02 18:26:48 +00001645}
1646
Ted Kremeneke68fff62010-02-17 00:41:32 +00001647CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00001648 switch (Kind) {
Ted Kremeneke68fff62010-02-17 00:41:32 +00001649 case CXCursor_FunctionDecl:
1650 return createCXString("FunctionDecl");
1651 case CXCursor_TypedefDecl:
1652 return createCXString("TypedefDecl");
1653 case CXCursor_EnumDecl:
1654 return createCXString("EnumDecl");
1655 case CXCursor_EnumConstantDecl:
1656 return createCXString("EnumConstantDecl");
1657 case CXCursor_StructDecl:
1658 return createCXString("StructDecl");
1659 case CXCursor_UnionDecl:
1660 return createCXString("UnionDecl");
1661 case CXCursor_ClassDecl:
1662 return createCXString("ClassDecl");
1663 case CXCursor_FieldDecl:
1664 return createCXString("FieldDecl");
1665 case CXCursor_VarDecl:
1666 return createCXString("VarDecl");
1667 case CXCursor_ParmDecl:
1668 return createCXString("ParmDecl");
1669 case CXCursor_ObjCInterfaceDecl:
1670 return createCXString("ObjCInterfaceDecl");
1671 case CXCursor_ObjCCategoryDecl:
1672 return createCXString("ObjCCategoryDecl");
1673 case CXCursor_ObjCProtocolDecl:
1674 return createCXString("ObjCProtocolDecl");
1675 case CXCursor_ObjCPropertyDecl:
1676 return createCXString("ObjCPropertyDecl");
1677 case CXCursor_ObjCIvarDecl:
1678 return createCXString("ObjCIvarDecl");
1679 case CXCursor_ObjCInstanceMethodDecl:
1680 return createCXString("ObjCInstanceMethodDecl");
1681 case CXCursor_ObjCClassMethodDecl:
1682 return createCXString("ObjCClassMethodDecl");
1683 case CXCursor_ObjCImplementationDecl:
1684 return createCXString("ObjCImplementationDecl");
1685 case CXCursor_ObjCCategoryImplDecl:
1686 return createCXString("ObjCCategoryImplDecl");
Ted Kremenek8bd5a692010-04-13 23:39:06 +00001687 case CXCursor_CXXMethod:
1688 return createCXString("CXXMethod");
Ted Kremeneke68fff62010-02-17 00:41:32 +00001689 case CXCursor_UnexposedDecl:
1690 return createCXString("UnexposedDecl");
1691 case CXCursor_ObjCSuperClassRef:
1692 return createCXString("ObjCSuperClassRef");
1693 case CXCursor_ObjCProtocolRef:
1694 return createCXString("ObjCProtocolRef");
1695 case CXCursor_ObjCClassRef:
1696 return createCXString("ObjCClassRef");
1697 case CXCursor_TypeRef:
1698 return createCXString("TypeRef");
1699 case CXCursor_UnexposedExpr:
1700 return createCXString("UnexposedExpr");
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00001701 case CXCursor_BlockExpr:
1702 return createCXString("BlockExpr");
Ted Kremeneke68fff62010-02-17 00:41:32 +00001703 case CXCursor_DeclRefExpr:
1704 return createCXString("DeclRefExpr");
1705 case CXCursor_MemberRefExpr:
1706 return createCXString("MemberRefExpr");
1707 case CXCursor_CallExpr:
1708 return createCXString("CallExpr");
1709 case CXCursor_ObjCMessageExpr:
1710 return createCXString("ObjCMessageExpr");
1711 case CXCursor_UnexposedStmt:
1712 return createCXString("UnexposedStmt");
1713 case CXCursor_InvalidFile:
1714 return createCXString("InvalidFile");
Ted Kremenek292db642010-03-19 20:39:05 +00001715 case CXCursor_InvalidCode:
1716 return createCXString("InvalidCode");
Ted Kremeneke68fff62010-02-17 00:41:32 +00001717 case CXCursor_NoDeclFound:
1718 return createCXString("NoDeclFound");
1719 case CXCursor_NotImplemented:
1720 return createCXString("NotImplemented");
1721 case CXCursor_TranslationUnit:
1722 return createCXString("TranslationUnit");
Ted Kremeneke77f4432010-02-18 03:09:07 +00001723 case CXCursor_UnexposedAttr:
1724 return createCXString("UnexposedAttr");
1725 case CXCursor_IBActionAttr:
1726 return createCXString("attribute(ibaction)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00001727 case CXCursor_IBOutletAttr:
1728 return createCXString("attribute(iboutlet)");
Ted Kremenek857e9182010-05-19 17:38:06 +00001729 case CXCursor_IBOutletCollectionAttr:
1730 return createCXString("attribute(iboutletcollection)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00001731 case CXCursor_PreprocessingDirective:
1732 return createCXString("preprocessing directive");
Douglas Gregor572feb22010-03-18 18:04:21 +00001733 case CXCursor_MacroDefinition:
1734 return createCXString("macro definition");
Douglas Gregor48072312010-03-18 15:23:44 +00001735 case CXCursor_MacroInstantiation:
1736 return createCXString("macro instantiation");
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00001737 case CXCursor_Namespace:
1738 return createCXString("Namespace");
Ted Kremeneka0536d82010-05-07 01:04:29 +00001739 case CXCursor_LinkageSpec:
1740 return createCXString("LinkageSpec");
Steve Naroff89922f82009-08-31 00:59:03 +00001741 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00001742
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00001743 llvm_unreachable("Unhandled CXCursorKind");
Ted Kremeneke68fff62010-02-17 00:41:32 +00001744 return createCXString(NULL);
Steve Naroff600866c2009-08-27 19:51:58 +00001745}
Steve Naroff89922f82009-08-31 00:59:03 +00001746
Ted Kremeneke68fff62010-02-17 00:41:32 +00001747enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
1748 CXCursor parent,
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001749 CXClientData client_data) {
1750 CXCursor *BestCursor = static_cast<CXCursor *>(client_data);
1751 *BestCursor = cursor;
1752 return CXChildVisit_Recurse;
1753}
Ted Kremeneke68fff62010-02-17 00:41:32 +00001754
Douglas Gregorb9790342010-01-22 21:44:22 +00001755CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
1756 if (!TU)
Ted Kremenekf4629892010-01-14 01:51:23 +00001757 return clang_getNullCursor();
Ted Kremeneke68fff62010-02-17 00:41:32 +00001758
Douglas Gregorb9790342010-01-22 21:44:22 +00001759 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
1760
Douglas Gregorbdf60622010-03-05 21:16:25 +00001761 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
1762
Ted Kremeneka297de22010-01-25 22:34:44 +00001763 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001764 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
1765 if (SLoc.isValid()) {
Daniel Dunbard52864b2010-02-14 10:02:57 +00001766 SourceRange RegionOfInterest(SLoc, SLoc.getFileLocWithOffset(1));
Ted Kremeneke68fff62010-02-17 00:41:32 +00001767
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001768 // FIXME: Would be great to have a "hint" cursor, then walk from that
1769 // hint cursor upward until we find a cursor whose source range encloses
1770 // the region of interest, rather than starting from the translation unit.
1771 CXCursor Parent = clang_getTranslationUnitCursor(CXXUnit);
Ted Kremeneke68fff62010-02-17 00:41:32 +00001772 CursorVisitor CursorVis(CXXUnit, GetCursorVisitor, &Result,
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001773 Decl::MaxPCHLevel, RegionOfInterest);
1774 CursorVis.VisitChildren(Parent);
Steve Naroff77128dd2009-09-15 20:25:34 +00001775 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00001776 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00001777}
1778
Ted Kremenek73885552009-11-17 19:28:59 +00001779CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00001780 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00001781}
1782
1783unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00001784 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00001785}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001786
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001787unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00001788 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
1789}
1790
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001791unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +00001792 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
1793}
Steve Naroff2d4d6292009-08-31 14:26:51 +00001794
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001795unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00001796 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
1797}
1798
Douglas Gregor97b98722010-01-19 23:20:36 +00001799unsigned clang_isExpression(enum CXCursorKind K) {
1800 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
1801}
1802
1803unsigned clang_isStatement(enum CXCursorKind K) {
1804 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
1805}
1806
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001807unsigned clang_isTranslationUnit(enum CXCursorKind K) {
1808 return K == CXCursor_TranslationUnit;
1809}
1810
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00001811unsigned clang_isPreprocessing(enum CXCursorKind K) {
1812 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
1813}
1814
Ted Kremenekad6eff62010-03-08 21:17:29 +00001815unsigned clang_isUnexposed(enum CXCursorKind K) {
1816 switch (K) {
1817 case CXCursor_UnexposedDecl:
1818 case CXCursor_UnexposedExpr:
1819 case CXCursor_UnexposedStmt:
1820 case CXCursor_UnexposedAttr:
1821 return true;
1822 default:
1823 return false;
1824 }
1825}
1826
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001827CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00001828 return C.kind;
1829}
1830
Douglas Gregor98258af2010-01-18 22:46:11 +00001831CXSourceLocation clang_getCursorLocation(CXCursor C) {
1832 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00001833 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001834 case CXCursor_ObjCSuperClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00001835 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1836 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001837 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001838 }
1839
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001840 case CXCursor_ObjCProtocolRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00001841 std::pair<ObjCProtocolDecl *, SourceLocation> P
1842 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001843 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001844 }
1845
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001846 case CXCursor_ObjCClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00001847 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1848 = getCursorObjCClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001849 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001850 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001851
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001852 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001853 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001854 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001855 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001856
Douglas Gregorf46034a2010-01-18 23:41:10 +00001857 default:
1858 // FIXME: Need a way to enumerate all non-reference cases.
1859 llvm_unreachable("Missed a reference kind");
1860 }
Douglas Gregor98258af2010-01-18 22:46:11 +00001861 }
Douglas Gregor97b98722010-01-19 23:20:36 +00001862
1863 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001864 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00001865 getLocationFromExpr(getCursorExpr(C)));
1866
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00001867 if (C.kind == CXCursor_PreprocessingDirective) {
1868 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
1869 return cxloc::translateSourceLocation(getCursorContext(C), L);
1870 }
Douglas Gregor48072312010-03-18 15:23:44 +00001871
1872 if (C.kind == CXCursor_MacroInstantiation) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00001873 SourceLocation L
1874 = cxcursor::getCursorMacroInstantiation(C)->getSourceRange().getBegin();
Douglas Gregor48072312010-03-18 15:23:44 +00001875 return cxloc::translateSourceLocation(getCursorContext(C), L);
1876 }
Douglas Gregor572feb22010-03-18 18:04:21 +00001877
1878 if (C.kind == CXCursor_MacroDefinition) {
1879 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
1880 return cxloc::translateSourceLocation(getCursorContext(C), L);
1881 }
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00001882
Ted Kremenek9a700d22010-05-12 06:16:13 +00001883 if (C.kind < CXCursor_FirstDecl || C.kind > CXCursor_LastDecl)
Douglas Gregor5352ac02010-01-28 00:27:43 +00001884 return clang_getNullLocation();
Douglas Gregor98258af2010-01-18 22:46:11 +00001885
Douglas Gregorf46034a2010-01-18 23:41:10 +00001886 Decl *D = getCursorDecl(C);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001887 SourceLocation Loc = D->getLocation();
1888 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
1889 Loc = Class->getClassLoc();
Douglas Gregor2ca54fe2010-03-22 15:53:50 +00001890 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00001891}
Douglas Gregora7bde202010-01-19 00:34:46 +00001892
1893CXSourceRange clang_getCursorExtent(CXCursor C) {
1894 if (clang_isReference(C.kind)) {
1895 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001896 case CXCursor_ObjCSuperClassRef: {
Douglas Gregora7bde202010-01-19 00:34:46 +00001897 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1898 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001899 return cxloc::translateSourceRange(P.first->getASTContext(), P.second);
Douglas Gregora7bde202010-01-19 00:34:46 +00001900 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001901
1902 case CXCursor_ObjCProtocolRef: {
Douglas Gregora7bde202010-01-19 00:34:46 +00001903 std::pair<ObjCProtocolDecl *, SourceLocation> P
1904 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001905 return cxloc::translateSourceRange(P.first->getASTContext(), P.second);
Douglas Gregora7bde202010-01-19 00:34:46 +00001906 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001907
1908 case CXCursor_ObjCClassRef: {
Douglas Gregora7bde202010-01-19 00:34:46 +00001909 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1910 = getCursorObjCClassRef(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001911
Ted Kremeneka297de22010-01-25 22:34:44 +00001912 return cxloc::translateSourceRange(P.first->getASTContext(), P.second);
Douglas Gregora7bde202010-01-19 00:34:46 +00001913 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001914
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001915 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001916 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001917 return cxloc::translateSourceRange(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001918 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001919
Douglas Gregora7bde202010-01-19 00:34:46 +00001920 default:
1921 // FIXME: Need a way to enumerate all non-reference cases.
1922 llvm_unreachable("Missed a reference kind");
1923 }
1924 }
Douglas Gregor97b98722010-01-19 23:20:36 +00001925
1926 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001927 return cxloc::translateSourceRange(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00001928 getCursorExpr(C)->getSourceRange());
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001929
1930 if (clang_isStatement(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001931 return cxloc::translateSourceRange(getCursorContext(C),
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001932 getCursorStmt(C)->getSourceRange());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001933
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00001934 if (C.kind == CXCursor_PreprocessingDirective) {
1935 SourceRange R = cxcursor::getCursorPreprocessingDirective(C);
1936 return cxloc::translateSourceRange(getCursorContext(C), R);
1937 }
Douglas Gregor48072312010-03-18 15:23:44 +00001938
1939 if (C.kind == CXCursor_MacroInstantiation) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00001940 SourceRange R = cxcursor::getCursorMacroInstantiation(C)->getSourceRange();
Douglas Gregor48072312010-03-18 15:23:44 +00001941 return cxloc::translateSourceRange(getCursorContext(C), R);
1942 }
Douglas Gregor572feb22010-03-18 18:04:21 +00001943
1944 if (C.kind == CXCursor_MacroDefinition) {
1945 SourceRange R = cxcursor::getCursorMacroDefinition(C)->getSourceRange();
1946 return cxloc::translateSourceRange(getCursorContext(C), R);
1947 }
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00001948
Ted Kremenek9a700d22010-05-12 06:16:13 +00001949 if (C.kind < CXCursor_FirstDecl || C.kind > CXCursor_LastDecl)
Douglas Gregor5352ac02010-01-28 00:27:43 +00001950 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001951
Douglas Gregora7bde202010-01-19 00:34:46 +00001952 Decl *D = getCursorDecl(C);
Douglas Gregor2ca54fe2010-03-22 15:53:50 +00001953 return cxloc::translateSourceRange(getCursorContext(C), D->getSourceRange());
Douglas Gregora7bde202010-01-19 00:34:46 +00001954}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001955
1956CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001957 if (clang_isInvalid(C.kind))
1958 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001959
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001960 ASTUnit *CXXUnit = getCursorASTUnit(C);
Douglas Gregorb6998662010-01-19 19:34:47 +00001961 if (clang_isDeclaration(C.kind))
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001962 return C;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001963
Douglas Gregor97b98722010-01-19 23:20:36 +00001964 if (clang_isExpression(C.kind)) {
1965 Decl *D = getDeclFromExpr(getCursorExpr(C));
1966 if (D)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001967 return MakeCXCursor(D, CXXUnit);
Douglas Gregor97b98722010-01-19 23:20:36 +00001968 return clang_getNullCursor();
1969 }
1970
Douglas Gregorbf7efa22010-03-18 18:23:03 +00001971 if (C.kind == CXCursor_MacroInstantiation) {
1972 if (MacroDefinition *Def = getCursorMacroInstantiation(C)->getDefinition())
1973 return MakeMacroDefinitionCursor(Def, CXXUnit);
1974 }
1975
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001976 if (!clang_isReference(C.kind))
1977 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001978
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001979 switch (C.kind) {
1980 case CXCursor_ObjCSuperClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001981 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001982
1983 case CXCursor_ObjCProtocolRef: {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001984 return MakeCXCursor(getCursorObjCProtocolRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001985
1986 case CXCursor_ObjCClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001987 return MakeCXCursor(getCursorObjCClassRef(C).first, CXXUnit);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001988
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001989 case CXCursor_TypeRef:
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001990 return MakeCXCursor(getCursorTypeRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001991
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001992 default:
1993 // We would prefer to enumerate all non-reference cursor kinds here.
1994 llvm_unreachable("Unhandled reference cursor kind");
1995 break;
1996 }
1997 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001998
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001999 return clang_getNullCursor();
2000}
2001
Douglas Gregorb6998662010-01-19 19:34:47 +00002002CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002003 if (clang_isInvalid(C.kind))
2004 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002005
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002006 ASTUnit *CXXUnit = getCursorASTUnit(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002007
Douglas Gregorb6998662010-01-19 19:34:47 +00002008 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00002009 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00002010 C = clang_getCursorReferenced(C);
2011 WasReference = true;
2012 }
2013
Douglas Gregorbf7efa22010-03-18 18:23:03 +00002014 if (C.kind == CXCursor_MacroInstantiation)
2015 return clang_getCursorReferenced(C);
2016
Douglas Gregorb6998662010-01-19 19:34:47 +00002017 if (!clang_isDeclaration(C.kind))
2018 return clang_getNullCursor();
2019
2020 Decl *D = getCursorDecl(C);
2021 if (!D)
2022 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002023
Douglas Gregorb6998662010-01-19 19:34:47 +00002024 switch (D->getKind()) {
2025 // Declaration kinds that don't really separate the notions of
2026 // declaration and definition.
2027 case Decl::Namespace:
2028 case Decl::Typedef:
2029 case Decl::TemplateTypeParm:
2030 case Decl::EnumConstant:
2031 case Decl::Field:
2032 case Decl::ObjCIvar:
2033 case Decl::ObjCAtDefsField:
2034 case Decl::ImplicitParam:
2035 case Decl::ParmVar:
2036 case Decl::NonTypeTemplateParm:
2037 case Decl::TemplateTemplateParm:
2038 case Decl::ObjCCategoryImpl:
2039 case Decl::ObjCImplementation:
2040 case Decl::LinkageSpec:
2041 case Decl::ObjCPropertyImpl:
2042 case Decl::FileScopeAsm:
2043 case Decl::StaticAssert:
2044 case Decl::Block:
2045 return C;
2046
2047 // Declaration kinds that don't make any sense here, but are
2048 // nonetheless harmless.
2049 case Decl::TranslationUnit:
Douglas Gregorb6998662010-01-19 19:34:47 +00002050 break;
2051
2052 // Declaration kinds for which the definition is not resolvable.
2053 case Decl::UnresolvedUsingTypename:
2054 case Decl::UnresolvedUsingValue:
2055 break;
2056
2057 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002058 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
2059 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002060
2061 case Decl::NamespaceAlias:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002062 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002063
2064 case Decl::Enum:
2065 case Decl::Record:
2066 case Decl::CXXRecord:
2067 case Decl::ClassTemplateSpecialization:
2068 case Decl::ClassTemplatePartialSpecialization:
Douglas Gregor952b0172010-02-11 01:04:33 +00002069 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002070 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002071 return clang_getNullCursor();
2072
2073 case Decl::Function:
2074 case Decl::CXXMethod:
2075 case Decl::CXXConstructor:
2076 case Decl::CXXDestructor:
2077 case Decl::CXXConversion: {
2078 const FunctionDecl *Def = 0;
2079 if (cast<FunctionDecl>(D)->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002080 return MakeCXCursor(const_cast<FunctionDecl *>(Def), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002081 return clang_getNullCursor();
2082 }
2083
2084 case Decl::Var: {
Sebastian Redl31310a22010-02-01 20:16:42 +00002085 // Ask the variable if it has a definition.
2086 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
2087 return MakeCXCursor(Def, CXXUnit);
2088 return clang_getNullCursor();
Douglas Gregorb6998662010-01-19 19:34:47 +00002089 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002090
Douglas Gregorb6998662010-01-19 19:34:47 +00002091 case Decl::FunctionTemplate: {
2092 const FunctionDecl *Def = 0;
2093 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002094 return MakeCXCursor(Def->getDescribedFunctionTemplate(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002095 return clang_getNullCursor();
2096 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002097
Douglas Gregorb6998662010-01-19 19:34:47 +00002098 case Decl::ClassTemplate: {
2099 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
Douglas Gregor952b0172010-02-11 01:04:33 +00002100 ->getDefinition())
Douglas Gregorb6998662010-01-19 19:34:47 +00002101 return MakeCXCursor(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002102 cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002103 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002104 return clang_getNullCursor();
2105 }
2106
2107 case Decl::Using: {
2108 UsingDecl *Using = cast<UsingDecl>(D);
2109 CXCursor Def = clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002110 for (UsingDecl::shadow_iterator S = Using->shadow_begin(),
2111 SEnd = Using->shadow_end();
Douglas Gregorb6998662010-01-19 19:34:47 +00002112 S != SEnd; ++S) {
2113 if (Def != clang_getNullCursor()) {
2114 // FIXME: We have no way to return multiple results.
2115 return clang_getNullCursor();
2116 }
2117
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002118 Def = clang_getCursorDefinition(MakeCXCursor((*S)->getTargetDecl(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002119 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002120 }
2121
2122 return Def;
2123 }
2124
2125 case Decl::UsingShadow:
2126 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002127 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002128 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002129
2130 case Decl::ObjCMethod: {
2131 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
2132 if (Method->isThisDeclarationADefinition())
2133 return C;
2134
2135 // Dig out the method definition in the associated
2136 // @implementation, if we have it.
2137 // FIXME: The ASTs should make finding the definition easier.
2138 if (ObjCInterfaceDecl *Class
2139 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
2140 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
2141 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
2142 Method->isInstanceMethod()))
2143 if (Def->isThisDeclarationADefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002144 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002145
2146 return clang_getNullCursor();
2147 }
2148
2149 case Decl::ObjCCategory:
2150 if (ObjCCategoryImplDecl *Impl
2151 = cast<ObjCCategoryDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002152 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002153 return clang_getNullCursor();
2154
2155 case Decl::ObjCProtocol:
2156 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
2157 return C;
2158 return clang_getNullCursor();
2159
2160 case Decl::ObjCInterface:
2161 // There are two notions of a "definition" for an Objective-C
2162 // class: the interface and its implementation. When we resolved a
2163 // reference to an Objective-C class, produce the @interface as
2164 // the definition; when we were provided with the interface,
2165 // produce the @implementation as the definition.
2166 if (WasReference) {
2167 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
2168 return C;
2169 } else if (ObjCImplementationDecl *Impl
2170 = cast<ObjCInterfaceDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002171 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002172 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002173
Douglas Gregorb6998662010-01-19 19:34:47 +00002174 case Decl::ObjCProperty:
2175 // FIXME: We don't really know where to find the
2176 // ObjCPropertyImplDecls that implement this property.
2177 return clang_getNullCursor();
2178
2179 case Decl::ObjCCompatibleAlias:
2180 if (ObjCInterfaceDecl *Class
2181 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
2182 if (!Class->isForwardDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002183 return MakeCXCursor(Class, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002184
Douglas Gregorb6998662010-01-19 19:34:47 +00002185 return clang_getNullCursor();
2186
2187 case Decl::ObjCForwardProtocol: {
2188 ObjCForwardProtocolDecl *Forward = cast<ObjCForwardProtocolDecl>(D);
2189 if (Forward->protocol_size() == 1)
2190 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002191 MakeCXCursor(*Forward->protocol_begin(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002192 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002193
2194 // FIXME: Cannot return multiple definitions.
2195 return clang_getNullCursor();
2196 }
2197
2198 case Decl::ObjCClass: {
2199 ObjCClassDecl *Class = cast<ObjCClassDecl>(D);
2200 if (Class->size() == 1) {
2201 ObjCInterfaceDecl *IFace = Class->begin()->getInterface();
2202 if (!IFace->isForwardDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002203 return MakeCXCursor(IFace, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002204 return clang_getNullCursor();
2205 }
2206
2207 // FIXME: Cannot return multiple definitions.
2208 return clang_getNullCursor();
2209 }
2210
2211 case Decl::Friend:
2212 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002213 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002214 return clang_getNullCursor();
2215
2216 case Decl::FriendTemplate:
2217 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002218 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002219 return clang_getNullCursor();
2220 }
2221
2222 return clang_getNullCursor();
2223}
2224
2225unsigned clang_isCursorDefinition(CXCursor C) {
2226 if (!clang_isDeclaration(C.kind))
2227 return 0;
2228
2229 return clang_getCursorDefinition(C) == C;
2230}
2231
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002232void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00002233 const char **startBuf,
2234 const char **endBuf,
2235 unsigned *startLine,
2236 unsigned *startColumn,
2237 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002238 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00002239 assert(getCursorDecl(C) && "CXCursor has null decl");
2240 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00002241 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
2242 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002243
Steve Naroff4ade6d62009-09-23 17:52:52 +00002244 SourceManager &SM = FD->getASTContext().getSourceManager();
2245 *startBuf = SM.getCharacterData(Body->getLBracLoc());
2246 *endBuf = SM.getCharacterData(Body->getRBracLoc());
2247 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
2248 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
2249 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
2250 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
2251}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002252
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002253void clang_enableStackTraces(void) {
2254 llvm::sys::PrintStackTraceOnErrorSignal();
2255}
2256
Ted Kremenekfb480492010-01-13 21:46:36 +00002257} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00002258
Ted Kremenekfb480492010-01-13 21:46:36 +00002259//===----------------------------------------------------------------------===//
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002260// Token-based Operations.
2261//===----------------------------------------------------------------------===//
2262
2263/* CXToken layout:
2264 * int_data[0]: a CXTokenKind
2265 * int_data[1]: starting token location
2266 * int_data[2]: token length
2267 * int_data[3]: reserved
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002268 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002269 * otherwise unused.
2270 */
2271extern "C" {
2272
2273CXTokenKind clang_getTokenKind(CXToken CXTok) {
2274 return static_cast<CXTokenKind>(CXTok.int_data[0]);
2275}
2276
2277CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
2278 switch (clang_getTokenKind(CXTok)) {
2279 case CXToken_Identifier:
2280 case CXToken_Keyword:
2281 // We know we have an IdentifierInfo*, so use that.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002282 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
2283 ->getNameStart());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002284
2285 case CXToken_Literal: {
2286 // We have stashed the starting pointer in the ptr_data field. Use it.
2287 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002288 return createCXString(llvm::StringRef(Text, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002289 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002290
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002291 case CXToken_Punctuation:
2292 case CXToken_Comment:
2293 break;
2294 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002295
2296 // We have to find the starting buffer pointer the hard way, by
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002297 // deconstructing the source location.
2298 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2299 if (!CXXUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002300 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002301
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002302 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
2303 std::pair<FileID, unsigned> LocInfo
2304 = CXXUnit->getSourceManager().getDecomposedLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +00002305 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002306 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00002307 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
2308 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00002309 return createCXString("");
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002310
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002311 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002312}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002313
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002314CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
2315 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2316 if (!CXXUnit)
2317 return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002318
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002319 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
2320 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
2321}
2322
2323CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
2324 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregor5352ac02010-01-28 00:27:43 +00002325 if (!CXXUnit)
2326 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002327
2328 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002329 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
2330}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002331
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002332void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
2333 CXToken **Tokens, unsigned *NumTokens) {
2334 if (Tokens)
2335 *Tokens = 0;
2336 if (NumTokens)
2337 *NumTokens = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002338
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002339 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2340 if (!CXXUnit || !Tokens || !NumTokens)
2341 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002342
Douglas Gregorbdf60622010-03-05 21:16:25 +00002343 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
2344
Daniel Dunbar85b988f2010-02-14 08:31:57 +00002345 SourceRange R = cxloc::translateCXSourceRange(Range);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002346 if (R.isInvalid())
2347 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002348
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002349 SourceManager &SourceMgr = CXXUnit->getSourceManager();
2350 std::pair<FileID, unsigned> BeginLocInfo
2351 = SourceMgr.getDecomposedLoc(R.getBegin());
2352 std::pair<FileID, unsigned> EndLocInfo
2353 = SourceMgr.getDecomposedLoc(R.getEnd());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002354
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002355 // Cannot tokenize across files.
2356 if (BeginLocInfo.first != EndLocInfo.first)
2357 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002358
2359 // Create a lexer
Douglas Gregorf715ca12010-03-16 00:06:06 +00002360 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002361 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00002362 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
Douglas Gregor47a3fcd2010-03-16 20:26:15 +00002363 if (Invalid)
2364 return;
Douglas Gregoraea67db2010-03-15 22:54:52 +00002365
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002366 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
2367 CXXUnit->getASTContext().getLangOptions(),
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002368 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002369 Lex.SetCommentRetentionState(true);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002370
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002371 // Lex tokens until we hit the end of the range.
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002372 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002373 llvm::SmallVector<CXToken, 32> CXTokens;
2374 Token Tok;
2375 do {
2376 // Lex the next token
2377 Lex.LexFromRawLexer(Tok);
2378 if (Tok.is(tok::eof))
2379 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002380
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002381 // Initialize the CXToken.
2382 CXToken CXTok;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002383
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002384 // - Common fields
2385 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
2386 CXTok.int_data[2] = Tok.getLength();
2387 CXTok.int_data[3] = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002388
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002389 // - Kind-specific fields
2390 if (Tok.isLiteral()) {
2391 CXTok.int_data[0] = CXToken_Literal;
2392 CXTok.ptr_data = (void *)Tok.getLiteralData();
2393 } else if (Tok.is(tok::identifier)) {
Douglas Gregoraea67db2010-03-15 22:54:52 +00002394 // Lookup the identifier to determine whether we have a keyword.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002395 std::pair<FileID, unsigned> LocInfo
2396 = SourceMgr.getDecomposedLoc(Tok.getLocation());
Douglas Gregorf715ca12010-03-16 00:06:06 +00002397 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002398 llvm::StringRef Buf
Douglas Gregorf715ca12010-03-16 00:06:06 +00002399 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
2400 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00002401 return;
2402
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002403 const char *StartPos = Buf.data() + LocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002404 IdentifierInfo *II
2405 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok, StartPos);
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00002406
2407 if (II->getObjCKeywordID() != tok::objc_not_keyword) {
2408 CXTok.int_data[0] = CXToken_Keyword;
2409 }
2410 else {
2411 CXTok.int_data[0] = II->getTokenID() == tok::identifier?
2412 CXToken_Identifier
2413 : CXToken_Keyword;
2414 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002415 CXTok.ptr_data = II;
2416 } else if (Tok.is(tok::comment)) {
2417 CXTok.int_data[0] = CXToken_Comment;
2418 CXTok.ptr_data = 0;
2419 } else {
2420 CXTok.int_data[0] = CXToken_Punctuation;
2421 CXTok.ptr_data = 0;
2422 }
2423 CXTokens.push_back(CXTok);
2424 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002425
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002426 if (CXTokens.empty())
2427 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002428
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002429 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
2430 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
2431 *NumTokens = CXTokens.size();
2432}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002433
Ted Kremenek6db61092010-05-05 00:55:15 +00002434void clang_disposeTokens(CXTranslationUnit TU,
2435 CXToken *Tokens, unsigned NumTokens) {
2436 free(Tokens);
2437}
2438
2439} // end: extern "C"
2440
2441//===----------------------------------------------------------------------===//
2442// Token annotation APIs.
2443//===----------------------------------------------------------------------===//
2444
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002445typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002446static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
2447 CXCursor parent,
2448 CXClientData client_data);
Ted Kremenek6db61092010-05-05 00:55:15 +00002449namespace {
2450class AnnotateTokensWorker {
2451 AnnotateTokensData &Annotated;
Ted Kremenek11949cb2010-05-05 00:55:17 +00002452 CXToken *Tokens;
2453 CXCursor *Cursors;
2454 unsigned NumTokens;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002455 unsigned TokIdx;
2456 CursorVisitor AnnotateVis;
2457 SourceManager &SrcMgr;
2458
2459 bool MoreTokens() const { return TokIdx < NumTokens; }
2460 unsigned NextToken() const { return TokIdx; }
2461 void AdvanceToken() { ++TokIdx; }
2462 SourceLocation GetTokenLoc(unsigned tokI) {
2463 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
2464 }
2465
Ted Kremenek6db61092010-05-05 00:55:15 +00002466public:
Ted Kremenek11949cb2010-05-05 00:55:17 +00002467 AnnotateTokensWorker(AnnotateTokensData &annotated,
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002468 CXToken *tokens, CXCursor *cursors, unsigned numTokens,
2469 ASTUnit *CXXUnit, SourceRange RegionOfInterest)
Ted Kremenek11949cb2010-05-05 00:55:17 +00002470 : Annotated(annotated), Tokens(tokens), Cursors(cursors),
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002471 NumTokens(numTokens), TokIdx(0),
2472 AnnotateVis(CXXUnit, AnnotateTokensVisitor, this,
2473 Decl::MaxPCHLevel, RegionOfInterest),
2474 SrcMgr(CXXUnit->getSourceManager()) {}
Ted Kremenek11949cb2010-05-05 00:55:17 +00002475
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002476 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
Ted Kremenek6db61092010-05-05 00:55:15 +00002477 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002478 void AnnotateTokens(CXCursor parent);
Ted Kremenek6db61092010-05-05 00:55:15 +00002479};
2480}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002481
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002482void AnnotateTokensWorker::AnnotateTokens(CXCursor parent) {
2483 // Walk the AST within the region of interest, annotating tokens
2484 // along the way.
2485 VisitChildren(parent);
Ted Kremenek11949cb2010-05-05 00:55:17 +00002486
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002487 for (unsigned I = 0 ; I < TokIdx ; ++I) {
2488 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
2489 if (Pos != Annotated.end())
2490 Cursors[I] = Pos->second;
2491 }
2492
2493 // Finish up annotating any tokens left.
2494 if (!MoreTokens())
2495 return;
2496
2497 const CXCursor &C = clang_getNullCursor();
2498 for (unsigned I = TokIdx ; I < NumTokens ; ++I) {
2499 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
2500 Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second;
Ted Kremenek11949cb2010-05-05 00:55:17 +00002501 }
2502}
2503
Ted Kremenek6db61092010-05-05 00:55:15 +00002504enum CXChildVisitResult
2505AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002506 CXSourceLocation Loc = clang_getCursorLocation(cursor);
2507 // We can always annotate a preprocessing directive/macro instantiation.
2508 if (clang_isPreprocessing(cursor.kind)) {
2509 Annotated[Loc.int_data] = cursor;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002510 return CXChildVisit_Recurse;
2511 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002512
2513 CXSourceRange cursorExtent = clang_getCursorExtent(cursor);
2514 SourceRange cursorRange = cxloc::translateCXSourceRange(cursorExtent);
Ted Kremeneka333c662010-05-12 05:29:33 +00002515
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002516 if (cursorRange.isInvalid())
2517 return CXChildVisit_Continue;
Ted Kremeneka333c662010-05-12 05:29:33 +00002518
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002519 SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data);
2520
Ted Kremeneka333c662010-05-12 05:29:33 +00002521 // Adjust the annotated range based specific declarations.
2522 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
2523 if (cursorK >= CXCursor_FirstDecl && cursorK <= CXCursor_LastDecl) {
Ted Kremenek23173d72010-05-18 21:09:07 +00002524 Decl *D = cxcursor::getCursorDecl(cursor);
2525 // Don't visit synthesized ObjC methods, since they have no syntatic
2526 // representation in the source.
2527 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
2528 if (MD->isSynthesized())
2529 return CXChildVisit_Continue;
2530 }
2531 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
Ted Kremeneka333c662010-05-12 05:29:33 +00002532 if (TypeSourceInfo *TI = DD->getTypeSourceInfo()) {
2533 TypeLoc TL = TI->getTypeLoc();
2534 SourceLocation TLoc = TL.getFullSourceRange().getBegin();
Ted Kremenek6bfd5332010-05-13 15:38:38 +00002535 if (TLoc.isValid() &&
2536 SrcMgr.isBeforeInTranslationUnit(TLoc, L))
Ted Kremeneka333c662010-05-12 05:29:33 +00002537 cursorRange.setBegin(TLoc);
Ted Kremeneka333c662010-05-12 05:29:33 +00002538 }
2539 }
2540 }
2541
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002542 const enum CXCursorKind K = clang_getCursorKind(parent);
2543 const CXCursor updateC =
2544 (clang_isInvalid(K) || K == CXCursor_TranslationUnit ||
2545 L.isMacroID())
2546 ? clang_getNullCursor() : parent;
2547
2548 while (MoreTokens()) {
2549 const unsigned I = NextToken();
2550 SourceLocation TokLoc = GetTokenLoc(I);
2551 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
2552 case RangeBefore:
2553 Cursors[I] = updateC;
2554 AdvanceToken();
2555 continue;
2556 case RangeAfter:
2557 return CXChildVisit_Continue;
2558 case RangeOverlap:
2559 break;
2560 }
2561 break;
2562 }
2563
2564 // Visit children to get their cursor information.
2565 const unsigned BeforeChildren = NextToken();
2566 VisitChildren(cursor);
2567 const unsigned AfterChildren = NextToken();
2568
2569 // Adjust 'Last' to the last token within the extent of the cursor.
2570 while (MoreTokens()) {
2571 const unsigned I = NextToken();
2572 SourceLocation TokLoc = GetTokenLoc(I);
2573 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
2574 case RangeBefore:
2575 assert(0 && "Infeasible");
2576 case RangeAfter:
2577 break;
2578 case RangeOverlap:
2579 Cursors[I] = updateC;
2580 AdvanceToken();
2581 continue;
2582 }
2583 break;
2584 }
2585 const unsigned Last = NextToken();
Ted Kremenek6db61092010-05-05 00:55:15 +00002586
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002587 // Scan the tokens that are at the beginning of the cursor, but are not
2588 // capture by the child cursors.
2589
2590 // For AST elements within macros, rely on a post-annotate pass to
2591 // to correctly annotate the tokens with cursors. Otherwise we can
2592 // get confusing results of having tokens that map to cursors that really
2593 // are expanded by an instantiation.
2594 if (L.isMacroID())
2595 cursor = clang_getNullCursor();
2596
2597 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
2598 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
2599 break;
2600 Cursors[I] = cursor;
2601 }
2602 // Scan the tokens that are at the end of the cursor, but are not captured
2603 // but the child cursors.
2604 for (unsigned I = AfterChildren; I != Last; ++I)
2605 Cursors[I] = cursor;
2606
2607 TokIdx = Last;
2608 return CXChildVisit_Continue;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002609}
2610
Ted Kremenek6db61092010-05-05 00:55:15 +00002611static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
2612 CXCursor parent,
2613 CXClientData client_data) {
2614 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
2615}
2616
2617extern "C" {
2618
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002619void clang_annotateTokens(CXTranslationUnit TU,
2620 CXToken *Tokens, unsigned NumTokens,
2621 CXCursor *Cursors) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002622
2623 if (NumTokens == 0 || !Tokens || !Cursors)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002624 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002625
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002626 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002627 if (!CXXUnit) {
2628 // Any token we don't specifically annotate will have a NULL cursor.
2629 const CXCursor &C = clang_getNullCursor();
2630 for (unsigned I = 0; I != NumTokens; ++I)
2631 Cursors[I] = C;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002632 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002633 }
2634
Douglas Gregorbdf60622010-03-05 21:16:25 +00002635 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002636
Douglas Gregor0396f462010-03-19 05:22:59 +00002637 // Determine the region of interest, which contains all of the tokens.
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002638 SourceRange RegionOfInterest;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002639 RegionOfInterest.setBegin(cxloc::translateSourceLocation(
2640 clang_getTokenLocation(TU, Tokens[0])));
2641
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002642 SourceLocation End
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002643 = cxloc::translateSourceLocation(clang_getTokenLocation(TU,
2644 Tokens[NumTokens - 1]));
Daniel Dunbard52864b2010-02-14 10:02:57 +00002645 RegionOfInterest.setEnd(CXXUnit->getPreprocessor().getLocForEndOfToken(End));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002646
Douglas Gregor0396f462010-03-19 05:22:59 +00002647 // A mapping from the source locations found when re-lexing or traversing the
2648 // region of interest to the corresponding cursors.
2649 AnnotateTokensData Annotated;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002650
2651 // Relex the tokens within the source range to look for preprocessing
Douglas Gregor0396f462010-03-19 05:22:59 +00002652 // directives.
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002653 SourceManager &SourceMgr = CXXUnit->getSourceManager();
2654 std::pair<FileID, unsigned> BeginLocInfo
2655 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
2656 std::pair<FileID, unsigned> EndLocInfo
2657 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002658
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002659 llvm::StringRef Buffer;
Douglas Gregor0396f462010-03-19 05:22:59 +00002660 bool Invalid = false;
2661 if (BeginLocInfo.first == EndLocInfo.first &&
2662 ((Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid)),true) &&
2663 !Invalid) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002664 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
2665 CXXUnit->getASTContext().getLangOptions(),
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002666 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002667 Buffer.end());
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002668 Lex.SetCommentRetentionState(true);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002669
2670 // Lex tokens in raw mode until we hit the end of the range, to avoid
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002671 // entering #includes or expanding macros.
Douglas Gregor48072312010-03-18 15:23:44 +00002672 while (true) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002673 Token Tok;
2674 Lex.LexFromRawLexer(Tok);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002675
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002676 reprocess:
2677 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
2678 // We have found a preprocessing directive. Gobble it up so that we
2679 // don't see it while preprocessing these tokens later, but keep track of
2680 // all of the token locations inside this preprocessing directive so that
2681 // we can annotate them appropriately.
2682 //
2683 // FIXME: Some simple tests here could identify macro definitions and
2684 // #undefs, to provide specific cursor kinds for those.
2685 std::vector<SourceLocation> Locations;
2686 do {
2687 Locations.push_back(Tok.getLocation());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002688 Lex.LexFromRawLexer(Tok);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002689 } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002690
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002691 using namespace cxcursor;
2692 CXCursor Cursor
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002693 = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
2694 Locations.back()),
Ted Kremenek6db61092010-05-05 00:55:15 +00002695 CXXUnit);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002696 for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
2697 Annotated[Locations[I].getRawEncoding()] = Cursor;
2698 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002699
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002700 if (Tok.isAtStartOfLine())
2701 goto reprocess;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002702
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002703 continue;
2704 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002705
Douglas Gregor48072312010-03-18 15:23:44 +00002706 if (Tok.is(tok::eof))
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002707 break;
2708 }
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002709 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002710
Douglas Gregor0396f462010-03-19 05:22:59 +00002711 // Annotate all of the source locations in the region of interest that map to
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002712 // a specific cursor.
2713 AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens,
2714 CXXUnit, RegionOfInterest);
2715 W.AnnotateTokens(clang_getTranslationUnitCursor(CXXUnit));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002716}
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002717} // end: extern "C"
2718
2719//===----------------------------------------------------------------------===//
Ted Kremenek16b42592010-03-03 06:36:57 +00002720// Operations for querying linkage of a cursor.
2721//===----------------------------------------------------------------------===//
2722
2723extern "C" {
2724CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
Douglas Gregor0396f462010-03-19 05:22:59 +00002725 if (!clang_isDeclaration(cursor.kind))
2726 return CXLinkage_Invalid;
2727
Ted Kremenek16b42592010-03-03 06:36:57 +00002728 Decl *D = cxcursor::getCursorDecl(cursor);
2729 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
2730 switch (ND->getLinkage()) {
2731 case NoLinkage: return CXLinkage_NoLinkage;
2732 case InternalLinkage: return CXLinkage_Internal;
2733 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
2734 case ExternalLinkage: return CXLinkage_External;
2735 };
2736
2737 return CXLinkage_Invalid;
2738}
2739} // end: extern "C"
2740
2741//===----------------------------------------------------------------------===//
Ted Kremenek45e1dae2010-04-12 21:22:16 +00002742// Operations for querying language of a cursor.
2743//===----------------------------------------------------------------------===//
2744
2745static CXLanguageKind getDeclLanguage(const Decl *D) {
2746 switch (D->getKind()) {
2747 default:
2748 break;
2749 case Decl::ImplicitParam:
2750 case Decl::ObjCAtDefsField:
2751 case Decl::ObjCCategory:
2752 case Decl::ObjCCategoryImpl:
2753 case Decl::ObjCClass:
2754 case Decl::ObjCCompatibleAlias:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00002755 case Decl::ObjCForwardProtocol:
2756 case Decl::ObjCImplementation:
2757 case Decl::ObjCInterface:
2758 case Decl::ObjCIvar:
2759 case Decl::ObjCMethod:
2760 case Decl::ObjCProperty:
2761 case Decl::ObjCPropertyImpl:
2762 case Decl::ObjCProtocol:
2763 return CXLanguage_ObjC;
2764 case Decl::CXXConstructor:
2765 case Decl::CXXConversion:
2766 case Decl::CXXDestructor:
2767 case Decl::CXXMethod:
2768 case Decl::CXXRecord:
2769 case Decl::ClassTemplate:
2770 case Decl::ClassTemplatePartialSpecialization:
2771 case Decl::ClassTemplateSpecialization:
2772 case Decl::Friend:
2773 case Decl::FriendTemplate:
2774 case Decl::FunctionTemplate:
2775 case Decl::LinkageSpec:
2776 case Decl::Namespace:
2777 case Decl::NamespaceAlias:
2778 case Decl::NonTypeTemplateParm:
2779 case Decl::StaticAssert:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00002780 case Decl::TemplateTemplateParm:
2781 case Decl::TemplateTypeParm:
2782 case Decl::UnresolvedUsingTypename:
2783 case Decl::UnresolvedUsingValue:
2784 case Decl::Using:
2785 case Decl::UsingDirective:
2786 case Decl::UsingShadow:
2787 return CXLanguage_CPlusPlus;
2788 }
2789
2790 return CXLanguage_C;
2791}
2792
2793extern "C" {
2794CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
2795 if (clang_isDeclaration(cursor.kind))
2796 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
2797
2798 return CXLanguage_Invalid;
2799}
2800} // end: extern "C"
2801
Ted Kremenek9ada39a2010-05-17 20:06:56 +00002802
2803//===----------------------------------------------------------------------===//
2804// C++ AST instrospection.
2805//===----------------------------------------------------------------------===//
2806
2807extern "C" {
2808unsigned clang_CXXMethod_isStatic(CXCursor C) {
2809 if (!clang_isDeclaration(C.kind))
2810 return 0;
2811 CXXMethodDecl *D = dyn_cast<CXXMethodDecl>(cxcursor::getCursorDecl(C));
2812 return (D && D->isStatic()) ? 1 : 0;
Ted Kremenek40b492a2010-05-17 20:12:45 +00002813}
Ted Kremenekb12903e2010-05-18 22:32:15 +00002814
2815unsigned clang_isTagDeclDefinition(CXCursor C) {
2816 if (!clang_isDeclaration(C.kind))
2817 return 0;
2818
2819 const TagDecl *D = dyn_cast<TagDecl>(cxcursor::getCursorDecl(C));
2820 return D && D->isDefinition() ? 1 : 0;
2821}
2822
Ted Kremenek9ada39a2010-05-17 20:06:56 +00002823} // end: extern "C"
2824
Ted Kremenek45e1dae2010-04-12 21:22:16 +00002825//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00002826// CXString Operations.
2827//===----------------------------------------------------------------------===//
2828
2829extern "C" {
2830const char *clang_getCString(CXString string) {
2831 return string.Spelling;
2832}
2833
2834void clang_disposeString(CXString string) {
2835 if (string.MustFreeString && string.Spelling)
2836 free((void*)string.Spelling);
2837}
Ted Kremenek04bb7162010-01-22 22:44:15 +00002838
Ted Kremenekfb480492010-01-13 21:46:36 +00002839} // end: extern "C"
Ted Kremenek04bb7162010-01-22 22:44:15 +00002840
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002841namespace clang { namespace cxstring {
2842CXString createCXString(const char *String, bool DupString){
2843 CXString Str;
2844 if (DupString) {
2845 Str.Spelling = strdup(String);
2846 Str.MustFreeString = 1;
2847 } else {
2848 Str.Spelling = String;
2849 Str.MustFreeString = 0;
2850 }
2851 return Str;
2852}
2853
2854CXString createCXString(llvm::StringRef String, bool DupString) {
2855 CXString Result;
2856 if (DupString || (!String.empty() && String.data()[String.size()] != 0)) {
2857 char *Spelling = (char *)malloc(String.size() + 1);
2858 memmove(Spelling, String.data(), String.size());
2859 Spelling[String.size()] = 0;
2860 Result.Spelling = Spelling;
2861 Result.MustFreeString = 1;
2862 } else {
2863 Result.Spelling = String.data();
2864 Result.MustFreeString = 0;
2865 }
2866 return Result;
2867}
2868}}
2869
Ted Kremenek04bb7162010-01-22 22:44:15 +00002870//===----------------------------------------------------------------------===//
2871// Misc. utility functions.
2872//===----------------------------------------------------------------------===//
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002873
Ted Kremenek04bb7162010-01-22 22:44:15 +00002874extern "C" {
2875
Ted Kremeneka2a9d6e2010-02-12 22:54:40 +00002876CXString clang_getClangVersion() {
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002877 return createCXString(getClangFullVersion());
Ted Kremenek04bb7162010-01-22 22:44:15 +00002878}
2879
2880} // end: extern "C"