blob: 16cd309b319b0ce615f4c9398a661beac40c2e7f [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);
300 bool VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
301 bool VisitObjCImplDecl(ObjCImplDecl *D);
302 bool VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
303 bool VisitObjCImplementationDecl(ObjCImplementationDecl *D);
304 // FIXME: ObjCPropertyDecl requires TypeSourceInfo, getter/setter locations,
305 // etc.
306 // FIXME: ObjCCompatibleAliasDecl requires aliased-class locations.
307 bool VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D);
308 bool VisitObjCClassDecl(ObjCClassDecl *D);
Ted Kremeneka0536d82010-05-07 01:04:29 +0000309 bool VisitLinkageSpecDecl(LinkageSpecDecl *D);
Ted Kremenek8f06e0e2010-05-06 23:38:21 +0000310 bool VisitNamespaceDecl(NamespaceDecl *D);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000311
312 // Type visitors
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000313 // FIXME: QualifiedTypeLoc doesn't provide any location information
314 bool VisitBuiltinTypeLoc(BuiltinTypeLoc TL);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000315 bool VisitTypedefTypeLoc(TypedefTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000316 bool VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL);
317 bool VisitTagTypeLoc(TagTypeLoc TL);
318 // FIXME: TemplateTypeParmTypeLoc doesn't provide any location information
319 bool VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL);
John McCallc12c5bb2010-05-15 11:32:37 +0000320 bool VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000321 bool VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL);
322 bool VisitPointerTypeLoc(PointerTypeLoc TL);
323 bool VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL);
324 bool VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL);
325 bool VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL);
326 bool VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL);
327 bool VisitFunctionTypeLoc(FunctionTypeLoc TL);
328 bool VisitArrayTypeLoc(ArrayTypeLoc TL);
Douglas Gregor2332c112010-01-21 20:48:56 +0000329 // FIXME: Implement for TemplateSpecializationTypeLoc
330 // FIXME: Implement visitors here when the unimplemented TypeLocs get
331 // implemented
332 bool VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL);
333 bool VisitTypeOfTypeLoc(TypeOfTypeLoc TL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000334
Douglas Gregora59e3902010-01-21 23:27:09 +0000335 // Statement visitors
336 bool VisitStmt(Stmt *S);
337 bool VisitDeclStmt(DeclStmt *S);
Douglas Gregorf5bab412010-01-22 01:00:11 +0000338 // FIXME: LabelStmt label?
339 bool VisitIfStmt(IfStmt *S);
340 bool VisitSwitchStmt(SwitchStmt *S);
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000341 bool VisitCaseStmt(CaseStmt *S);
Douglas Gregor263b47b2010-01-25 16:12:32 +0000342 bool VisitWhileStmt(WhileStmt *S);
343 bool VisitForStmt(ForStmt *S);
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000344// bool VisitSwitchCase(SwitchCase *S);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000345
Douglas Gregor336fd812010-01-23 00:40:08 +0000346 // Expression visitors
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000347 bool VisitBlockExpr(BlockExpr *B);
Douglas Gregor336fd812010-01-23 00:40:08 +0000348 bool VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000349 bool VisitExplicitCastExpr(ExplicitCastExpr *E);
Douglas Gregorc2350e52010-03-08 16:40:19 +0000350 bool VisitObjCMessageExpr(ObjCMessageExpr *E);
Douglas Gregor81d34662010-04-20 15:39:42 +0000351 bool VisitObjCEncodeExpr(ObjCEncodeExpr *E);
Douglas Gregor8ecdb652010-04-28 22:16:22 +0000352 bool VisitOffsetOfExpr(OffsetOfExpr *E);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000353 bool VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E);
Steve Naroff89922f82009-08-31 00:59:03 +0000354};
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000355
Ted Kremenekab188932010-01-05 19:32:54 +0000356} // end anonymous namespace
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000357
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000358RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000359 return RangeCompare(TU->getSourceManager(), R, RegionOfInterest);
360}
361
Douglas Gregorb1373d02010-01-20 20:59:29 +0000362/// \brief Visit the given cursor and, if requested by the visitor,
363/// its children.
364///
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000365/// \param Cursor the cursor to visit.
366///
367/// \param CheckRegionOfInterest if true, then the caller already checked that
368/// this cursor is within the region of interest.
369///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000370/// \returns true if the visitation should be aborted, false if it
371/// should continue.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000372bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
Douglas Gregorb1373d02010-01-20 20:59:29 +0000373 if (clang_isInvalid(Cursor.kind))
374 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000375
Douglas Gregorb1373d02010-01-20 20:59:29 +0000376 if (clang_isDeclaration(Cursor.kind)) {
377 Decl *D = getCursorDecl(Cursor);
378 assert(D && "Invalid declaration cursor");
379 if (D->getPCHLevel() > MaxPCHLevel)
380 return false;
381
382 if (D->isImplicit())
383 return false;
384 }
385
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000386 // If we have a range of interest, and this cursor doesn't intersect with it,
387 // we're done.
388 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
Daniel Dunbarf408f322010-02-14 08:32:05 +0000389 SourceRange Range =
390 cxloc::translateCXSourceRange(clang_getCursorExtent(Cursor));
391 if (Range.isInvalid() || CompareRegionOfInterest(Range))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000392 return false;
393 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000394
Douglas Gregorb1373d02010-01-20 20:59:29 +0000395 switch (Visitor(Cursor, Parent, ClientData)) {
396 case CXChildVisit_Break:
397 return true;
398
399 case CXChildVisit_Continue:
400 return false;
401
402 case CXChildVisit_Recurse:
403 return VisitChildren(Cursor);
404 }
405
Douglas Gregorfd643772010-01-25 16:45:46 +0000406 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000407}
408
Douglas Gregor788f5a12010-03-20 00:41:21 +0000409std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
410CursorVisitor::getPreprocessedEntities() {
411 PreprocessingRecord &PPRec
412 = *TU->getPreprocessor().getPreprocessingRecord();
413
414 bool OnlyLocalDecls
415 = !TU->isMainFileAST() && TU->getOnlyLocalDecls();
416
417 // There is no region of interest; we have to walk everything.
418 if (RegionOfInterest.isInvalid())
419 return std::make_pair(PPRec.begin(OnlyLocalDecls),
420 PPRec.end(OnlyLocalDecls));
421
422 // Find the file in which the region of interest lands.
423 SourceManager &SM = TU->getSourceManager();
424 std::pair<FileID, unsigned> Begin
425 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getBegin());
426 std::pair<FileID, unsigned> End
427 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getEnd());
428
429 // The region of interest spans files; we have to walk everything.
430 if (Begin.first != End.first)
431 return std::make_pair(PPRec.begin(OnlyLocalDecls),
432 PPRec.end(OnlyLocalDecls));
433
434 ASTUnit::PreprocessedEntitiesByFileMap &ByFileMap
435 = TU->getPreprocessedEntitiesByFile();
436 if (ByFileMap.empty()) {
437 // Build the mapping from files to sets of preprocessed entities.
438 for (PreprocessingRecord::iterator E = PPRec.begin(OnlyLocalDecls),
439 EEnd = PPRec.end(OnlyLocalDecls);
440 E != EEnd; ++E) {
441 std::pair<FileID, unsigned> P
442 = SM.getDecomposedInstantiationLoc((*E)->getSourceRange().getBegin());
443 ByFileMap[P.first].push_back(*E);
444 }
445 }
446
447 return std::make_pair(ByFileMap[Begin.first].begin(),
448 ByFileMap[Begin.first].end());
449}
450
Douglas Gregorb1373d02010-01-20 20:59:29 +0000451/// \brief Visit the children of the given cursor.
452///
453/// \returns true if the visitation should be aborted, false if it
454/// should continue.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000455bool CursorVisitor::VisitChildren(CXCursor Cursor) {
Douglas Gregora59e3902010-01-21 23:27:09 +0000456 if (clang_isReference(Cursor.kind)) {
457 // By definition, references have no children.
458 return false;
459 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000460
461 // Set the Parent field to Cursor, then back to its old value once we're
Douglas Gregorb1373d02010-01-20 20:59:29 +0000462 // done.
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000463 SetParentRAII SetParent(Parent, StmtParent, Cursor);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000464
Douglas Gregorb1373d02010-01-20 20:59:29 +0000465 if (clang_isDeclaration(Cursor.kind)) {
466 Decl *D = getCursorDecl(Cursor);
467 assert(D && "Invalid declaration cursor");
Ted Kremenek539311e2010-02-18 18:47:01 +0000468 return VisitAttributes(D) || Visit(D);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000469 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000470
Douglas Gregora59e3902010-01-21 23:27:09 +0000471 if (clang_isStatement(Cursor.kind))
472 return Visit(getCursorStmt(Cursor));
473 if (clang_isExpression(Cursor.kind))
474 return Visit(getCursorExpr(Cursor));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000475
Douglas Gregorb1373d02010-01-20 20:59:29 +0000476 if (clang_isTranslationUnit(Cursor.kind)) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000477 ASTUnit *CXXUnit = getCursorASTUnit(Cursor);
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000478 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
479 RegionOfInterest.isInvalid()) {
Douglas Gregor7b691f332010-01-20 21:13:59 +0000480 const std::vector<Decl*> &TLDs = CXXUnit->getTopLevelDecls();
481 for (std::vector<Decl*>::const_iterator it = TLDs.begin(),
482 ie = TLDs.end(); it != ie; ++it) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000483 if (Visit(MakeCXCursor(*it, CXXUnit), true))
Douglas Gregor7b691f332010-01-20 21:13:59 +0000484 return true;
485 }
Douglas Gregor0396f462010-03-19 05:22:59 +0000486 } else if (VisitDeclContext(
487 CXXUnit->getASTContext().getTranslationUnitDecl()))
488 return true;
Bob Wilson3178cb62010-03-19 03:57:57 +0000489
Douglas Gregor0396f462010-03-19 05:22:59 +0000490 // Walk the preprocessing record.
Daniel Dunbar8de30ff2010-03-20 01:11:56 +0000491 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000492 // FIXME: Once we have the ability to deserialize a preprocessing record,
493 // do so.
Douglas Gregor788f5a12010-03-20 00:41:21 +0000494 PreprocessingRecord::iterator E, EEnd;
495 for (llvm::tie(E, EEnd) = getPreprocessedEntities(); E != EEnd; ++E) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000496 if (MacroInstantiation *MI = dyn_cast<MacroInstantiation>(*E)) {
497 if (Visit(MakeMacroInstantiationCursor(MI, CXXUnit)))
498 return true;
Douglas Gregor788f5a12010-03-20 00:41:21 +0000499
Douglas Gregor0396f462010-03-19 05:22:59 +0000500 continue;
501 }
502
503 if (MacroDefinition *MD = dyn_cast<MacroDefinition>(*E)) {
504 if (Visit(MakeMacroDefinitionCursor(MD, CXXUnit)))
505 return true;
506
507 continue;
508 }
509 }
510 }
Douglas Gregor7b691f332010-01-20 21:13:59 +0000511 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000512 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000513
Douglas Gregorb1373d02010-01-20 20:59:29 +0000514 // Nothing to visit at the moment.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000515 return false;
516}
517
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000518bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
519 for (BlockDecl::param_iterator I=B->param_begin(), E=B->param_end(); I!=E;++I)
520 if (Decl *D = *I)
521 if (Visit(D))
522 return true;
523
524 return Visit(MakeCXCursor(B->getBody(), StmtParent, TU));
525}
526
Douglas Gregorb1373d02010-01-20 20:59:29 +0000527bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000528 for (DeclContext::decl_iterator
Douglas Gregorb1373d02010-01-20 20:59:29 +0000529 I = DC->decls_begin(), E = DC->decls_end(); I != E; ++I) {
Ted Kremenek09dfa372010-02-18 05:46:33 +0000530
Daniel Dunbard52864b2010-02-14 10:02:57 +0000531 CXCursor Cursor = MakeCXCursor(*I, TU);
532
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000533 if (RegionOfInterest.isValid()) {
Daniel Dunbard52864b2010-02-14 10:02:57 +0000534 SourceRange Range =
535 cxloc::translateCXSourceRange(clang_getCursorExtent(Cursor));
536 if (Range.isInvalid())
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000537 continue;
Daniel Dunbard52864b2010-02-14 10:02:57 +0000538
539 switch (CompareRegionOfInterest(Range)) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000540 case RangeBefore:
541 // This declaration comes before the region of interest; skip it.
542 continue;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000543
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000544 case RangeAfter:
545 // This declaration comes after the region of interest; we're done.
546 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000547
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000548 case RangeOverlap:
549 // This declaration overlaps the region of interest; visit it.
550 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000551 }
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000552 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000553
Daniel Dunbard52864b2010-02-14 10:02:57 +0000554 if (Visit(Cursor, true))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000555 return true;
556 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000557
Douglas Gregorb1373d02010-01-20 20:59:29 +0000558 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000559}
560
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000561bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
562 llvm_unreachable("Translation units are visited directly by Visit()");
563 return false;
564}
565
566bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
567 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
568 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000569
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000570 return false;
571}
572
573bool CursorVisitor::VisitTagDecl(TagDecl *D) {
574 return VisitDeclContext(D);
575}
576
577bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
578 if (Expr *Init = D->getInitExpr())
579 return Visit(MakeCXCursor(Init, StmtParent, TU));
580 return false;
581}
582
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000583bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
584 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
585 if (Visit(TSInfo->getTypeLoc()))
586 return true;
587
588 return false;
589}
590
Douglas Gregorb1373d02010-01-20 20:59:29 +0000591bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000592 if (VisitDeclaratorDecl(ND))
593 return true;
594
Douglas Gregora59e3902010-01-21 23:27:09 +0000595 if (ND->isThisDeclarationADefinition() &&
596 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
597 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000598
Douglas Gregorb1373d02010-01-20 20:59:29 +0000599 return false;
600}
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000601
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000602bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
603 if (VisitDeclaratorDecl(D))
604 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000605
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000606 if (Expr *BitWidth = D->getBitWidth())
607 return Visit(MakeCXCursor(BitWidth, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000608
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000609 return false;
610}
611
612bool CursorVisitor::VisitVarDecl(VarDecl *D) {
613 if (VisitDeclaratorDecl(D))
614 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000615
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000616 if (Expr *Init = D->getInit())
617 return Visit(MakeCXCursor(Init, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000618
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000619 return false;
620}
621
622bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
Douglas Gregor4bc1cb62010-03-08 14:59:44 +0000623 if (TypeSourceInfo *TSInfo = ND->getResultTypeSourceInfo())
624 if (Visit(TSInfo->getTypeLoc()))
625 return true;
626
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000627 for (ObjCMethodDecl::param_iterator P = ND->param_begin(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000628 PEnd = ND->param_end();
629 P != PEnd; ++P) {
630 if (Visit(MakeCXCursor(*P, TU)))
631 return true;
632 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000633
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000634 if (ND->isThisDeclarationADefinition() &&
635 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
636 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000637
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000638 return false;
639}
640
Douglas Gregora59e3902010-01-21 23:27:09 +0000641bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
642 return VisitDeclContext(D);
643}
644
Douglas Gregorb1373d02010-01-20 20:59:29 +0000645bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000646 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
647 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000648 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000649
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000650 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
651 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
652 E = ND->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000653 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000654 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000655
Douglas Gregora59e3902010-01-21 23:27:09 +0000656 return VisitObjCContainerDecl(ND);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000657}
658
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000659bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
660 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
661 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
662 E = PID->protocol_end(); I != E; ++I, ++PL)
663 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
664 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000665
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000666 return VisitObjCContainerDecl(PID);
667}
668
Douglas Gregorb1373d02010-01-20 20:59:29 +0000669bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000670 // Issue callbacks for super class.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000671 if (D->getSuperClass() &&
672 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000673 D->getSuperClassLoc(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000674 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000675 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000676
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000677 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
678 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
679 E = D->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000680 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000681 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000682
Douglas Gregora59e3902010-01-21 23:27:09 +0000683 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000684}
685
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000686bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
687 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000688}
689
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000690bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
Ted Kremenekebfa3392010-03-19 20:39:03 +0000691 // 'ID' could be null when dealing with invalid code.
692 if (ObjCInterfaceDecl *ID = D->getClassInterface())
693 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
694 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000695
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000696 return VisitObjCImplDecl(D);
697}
698
699bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
700#if 0
701 // Issue callbacks for super class.
702 // FIXME: No source location information!
703 if (D->getSuperClass() &&
704 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000705 D->getSuperClassLoc(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000706 TU)))
707 return true;
708#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000709
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000710 return VisitObjCImplDecl(D);
711}
712
713bool CursorVisitor::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D) {
714 ObjCForwardProtocolDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
715 for (ObjCForwardProtocolDecl::protocol_iterator I = D->protocol_begin(),
716 E = D->protocol_end();
717 I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000718 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000719 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000720
721 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000722}
723
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000724bool CursorVisitor::VisitObjCClassDecl(ObjCClassDecl *D) {
725 for (ObjCClassDecl::iterator C = D->begin(), CEnd = D->end(); C != CEnd; ++C)
726 if (Visit(MakeCursorObjCClassRef(C->getInterface(), C->getLocation(), TU)))
727 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000728
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000729 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000730}
731
Ted Kremenek8f06e0e2010-05-06 23:38:21 +0000732bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
733 return VisitDeclContext(D);
734}
735
Ted Kremeneka0536d82010-05-07 01:04:29 +0000736bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
737 return VisitDeclContext(D);
738}
739
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000740bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
741 ASTContext &Context = TU->getASTContext();
742
743 // Some builtin types (such as Objective-C's "id", "sel", and
744 // "Class") have associated declarations. Create cursors for those.
745 QualType VisitType;
746 switch (TL.getType()->getAs<BuiltinType>()->getKind()) {
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000747 case BuiltinType::Void:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000748 case BuiltinType::Bool:
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000749 case BuiltinType::Char_U:
750 case BuiltinType::UChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000751 case BuiltinType::Char16:
752 case BuiltinType::Char32:
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000753 case BuiltinType::UShort:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000754 case BuiltinType::UInt:
755 case BuiltinType::ULong:
756 case BuiltinType::ULongLong:
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000757 case BuiltinType::UInt128:
758 case BuiltinType::Char_S:
759 case BuiltinType::SChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000760 case BuiltinType::WChar:
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000761 case BuiltinType::Short:
762 case BuiltinType::Int:
763 case BuiltinType::Long:
764 case BuiltinType::LongLong:
765 case BuiltinType::Int128:
766 case BuiltinType::Float:
767 case BuiltinType::Double:
768 case BuiltinType::LongDouble:
769 case BuiltinType::NullPtr:
770 case BuiltinType::Overload:
771 case BuiltinType::Dependent:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000772 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000773
774 case BuiltinType::UndeducedAuto: // FIXME: Deserves a cursor?
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000775 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000776
Ted Kremenekc4174cc2010-02-18 18:52:18 +0000777 case BuiltinType::ObjCId:
778 VisitType = Context.getObjCIdType();
779 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000780
781 case BuiltinType::ObjCClass:
782 VisitType = Context.getObjCClassType();
783 break;
784
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000785 case BuiltinType::ObjCSel:
786 VisitType = Context.getObjCSelType();
787 break;
788 }
789
790 if (!VisitType.isNull()) {
791 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000792 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000793 TU));
794 }
795
796 return false;
797}
798
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000799bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
800 return Visit(MakeCursorTypeRef(TL.getTypedefDecl(), TL.getNameLoc(), TU));
801}
802
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000803bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
804 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
805}
806
807bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
808 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
809}
810
811bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
812 if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
813 return true;
814
John McCallc12c5bb2010-05-15 11:32:37 +0000815 return false;
816}
817
818bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
819 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
820 return true;
821
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000822 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
823 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
824 TU)))
825 return true;
826 }
827
828 return false;
829}
830
831bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
John McCallc12c5bb2010-05-15 11:32:37 +0000832 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000833}
834
835bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
836 return Visit(TL.getPointeeLoc());
837}
838
839bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
840 return Visit(TL.getPointeeLoc());
841}
842
843bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
844 return Visit(TL.getPointeeLoc());
845}
846
847bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000848 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000849}
850
851bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000852 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000853}
854
855bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
856 if (Visit(TL.getResultLoc()))
857 return true;
858
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000859 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
Ted Kremenek5dbacb42010-04-07 00:27:13 +0000860 if (Decl *D = TL.getArg(I))
861 if (Visit(MakeCXCursor(D, TU)))
862 return true;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000863
864 return false;
865}
866
867bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
868 if (Visit(TL.getElementLoc()))
869 return true;
870
871 if (Expr *Size = TL.getSizeExpr())
872 return Visit(MakeCXCursor(Size, StmtParent, TU));
873
874 return false;
875}
876
Douglas Gregor2332c112010-01-21 20:48:56 +0000877bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
878 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
879}
880
881bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
882 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
883 return Visit(TSInfo->getTypeLoc());
884
885 return false;
886}
887
Douglas Gregora59e3902010-01-21 23:27:09 +0000888bool CursorVisitor::VisitStmt(Stmt *S) {
889 for (Stmt::child_iterator Child = S->child_begin(), ChildEnd = S->child_end();
890 Child != ChildEnd; ++Child) {
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000891 if (Stmt *C = *Child)
892 if (Visit(MakeCXCursor(C, StmtParent, TU)))
893 return true;
Douglas Gregora59e3902010-01-21 23:27:09 +0000894 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000895
Douglas Gregora59e3902010-01-21 23:27:09 +0000896 return false;
897}
898
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000899bool CursorVisitor::VisitCaseStmt(CaseStmt *S) {
900 // Specially handle CaseStmts because they can be nested, e.g.:
901 //
902 // case 1:
903 // case 2:
904 //
905 // In this case the second CaseStmt is the child of the first. Walking
906 // these recursively can blow out the stack.
907 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU);
908 while (true) {
909 // Set the Parent field to Cursor, then back to its old value once we're
910 // done.
911 SetParentRAII SetParent(Parent, StmtParent, Cursor);
912
913 if (Stmt *LHS = S->getLHS())
914 if (Visit(MakeCXCursor(LHS, StmtParent, TU)))
915 return true;
916 if (Stmt *RHS = S->getRHS())
917 if (Visit(MakeCXCursor(RHS, StmtParent, TU)))
918 return true;
919 if (Stmt *SubStmt = S->getSubStmt()) {
920 if (!isa<CaseStmt>(SubStmt))
921 return Visit(MakeCXCursor(SubStmt, StmtParent, TU));
922
923 // Specially handle 'CaseStmt' so that we don't blow out the stack.
924 CaseStmt *CS = cast<CaseStmt>(SubStmt);
925 Cursor = MakeCXCursor(CS, StmtParent, TU);
926 if (RegionOfInterest.isValid()) {
927 SourceRange Range = CS->getSourceRange();
928 if (Range.isInvalid() || CompareRegionOfInterest(Range))
929 return false;
930 }
931
932 switch (Visitor(Cursor, Parent, ClientData)) {
933 case CXChildVisit_Break: return true;
934 case CXChildVisit_Continue: return false;
935 case CXChildVisit_Recurse:
936 // Perform tail-recursion manually.
937 S = CS;
938 continue;
939 }
940 }
941 return false;
942 }
943}
944
Douglas Gregora59e3902010-01-21 23:27:09 +0000945bool CursorVisitor::VisitDeclStmt(DeclStmt *S) {
946 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
947 D != DEnd; ++D) {
Douglas Gregor263b47b2010-01-25 16:12:32 +0000948 if (*D && Visit(MakeCXCursor(*D, TU)))
Douglas Gregora59e3902010-01-21 23:27:09 +0000949 return true;
950 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000951
Douglas Gregora59e3902010-01-21 23:27:09 +0000952 return false;
953}
954
Douglas Gregorf5bab412010-01-22 01:00:11 +0000955bool CursorVisitor::VisitIfStmt(IfStmt *S) {
956 if (VarDecl *Var = S->getConditionVariable()) {
957 if (Visit(MakeCXCursor(Var, TU)))
958 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000959 }
960
Douglas Gregor263b47b2010-01-25 16:12:32 +0000961 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
962 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +0000963 if (S->getThen() && Visit(MakeCXCursor(S->getThen(), StmtParent, TU)))
964 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +0000965 if (S->getElse() && Visit(MakeCXCursor(S->getElse(), StmtParent, TU)))
966 return true;
967
968 return false;
969}
970
971bool CursorVisitor::VisitSwitchStmt(SwitchStmt *S) {
972 if (VarDecl *Var = S->getConditionVariable()) {
973 if (Visit(MakeCXCursor(Var, TU)))
974 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000975 }
976
Douglas Gregor263b47b2010-01-25 16:12:32 +0000977 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
978 return true;
979 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
980 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000981
Douglas Gregor263b47b2010-01-25 16:12:32 +0000982 return false;
983}
984
985bool CursorVisitor::VisitWhileStmt(WhileStmt *S) {
986 if (VarDecl *Var = S->getConditionVariable()) {
987 if (Visit(MakeCXCursor(Var, TU)))
988 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000989 }
990
Douglas Gregor263b47b2010-01-25 16:12:32 +0000991 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
992 return true;
993 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
Douglas Gregorf5bab412010-01-22 01:00:11 +0000994 return true;
995
Douglas Gregor263b47b2010-01-25 16:12:32 +0000996 return false;
997}
998
999bool CursorVisitor::VisitForStmt(ForStmt *S) {
1000 if (S->getInit() && Visit(MakeCXCursor(S->getInit(), StmtParent, TU)))
1001 return true;
1002 if (VarDecl *Var = S->getConditionVariable()) {
1003 if (Visit(MakeCXCursor(Var, TU)))
1004 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001005 }
1006
Douglas Gregor263b47b2010-01-25 16:12:32 +00001007 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1008 return true;
1009 if (S->getInc() && Visit(MakeCXCursor(S->getInc(), StmtParent, TU)))
1010 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +00001011 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
1012 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001013
Douglas Gregorf5bab412010-01-22 01:00:11 +00001014 return false;
1015}
1016
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00001017bool CursorVisitor::VisitBlockExpr(BlockExpr *B) {
1018 return Visit(B->getBlockDecl());
1019}
1020
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001021bool CursorVisitor::VisitOffsetOfExpr(OffsetOfExpr *E) {
1022 // FIXME: Visit fields as well?
1023 if (Visit(E->getTypeSourceInfo()->getTypeLoc()))
1024 return true;
1025
1026 return VisitExpr(E);
1027}
1028
Douglas Gregor336fd812010-01-23 00:40:08 +00001029bool CursorVisitor::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E) {
1030 if (E->isArgumentType()) {
1031 if (TypeSourceInfo *TSInfo = E->getArgumentTypeInfo())
1032 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001033
Douglas Gregor336fd812010-01-23 00:40:08 +00001034 return false;
1035 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001036
Douglas Gregor336fd812010-01-23 00:40:08 +00001037 return VisitExpr(E);
1038}
1039
1040bool CursorVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
1041 if (TypeSourceInfo *TSInfo = E->getTypeInfoAsWritten())
1042 if (Visit(TSInfo->getTypeLoc()))
1043 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001044
Douglas Gregor336fd812010-01-23 00:40:08 +00001045 return VisitCastExpr(E);
1046}
1047
1048bool CursorVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
1049 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
1050 if (Visit(TSInfo->getTypeLoc()))
1051 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001052
Douglas Gregor336fd812010-01-23 00:40:08 +00001053 return VisitExpr(E);
1054}
1055
Douglas Gregorc2350e52010-03-08 16:40:19 +00001056bool CursorVisitor::VisitObjCMessageExpr(ObjCMessageExpr *E) {
Douglas Gregor04badcf2010-04-21 00:45:42 +00001057 if (TypeSourceInfo *TSInfo = E->getClassReceiverTypeInfo())
1058 if (Visit(TSInfo->getTypeLoc()))
1059 return true;
Douglas Gregorc2350e52010-03-08 16:40:19 +00001060
1061 return VisitExpr(E);
1062}
1063
Douglas Gregor81d34662010-04-20 15:39:42 +00001064bool CursorVisitor::VisitObjCEncodeExpr(ObjCEncodeExpr *E) {
1065 return Visit(E->getEncodedTypeSourceInfo()->getTypeLoc());
1066}
1067
1068
Ted Kremenek09dfa372010-02-18 05:46:33 +00001069bool CursorVisitor::VisitAttributes(Decl *D) {
1070 for (const Attr *A = D->getAttrs(); A; A = A->getNext())
1071 if (Visit(MakeCXCursor(A, D, TU)))
1072 return true;
1073
1074 return false;
1075}
1076
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00001077extern "C" {
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001078CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
1079 int displayDiagnostics) {
Douglas Gregora030b7c2010-01-22 20:35:53 +00001080 CIndexer *CIdxr = new CIndexer();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001081 if (excludeDeclarationsFromPCH)
1082 CIdxr->setOnlyLocalDecls();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001083 if (displayDiagnostics)
1084 CIdxr->setDisplayDiagnostics();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001085 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +00001086}
1087
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001088void clang_disposeIndex(CXIndex CIdx) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001089 if (CIdx)
1090 delete static_cast<CIndexer *>(CIdx);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00001091}
1092
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001093void clang_setUseExternalASTGeneration(CXIndex CIdx, int value) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001094 if (CIdx) {
1095 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
1096 CXXIdx->setUseExternalASTGeneration(value);
1097 }
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001098}
1099
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001100CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
Douglas Gregora88084b2010-02-18 18:08:43 +00001101 const char *ast_filename) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001102 if (!CIdx)
1103 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001104
Douglas Gregor7d1d49d2009-10-16 20:01:17 +00001105 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001106
Douglas Gregor28019772010-04-05 23:52:57 +00001107 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
1108 return ASTUnit::LoadFromPCHFile(ast_filename, Diags,
Douglas Gregora88084b2010-02-18 18:08:43 +00001109 CXXIdx->getOnlyLocalDecls(),
1110 0, 0, true);
Steve Naroff600866c2009-08-27 19:51:58 +00001111}
1112
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001113CXTranslationUnit
1114clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
1115 const char *source_filename,
1116 int num_command_line_args,
Douglas Gregor4db64a42010-01-23 00:14:00 +00001117 const char **command_line_args,
1118 unsigned num_unsaved_files,
Douglas Gregora88084b2010-02-18 18:08:43 +00001119 struct CXUnsavedFile *unsaved_files) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001120 if (!CIdx)
1121 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001122
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001123 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
1124
Douglas Gregor5352ac02010-01-28 00:27:43 +00001125 // Configure the diagnostics.
1126 DiagnosticOptions DiagOpts;
Douglas Gregor28019772010-04-05 23:52:57 +00001127 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
1128 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001129
Douglas Gregor4db64a42010-01-23 00:14:00 +00001130 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
1131 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattnera0a270c2010-04-05 22:42:27 +00001132 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001133 const llvm::MemoryBuffer *Buffer
Chris Lattnera0a270c2010-04-05 22:42:27 +00001134 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregor4db64a42010-01-23 00:14:00 +00001135 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
1136 Buffer));
1137 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001138
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001139 if (!CXXIdx->getUseExternalASTGeneration()) {
1140 llvm::SmallVector<const char *, 16> Args;
1141
1142 // The 'source_filename' argument is optional. If the caller does not
1143 // specify it then it is assumed that the source file is specified
1144 // in the actual argument list.
1145 if (source_filename)
1146 Args.push_back(source_filename);
1147 Args.insert(Args.end(), command_line_args,
1148 command_line_args + num_command_line_args);
Douglas Gregor94dc8f62010-03-19 16:15:56 +00001149 Args.push_back("-Xclang");
1150 Args.push_back("-detailed-preprocessing-record");
Douglas Gregor5352ac02010-01-28 00:27:43 +00001151 unsigned NumErrors = Diags->getNumErrors();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001152
Ted Kremenek29b72842010-01-07 22:49:05 +00001153#ifdef USE_CRASHTRACER
1154 ArgsCrashTracerInfo ACTI(Args);
Ted Kremenek8a8da7d2010-01-06 03:42:32 +00001155#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001156
Daniel Dunbar94220972009-12-05 02:17:18 +00001157 llvm::OwningPtr<ASTUnit> Unit(
1158 ASTUnit::LoadFromCommandLine(Args.data(), Args.data() + Args.size(),
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001159 Diags,
Daniel Dunbar869824e2009-12-13 03:46:13 +00001160 CXXIdx->getClangResourcesPath(),
Daniel Dunbar94220972009-12-05 02:17:18 +00001161 CXXIdx->getOnlyLocalDecls(),
Douglas Gregor4db64a42010-01-23 00:14:00 +00001162 RemappedFiles.data(),
Douglas Gregora88084b2010-02-18 18:08:43 +00001163 RemappedFiles.size(),
Douglas Gregor94dc8f62010-03-19 16:15:56 +00001164 /*CaptureDiagnostics=*/true));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001165
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001166 if (NumErrors != Diags->getNumErrors()) {
Ted Kremenek34f6a322010-03-05 22:43:29 +00001167 // Make sure to check that 'Unit' is non-NULL.
1168 if (CXXIdx->getDisplayDiagnostics() && Unit.get()) {
Douglas Gregor405634b2010-04-05 18:10:21 +00001169 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
1170 DEnd = Unit->stored_diag_end();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001171 D != DEnd; ++D) {
1172 CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOptions());
Douglas Gregor274f1902010-02-22 23:17:23 +00001173 CXString Msg = clang_formatDiagnostic(&Diag,
1174 clang_defaultDiagnosticDisplayOptions());
1175 fprintf(stderr, "%s\n", clang_getCString(Msg));
1176 clang_disposeString(Msg);
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001177 }
Douglas Gregor274f1902010-02-22 23:17:23 +00001178#ifdef LLVM_ON_WIN32
1179 // On Windows, force a flush, since there may be multiple copies of
1180 // stderr and stdout in the file system, all with different buffers
1181 // but writing to the same device.
1182 fflush(stderr);
Ted Kremenek83c51842010-03-26 01:34:51 +00001183#endif
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001184 }
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001185 }
Daniel Dunbar94220972009-12-05 02:17:18 +00001186
1187 return Unit.take();
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001188 }
1189
Ted Kremenek139ba862009-10-22 00:03:57 +00001190 // Build up the arguments for invoking 'clang'.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001191 std::vector<const char *> argv;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001192
Ted Kremenek139ba862009-10-22 00:03:57 +00001193 // First add the complete path to the 'clang' executable.
1194 llvm::sys::Path ClangPath = static_cast<CIndexer *>(CIdx)->getClangPath();
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00001195 argv.push_back(ClangPath.c_str());
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001196
Ted Kremenek139ba862009-10-22 00:03:57 +00001197 // Add the '-emit-ast' option as our execution mode for 'clang'.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001198 argv.push_back("-emit-ast");
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001199
Ted Kremenek139ba862009-10-22 00:03:57 +00001200 // The 'source_filename' argument is optional. If the caller does not
1201 // specify it then it is assumed that the source file is specified
1202 // in the actual argument list.
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001203 if (source_filename)
1204 argv.push_back(source_filename);
Ted Kremenek139ba862009-10-22 00:03:57 +00001205
Steve Naroff37b5ac22009-10-15 20:50:09 +00001206 // Generate a temporary name for the AST file.
Ted Kremenek139ba862009-10-22 00:03:57 +00001207 argv.push_back("-o");
Benjamin Kramerc2a98162010-03-13 21:22:49 +00001208 char astTmpFile[L_tmpnam];
1209 argv.push_back(tmpnam(astTmpFile));
Ted Kremenek139ba862009-10-22 00:03:57 +00001210
Douglas Gregor4db64a42010-01-23 00:14:00 +00001211 // Remap any unsaved files to temporary files.
1212 std::vector<llvm::sys::Path> TemporaryFiles;
1213 std::vector<std::string> RemapArgs;
1214 if (RemapFiles(num_unsaved_files, unsaved_files, RemapArgs, TemporaryFiles))
1215 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001216
Douglas Gregor4db64a42010-01-23 00:14:00 +00001217 // The pointers into the elements of RemapArgs are stable because we
1218 // won't be adding anything to RemapArgs after this point.
1219 for (unsigned i = 0, e = RemapArgs.size(); i != e; ++i)
1220 argv.push_back(RemapArgs[i].c_str());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001221
Ted Kremenek139ba862009-10-22 00:03:57 +00001222 // Process the compiler options, stripping off '-o', '-c', '-fsyntax-only'.
1223 for (int i = 0; i < num_command_line_args; ++i)
1224 if (const char *arg = command_line_args[i]) {
1225 if (strcmp(arg, "-o") == 0) {
1226 ++i; // Also skip the matching argument.
1227 continue;
1228 }
1229 if (strcmp(arg, "-emit-ast") == 0 ||
1230 strcmp(arg, "-c") == 0 ||
1231 strcmp(arg, "-fsyntax-only") == 0) {
1232 continue;
1233 }
1234
1235 // Keep the argument.
1236 argv.push_back(arg);
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001237 }
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001238
Douglas Gregord93256e2010-01-28 06:00:51 +00001239 // Generate a temporary name for the diagnostics file.
Benjamin Kramerc2a98162010-03-13 21:22:49 +00001240 char tmpFileResults[L_tmpnam];
1241 char *tmpResultsFileName = tmpnam(tmpFileResults);
1242 llvm::sys::Path DiagnosticsFile(tmpResultsFileName);
Douglas Gregord93256e2010-01-28 06:00:51 +00001243 TemporaryFiles.push_back(DiagnosticsFile);
1244 argv.push_back("-fdiagnostics-binary");
1245
Douglas Gregor94dc8f62010-03-19 16:15:56 +00001246 argv.push_back("-Xclang");
1247 argv.push_back("-detailed-preprocessing-record");
1248
Ted Kremenek139ba862009-10-22 00:03:57 +00001249 // Add the null terminator.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001250 argv.push_back(NULL);
1251
Ted Kremenekfeb15e32009-10-26 22:14:08 +00001252 // Invoke 'clang'.
1253 llvm::sys::Path DevNull; // leave empty, causes redirection to /dev/null
1254 // on Unix or NUL (Windows).
Ted Kremenek379afec2009-10-22 03:24:01 +00001255 std::string ErrMsg;
Douglas Gregord93256e2010-01-28 06:00:51 +00001256 const llvm::sys::Path *Redirects[] = { &DevNull, &DevNull, &DiagnosticsFile,
1257 NULL };
Ted Kremenek379afec2009-10-22 03:24:01 +00001258 llvm::sys::Program::ExecuteAndWait(ClangPath, &argv[0], /* env */ NULL,
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001259 /* redirects */ &Redirects[0],
Ted Kremenek379afec2009-10-22 03:24:01 +00001260 /* secondsToWait */ 0, /* memoryLimits */ 0, &ErrMsg);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001261
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001262 if (!ErrMsg.empty()) {
1263 std::string AllArgs;
Ted Kremenek379afec2009-10-22 03:24:01 +00001264 for (std::vector<const char*>::iterator I = argv.begin(), E = argv.end();
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001265 I != E; ++I) {
1266 AllArgs += ' ';
Ted Kremenek779e5f42009-10-26 22:08:39 +00001267 if (*I)
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001268 AllArgs += *I;
Ted Kremenek779e5f42009-10-26 22:08:39 +00001269 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001270
Daniel Dunbar32141c82010-02-23 20:23:45 +00001271 Diags->Report(diag::err_fe_invoking) << AllArgs << ErrMsg;
Ted Kremenek379afec2009-10-22 03:24:01 +00001272 }
Benjamin Kramer0829a832009-10-18 11:19:36 +00001273
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001274 ASTUnit *ATU = ASTUnit::LoadFromPCHFile(astTmpFile, Diags,
Douglas Gregor4db64a42010-01-23 00:14:00 +00001275 CXXIdx->getOnlyLocalDecls(),
Douglas Gregor4db64a42010-01-23 00:14:00 +00001276 RemappedFiles.data(),
Douglas Gregora88084b2010-02-18 18:08:43 +00001277 RemappedFiles.size(),
1278 /*CaptureDiagnostics=*/true);
Douglas Gregora88084b2010-02-18 18:08:43 +00001279 if (ATU) {
1280 LoadSerializedDiagnostics(DiagnosticsFile,
1281 num_unsaved_files, unsaved_files,
1282 ATU->getFileManager(),
1283 ATU->getSourceManager(),
Douglas Gregor405634b2010-04-05 18:10:21 +00001284 ATU->getStoredDiagnostics());
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001285 } else if (CXXIdx->getDisplayDiagnostics()) {
1286 // We failed to load the ASTUnit, but we can still deserialize the
1287 // diagnostics and emit them.
1288 FileManager FileMgr;
Douglas Gregorf715ca12010-03-16 00:06:06 +00001289 Diagnostic Diag;
1290 SourceManager SourceMgr(Diag);
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001291 // FIXME: Faked LangOpts!
1292 LangOptions LangOpts;
1293 llvm::SmallVector<StoredDiagnostic, 4> Diags;
1294 LoadSerializedDiagnostics(DiagnosticsFile,
1295 num_unsaved_files, unsaved_files,
1296 FileMgr, SourceMgr, Diags);
1297 for (llvm::SmallVector<StoredDiagnostic, 4>::iterator D = Diags.begin(),
1298 DEnd = Diags.end();
1299 D != DEnd; ++D) {
1300 CXStoredDiagnostic Diag(*D, LangOpts);
Douglas Gregor274f1902010-02-22 23:17:23 +00001301 CXString Msg = clang_formatDiagnostic(&Diag,
1302 clang_defaultDiagnosticDisplayOptions());
1303 fprintf(stderr, "%s\n", clang_getCString(Msg));
1304 clang_disposeString(Msg);
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001305 }
Douglas Gregor274f1902010-02-22 23:17:23 +00001306
1307#ifdef LLVM_ON_WIN32
1308 // On Windows, force a flush, since there may be multiple copies of
1309 // stderr and stdout in the file system, all with different buffers
1310 // but writing to the same device.
1311 fflush(stderr);
1312#endif
Douglas Gregora88084b2010-02-18 18:08:43 +00001313 }
Douglas Gregord93256e2010-01-28 06:00:51 +00001314
Douglas Gregor313e26c2010-02-18 23:35:40 +00001315 if (ATU) {
1316 // Make the translation unit responsible for destroying all temporary files.
1317 for (unsigned i = 0, e = TemporaryFiles.size(); i != e; ++i)
1318 ATU->addTemporaryFile(TemporaryFiles[i]);
1319 ATU->addTemporaryFile(llvm::sys::Path(ATU->getPCHFileName()));
1320 } else {
1321 // Destroy all of the temporary files now; they can't be referenced any
1322 // longer.
1323 llvm::sys::Path(astTmpFile).eraseFromDisk();
1324 for (unsigned i = 0, e = TemporaryFiles.size(); i != e; ++i)
1325 TemporaryFiles[i].eraseFromDisk();
1326 }
1327
Steve Naroffe19944c2009-10-15 22:23:48 +00001328 return ATU;
Steve Naroff5b7d8e22009-10-15 20:04:39 +00001329}
1330
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001331void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001332 if (CTUnit)
1333 delete static_cast<ASTUnit *>(CTUnit);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00001334}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001335
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001336CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001337 if (!CTUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001338 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001339
Steve Naroff77accc12009-09-03 18:19:54 +00001340 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001341 return createCXString(CXXUnit->getOriginalSourceFileName(), true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +00001342}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +00001343
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001344CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001345 CXCursor Result = { CXCursor_TranslationUnit, { 0, 0, TU } };
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001346 return Result;
1347}
1348
Ted Kremenekfb480492010-01-13 21:46:36 +00001349} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +00001350
Ted Kremenekfb480492010-01-13 21:46:36 +00001351//===----------------------------------------------------------------------===//
Douglas Gregor1db19de2010-01-19 21:36:55 +00001352// CXSourceLocation and CXSourceRange Operations.
1353//===----------------------------------------------------------------------===//
1354
Douglas Gregorb9790342010-01-22 21:44:22 +00001355extern "C" {
1356CXSourceLocation clang_getNullLocation() {
Douglas Gregor5352ac02010-01-28 00:27:43 +00001357 CXSourceLocation Result = { { 0, 0 }, 0 };
Douglas Gregorb9790342010-01-22 21:44:22 +00001358 return Result;
1359}
1360
1361unsigned clang_equalLocations(CXSourceLocation loc1, CXSourceLocation loc2) {
Daniel Dunbar90a6b9e2010-01-30 23:58:27 +00001362 return (loc1.ptr_data[0] == loc2.ptr_data[0] &&
1363 loc1.ptr_data[1] == loc2.ptr_data[1] &&
1364 loc1.int_data == loc2.int_data);
Douglas Gregorb9790342010-01-22 21:44:22 +00001365}
1366
1367CXSourceLocation clang_getLocation(CXTranslationUnit tu,
1368 CXFile file,
1369 unsigned line,
1370 unsigned column) {
Douglas Gregor42748ec2010-04-30 19:45:53 +00001371 if (!tu || !file)
Douglas Gregorb9790342010-01-22 21:44:22 +00001372 return clang_getNullLocation();
Douglas Gregor42748ec2010-04-30 19:45:53 +00001373
Douglas Gregorb9790342010-01-22 21:44:22 +00001374 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
1375 SourceLocation SLoc
1376 = CXXUnit->getSourceManager().getLocation(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001377 static_cast<const FileEntry *>(file),
Douglas Gregorb9790342010-01-22 21:44:22 +00001378 line, column);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001379
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00001380 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
Douglas Gregorb9790342010-01-22 21:44:22 +00001381}
1382
Douglas Gregor5352ac02010-01-28 00:27:43 +00001383CXSourceRange clang_getNullRange() {
1384 CXSourceRange Result = { { 0, 0 }, 0, 0 };
1385 return Result;
1386}
Daniel Dunbard52864b2010-02-14 10:02:57 +00001387
Douglas Gregor5352ac02010-01-28 00:27:43 +00001388CXSourceRange clang_getRange(CXSourceLocation begin, CXSourceLocation end) {
1389 if (begin.ptr_data[0] != end.ptr_data[0] ||
1390 begin.ptr_data[1] != end.ptr_data[1])
1391 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001392
1393 CXSourceRange Result = { { begin.ptr_data[0], begin.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00001394 begin.int_data, end.int_data };
Douglas Gregorb9790342010-01-22 21:44:22 +00001395 return Result;
1396}
1397
Douglas Gregor46766dc2010-01-26 19:19:08 +00001398void clang_getInstantiationLocation(CXSourceLocation location,
1399 CXFile *file,
1400 unsigned *line,
1401 unsigned *column,
1402 unsigned *offset) {
Douglas Gregor1db19de2010-01-19 21:36:55 +00001403 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
1404
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00001405 if (!location.ptr_data[0] || Loc.isInvalid()) {
Douglas Gregor46766dc2010-01-26 19:19:08 +00001406 if (file)
1407 *file = 0;
1408 if (line)
1409 *line = 0;
1410 if (column)
1411 *column = 0;
1412 if (offset)
1413 *offset = 0;
1414 return;
1415 }
1416
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00001417 const SourceManager &SM =
1418 *static_cast<const SourceManager*>(location.ptr_data[0]);
Douglas Gregor1db19de2010-01-19 21:36:55 +00001419 SourceLocation InstLoc = SM.getInstantiationLoc(Loc);
Douglas Gregor1db19de2010-01-19 21:36:55 +00001420
1421 if (file)
1422 *file = (void *)SM.getFileEntryForID(SM.getFileID(InstLoc));
1423 if (line)
1424 *line = SM.getInstantiationLineNumber(InstLoc);
1425 if (column)
1426 *column = SM.getInstantiationColumnNumber(InstLoc);
Douglas Gregore69517c2010-01-26 03:07:15 +00001427 if (offset)
Douglas Gregor46766dc2010-01-26 19:19:08 +00001428 *offset = SM.getDecomposedLoc(InstLoc).second;
Douglas Gregore69517c2010-01-26 03:07:15 +00001429}
1430
Douglas Gregor1db19de2010-01-19 21:36:55 +00001431CXSourceLocation clang_getRangeStart(CXSourceRange range) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001432 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00001433 range.begin_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00001434 return Result;
1435}
1436
1437CXSourceLocation clang_getRangeEnd(CXSourceRange range) {
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00001438 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00001439 range.end_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00001440 return Result;
1441}
1442
Douglas Gregorb9790342010-01-22 21:44:22 +00001443} // end: extern "C"
1444
Douglas Gregor1db19de2010-01-19 21:36:55 +00001445//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00001446// CXFile Operations.
1447//===----------------------------------------------------------------------===//
1448
1449extern "C" {
Ted Kremenek74844072010-02-17 00:41:20 +00001450CXString clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00001451 if (!SFile)
Ted Kremenek74844072010-02-17 00:41:20 +00001452 return createCXString(NULL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001453
Steve Naroff88145032009-10-27 14:35:18 +00001454 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Ted Kremenek74844072010-02-17 00:41:20 +00001455 return createCXString(FEnt->getName());
Steve Naroff88145032009-10-27 14:35:18 +00001456}
1457
1458time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00001459 if (!SFile)
1460 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001461
Steve Naroff88145032009-10-27 14:35:18 +00001462 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
1463 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +00001464}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001465
Douglas Gregorb9790342010-01-22 21:44:22 +00001466CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
1467 if (!tu)
1468 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001469
Douglas Gregorb9790342010-01-22 21:44:22 +00001470 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001471
Douglas Gregorb9790342010-01-22 21:44:22 +00001472 FileManager &FMgr = CXXUnit->getFileManager();
1473 const FileEntry *File = FMgr.getFile(file_name, file_name+strlen(file_name));
1474 return const_cast<FileEntry *>(File);
1475}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001476
Ted Kremenekfb480492010-01-13 21:46:36 +00001477} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +00001478
Ted Kremenekfb480492010-01-13 21:46:36 +00001479//===----------------------------------------------------------------------===//
1480// CXCursor Operations.
1481//===----------------------------------------------------------------------===//
1482
Ted Kremenekfb480492010-01-13 21:46:36 +00001483static Decl *getDeclFromExpr(Stmt *E) {
1484 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
1485 return RefExpr->getDecl();
1486 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
1487 return ME->getMemberDecl();
1488 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
1489 return RE->getDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001490
Ted Kremenekfb480492010-01-13 21:46:36 +00001491 if (CallExpr *CE = dyn_cast<CallExpr>(E))
1492 return getDeclFromExpr(CE->getCallee());
1493 if (CastExpr *CE = dyn_cast<CastExpr>(E))
1494 return getDeclFromExpr(CE->getSubExpr());
1495 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
1496 return OME->getMethodDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001497
Ted Kremenekfb480492010-01-13 21:46:36 +00001498 return 0;
1499}
1500
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00001501static SourceLocation getLocationFromExpr(Expr *E) {
1502 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
1503 return /*FIXME:*/Msg->getLeftLoc();
1504 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
1505 return DRE->getLocation();
1506 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
1507 return Member->getMemberLoc();
1508 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
1509 return Ivar->getLocation();
1510 return E->getLocStart();
1511}
1512
Ted Kremenekfb480492010-01-13 21:46:36 +00001513extern "C" {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001514
1515unsigned clang_visitChildren(CXCursor parent,
Douglas Gregorb1373d02010-01-20 20:59:29 +00001516 CXCursorVisitor visitor,
1517 CXClientData client_data) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001518 ASTUnit *CXXUnit = getCursorASTUnit(parent);
Douglas Gregorb1373d02010-01-20 20:59:29 +00001519
1520 unsigned PCHLevel = Decl::MaxPCHLevel;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001521
Douglas Gregorb1373d02010-01-20 20:59:29 +00001522 // Set the PCHLevel to filter out unwanted decls if requested.
1523 if (CXXUnit->getOnlyLocalDecls()) {
1524 PCHLevel = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001525
Douglas Gregorb1373d02010-01-20 20:59:29 +00001526 // If the main input was an AST, bump the level.
1527 if (CXXUnit->isMainFileAST())
1528 ++PCHLevel;
1529 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001530
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001531 CursorVisitor CursorVis(CXXUnit, visitor, client_data, PCHLevel);
Douglas Gregorb1373d02010-01-20 20:59:29 +00001532 return CursorVis.VisitChildren(parent);
1533}
1534
Douglas Gregor78205d42010-01-20 21:45:58 +00001535static CXString getDeclSpelling(Decl *D) {
1536 NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
1537 if (!ND)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001538 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001539
Douglas Gregor78205d42010-01-20 21:45:58 +00001540 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001541 return createCXString(OMD->getSelector().getAsString());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001542
Douglas Gregor78205d42010-01-20 21:45:58 +00001543 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
1544 // No, this isn't the same as the code below. getIdentifier() is non-virtual
1545 // and returns different names. NamedDecl returns the class name and
1546 // ObjCCategoryImplDecl returns the category name.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001547 return createCXString(CIMP->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001548
Douglas Gregor78205d42010-01-20 21:45:58 +00001549 if (ND->getIdentifier())
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001550 return createCXString(ND->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001551
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001552 return createCXString("");
Douglas Gregor78205d42010-01-20 21:45:58 +00001553}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001554
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001555CXString clang_getCursorSpelling(CXCursor C) {
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001556 if (clang_isTranslationUnit(C.kind))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001557 return clang_getTranslationUnitSpelling(C.data[2]);
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001558
Steve Narofff334b4e2009-09-02 18:26:48 +00001559 if (clang_isReference(C.kind)) {
1560 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00001561 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +00001562 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001563 return createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00001564 }
1565 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +00001566 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001567 return createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00001568 }
1569 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +00001570 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +00001571 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001572 return createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00001573 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001574 case CXCursor_TypeRef: {
1575 TypeDecl *Type = getCursorTypeRef(C).first;
1576 assert(Type && "Missing type decl");
1577
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001578 return createCXString(getCursorContext(C).getTypeDeclType(Type).
1579 getAsString());
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001580 }
1581
Daniel Dunbaracca7252009-11-30 20:42:49 +00001582 default:
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001583 return createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +00001584 }
1585 }
Douglas Gregor97b98722010-01-19 23:20:36 +00001586
1587 if (clang_isExpression(C.kind)) {
1588 Decl *D = getDeclFromExpr(getCursorExpr(C));
1589 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +00001590 return getDeclSpelling(D);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001591 return createCXString("");
Douglas Gregor97b98722010-01-19 23:20:36 +00001592 }
1593
Douglas Gregor4ae8f292010-03-18 17:52:52 +00001594 if (C.kind == CXCursor_MacroInstantiation)
1595 return createCXString(getCursorMacroInstantiation(C)->getName()
1596 ->getNameStart());
1597
Douglas Gregor572feb22010-03-18 18:04:21 +00001598 if (C.kind == CXCursor_MacroDefinition)
1599 return createCXString(getCursorMacroDefinition(C)->getName()
1600 ->getNameStart());
1601
Douglas Gregor60cbfac2010-01-25 16:56:17 +00001602 if (clang_isDeclaration(C.kind))
1603 return getDeclSpelling(getCursorDecl(C));
Ted Kremeneke68fff62010-02-17 00:41:32 +00001604
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001605 return createCXString("");
Steve Narofff334b4e2009-09-02 18:26:48 +00001606}
1607
Ted Kremeneke68fff62010-02-17 00:41:32 +00001608CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00001609 switch (Kind) {
Ted Kremeneke68fff62010-02-17 00:41:32 +00001610 case CXCursor_FunctionDecl:
1611 return createCXString("FunctionDecl");
1612 case CXCursor_TypedefDecl:
1613 return createCXString("TypedefDecl");
1614 case CXCursor_EnumDecl:
1615 return createCXString("EnumDecl");
1616 case CXCursor_EnumConstantDecl:
1617 return createCXString("EnumConstantDecl");
1618 case CXCursor_StructDecl:
1619 return createCXString("StructDecl");
1620 case CXCursor_UnionDecl:
1621 return createCXString("UnionDecl");
1622 case CXCursor_ClassDecl:
1623 return createCXString("ClassDecl");
1624 case CXCursor_FieldDecl:
1625 return createCXString("FieldDecl");
1626 case CXCursor_VarDecl:
1627 return createCXString("VarDecl");
1628 case CXCursor_ParmDecl:
1629 return createCXString("ParmDecl");
1630 case CXCursor_ObjCInterfaceDecl:
1631 return createCXString("ObjCInterfaceDecl");
1632 case CXCursor_ObjCCategoryDecl:
1633 return createCXString("ObjCCategoryDecl");
1634 case CXCursor_ObjCProtocolDecl:
1635 return createCXString("ObjCProtocolDecl");
1636 case CXCursor_ObjCPropertyDecl:
1637 return createCXString("ObjCPropertyDecl");
1638 case CXCursor_ObjCIvarDecl:
1639 return createCXString("ObjCIvarDecl");
1640 case CXCursor_ObjCInstanceMethodDecl:
1641 return createCXString("ObjCInstanceMethodDecl");
1642 case CXCursor_ObjCClassMethodDecl:
1643 return createCXString("ObjCClassMethodDecl");
1644 case CXCursor_ObjCImplementationDecl:
1645 return createCXString("ObjCImplementationDecl");
1646 case CXCursor_ObjCCategoryImplDecl:
1647 return createCXString("ObjCCategoryImplDecl");
Ted Kremenek8bd5a692010-04-13 23:39:06 +00001648 case CXCursor_CXXMethod:
1649 return createCXString("CXXMethod");
Ted Kremeneke68fff62010-02-17 00:41:32 +00001650 case CXCursor_UnexposedDecl:
1651 return createCXString("UnexposedDecl");
1652 case CXCursor_ObjCSuperClassRef:
1653 return createCXString("ObjCSuperClassRef");
1654 case CXCursor_ObjCProtocolRef:
1655 return createCXString("ObjCProtocolRef");
1656 case CXCursor_ObjCClassRef:
1657 return createCXString("ObjCClassRef");
1658 case CXCursor_TypeRef:
1659 return createCXString("TypeRef");
1660 case CXCursor_UnexposedExpr:
1661 return createCXString("UnexposedExpr");
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00001662 case CXCursor_BlockExpr:
1663 return createCXString("BlockExpr");
Ted Kremeneke68fff62010-02-17 00:41:32 +00001664 case CXCursor_DeclRefExpr:
1665 return createCXString("DeclRefExpr");
1666 case CXCursor_MemberRefExpr:
1667 return createCXString("MemberRefExpr");
1668 case CXCursor_CallExpr:
1669 return createCXString("CallExpr");
1670 case CXCursor_ObjCMessageExpr:
1671 return createCXString("ObjCMessageExpr");
1672 case CXCursor_UnexposedStmt:
1673 return createCXString("UnexposedStmt");
1674 case CXCursor_InvalidFile:
1675 return createCXString("InvalidFile");
Ted Kremenek292db642010-03-19 20:39:05 +00001676 case CXCursor_InvalidCode:
1677 return createCXString("InvalidCode");
Ted Kremeneke68fff62010-02-17 00:41:32 +00001678 case CXCursor_NoDeclFound:
1679 return createCXString("NoDeclFound");
1680 case CXCursor_NotImplemented:
1681 return createCXString("NotImplemented");
1682 case CXCursor_TranslationUnit:
1683 return createCXString("TranslationUnit");
Ted Kremeneke77f4432010-02-18 03:09:07 +00001684 case CXCursor_UnexposedAttr:
1685 return createCXString("UnexposedAttr");
1686 case CXCursor_IBActionAttr:
1687 return createCXString("attribute(ibaction)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00001688 case CXCursor_IBOutletAttr:
1689 return createCXString("attribute(iboutlet)");
1690 case CXCursor_PreprocessingDirective:
1691 return createCXString("preprocessing directive");
Douglas Gregor572feb22010-03-18 18:04:21 +00001692 case CXCursor_MacroDefinition:
1693 return createCXString("macro definition");
Douglas Gregor48072312010-03-18 15:23:44 +00001694 case CXCursor_MacroInstantiation:
1695 return createCXString("macro instantiation");
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00001696 case CXCursor_Namespace:
1697 return createCXString("Namespace");
Ted Kremeneka0536d82010-05-07 01:04:29 +00001698 case CXCursor_LinkageSpec:
1699 return createCXString("LinkageSpec");
Steve Naroff89922f82009-08-31 00:59:03 +00001700 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00001701
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00001702 llvm_unreachable("Unhandled CXCursorKind");
Ted Kremeneke68fff62010-02-17 00:41:32 +00001703 return createCXString(NULL);
Steve Naroff600866c2009-08-27 19:51:58 +00001704}
Steve Naroff89922f82009-08-31 00:59:03 +00001705
Ted Kremeneke68fff62010-02-17 00:41:32 +00001706enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
1707 CXCursor parent,
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001708 CXClientData client_data) {
1709 CXCursor *BestCursor = static_cast<CXCursor *>(client_data);
1710 *BestCursor = cursor;
1711 return CXChildVisit_Recurse;
1712}
Ted Kremeneke68fff62010-02-17 00:41:32 +00001713
Douglas Gregorb9790342010-01-22 21:44:22 +00001714CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
1715 if (!TU)
Ted Kremenekf4629892010-01-14 01:51:23 +00001716 return clang_getNullCursor();
Ted Kremeneke68fff62010-02-17 00:41:32 +00001717
Douglas Gregorb9790342010-01-22 21:44:22 +00001718 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
1719
Douglas Gregorbdf60622010-03-05 21:16:25 +00001720 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
1721
Ted Kremeneka297de22010-01-25 22:34:44 +00001722 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001723 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
1724 if (SLoc.isValid()) {
Daniel Dunbard52864b2010-02-14 10:02:57 +00001725 SourceRange RegionOfInterest(SLoc, SLoc.getFileLocWithOffset(1));
Ted Kremeneke68fff62010-02-17 00:41:32 +00001726
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001727 // FIXME: Would be great to have a "hint" cursor, then walk from that
1728 // hint cursor upward until we find a cursor whose source range encloses
1729 // the region of interest, rather than starting from the translation unit.
1730 CXCursor Parent = clang_getTranslationUnitCursor(CXXUnit);
Ted Kremeneke68fff62010-02-17 00:41:32 +00001731 CursorVisitor CursorVis(CXXUnit, GetCursorVisitor, &Result,
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001732 Decl::MaxPCHLevel, RegionOfInterest);
1733 CursorVis.VisitChildren(Parent);
Steve Naroff77128dd2009-09-15 20:25:34 +00001734 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00001735 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00001736}
1737
Ted Kremenek73885552009-11-17 19:28:59 +00001738CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00001739 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00001740}
1741
1742unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00001743 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00001744}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001745
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001746unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00001747 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
1748}
1749
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001750unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +00001751 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
1752}
Steve Naroff2d4d6292009-08-31 14:26:51 +00001753
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001754unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00001755 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
1756}
1757
Douglas Gregor97b98722010-01-19 23:20:36 +00001758unsigned clang_isExpression(enum CXCursorKind K) {
1759 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
1760}
1761
1762unsigned clang_isStatement(enum CXCursorKind K) {
1763 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
1764}
1765
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001766unsigned clang_isTranslationUnit(enum CXCursorKind K) {
1767 return K == CXCursor_TranslationUnit;
1768}
1769
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00001770unsigned clang_isPreprocessing(enum CXCursorKind K) {
1771 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
1772}
1773
Ted Kremenekad6eff62010-03-08 21:17:29 +00001774unsigned clang_isUnexposed(enum CXCursorKind K) {
1775 switch (K) {
1776 case CXCursor_UnexposedDecl:
1777 case CXCursor_UnexposedExpr:
1778 case CXCursor_UnexposedStmt:
1779 case CXCursor_UnexposedAttr:
1780 return true;
1781 default:
1782 return false;
1783 }
1784}
1785
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001786CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00001787 return C.kind;
1788}
1789
Douglas Gregor98258af2010-01-18 22:46:11 +00001790CXSourceLocation clang_getCursorLocation(CXCursor C) {
1791 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00001792 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001793 case CXCursor_ObjCSuperClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00001794 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1795 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001796 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001797 }
1798
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001799 case CXCursor_ObjCProtocolRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00001800 std::pair<ObjCProtocolDecl *, SourceLocation> P
1801 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001802 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001803 }
1804
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001805 case CXCursor_ObjCClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00001806 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1807 = getCursorObjCClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001808 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001809 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001810
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001811 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001812 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001813 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001814 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001815
Douglas Gregorf46034a2010-01-18 23:41:10 +00001816 default:
1817 // FIXME: Need a way to enumerate all non-reference cases.
1818 llvm_unreachable("Missed a reference kind");
1819 }
Douglas Gregor98258af2010-01-18 22:46:11 +00001820 }
Douglas Gregor97b98722010-01-19 23:20:36 +00001821
1822 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001823 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00001824 getLocationFromExpr(getCursorExpr(C)));
1825
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00001826 if (C.kind == CXCursor_PreprocessingDirective) {
1827 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
1828 return cxloc::translateSourceLocation(getCursorContext(C), L);
1829 }
Douglas Gregor48072312010-03-18 15:23:44 +00001830
1831 if (C.kind == CXCursor_MacroInstantiation) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00001832 SourceLocation L
1833 = cxcursor::getCursorMacroInstantiation(C)->getSourceRange().getBegin();
Douglas Gregor48072312010-03-18 15:23:44 +00001834 return cxloc::translateSourceLocation(getCursorContext(C), L);
1835 }
Douglas Gregor572feb22010-03-18 18:04:21 +00001836
1837 if (C.kind == CXCursor_MacroDefinition) {
1838 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
1839 return cxloc::translateSourceLocation(getCursorContext(C), L);
1840 }
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00001841
Ted Kremenek9a700d22010-05-12 06:16:13 +00001842 if (C.kind < CXCursor_FirstDecl || C.kind > CXCursor_LastDecl)
Douglas Gregor5352ac02010-01-28 00:27:43 +00001843 return clang_getNullLocation();
Douglas Gregor98258af2010-01-18 22:46:11 +00001844
Douglas Gregorf46034a2010-01-18 23:41:10 +00001845 Decl *D = getCursorDecl(C);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001846 SourceLocation Loc = D->getLocation();
1847 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
1848 Loc = Class->getClassLoc();
Douglas Gregor2ca54fe2010-03-22 15:53:50 +00001849 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00001850}
Douglas Gregora7bde202010-01-19 00:34:46 +00001851
1852CXSourceRange clang_getCursorExtent(CXCursor C) {
1853 if (clang_isReference(C.kind)) {
1854 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001855 case CXCursor_ObjCSuperClassRef: {
Douglas Gregora7bde202010-01-19 00:34:46 +00001856 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1857 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001858 return cxloc::translateSourceRange(P.first->getASTContext(), P.second);
Douglas Gregora7bde202010-01-19 00:34:46 +00001859 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001860
1861 case CXCursor_ObjCProtocolRef: {
Douglas Gregora7bde202010-01-19 00:34:46 +00001862 std::pair<ObjCProtocolDecl *, SourceLocation> P
1863 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001864 return cxloc::translateSourceRange(P.first->getASTContext(), P.second);
Douglas Gregora7bde202010-01-19 00:34:46 +00001865 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001866
1867 case CXCursor_ObjCClassRef: {
Douglas Gregora7bde202010-01-19 00:34:46 +00001868 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1869 = getCursorObjCClassRef(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001870
Ted Kremeneka297de22010-01-25 22:34:44 +00001871 return cxloc::translateSourceRange(P.first->getASTContext(), P.second);
Douglas Gregora7bde202010-01-19 00:34:46 +00001872 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001873
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001874 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001875 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001876 return cxloc::translateSourceRange(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001877 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001878
Douglas Gregora7bde202010-01-19 00:34:46 +00001879 default:
1880 // FIXME: Need a way to enumerate all non-reference cases.
1881 llvm_unreachable("Missed a reference kind");
1882 }
1883 }
Douglas Gregor97b98722010-01-19 23:20:36 +00001884
1885 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001886 return cxloc::translateSourceRange(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00001887 getCursorExpr(C)->getSourceRange());
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001888
1889 if (clang_isStatement(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001890 return cxloc::translateSourceRange(getCursorContext(C),
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001891 getCursorStmt(C)->getSourceRange());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001892
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00001893 if (C.kind == CXCursor_PreprocessingDirective) {
1894 SourceRange R = cxcursor::getCursorPreprocessingDirective(C);
1895 return cxloc::translateSourceRange(getCursorContext(C), R);
1896 }
Douglas Gregor48072312010-03-18 15:23:44 +00001897
1898 if (C.kind == CXCursor_MacroInstantiation) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00001899 SourceRange R = cxcursor::getCursorMacroInstantiation(C)->getSourceRange();
Douglas Gregor48072312010-03-18 15:23:44 +00001900 return cxloc::translateSourceRange(getCursorContext(C), R);
1901 }
Douglas Gregor572feb22010-03-18 18:04:21 +00001902
1903 if (C.kind == CXCursor_MacroDefinition) {
1904 SourceRange R = cxcursor::getCursorMacroDefinition(C)->getSourceRange();
1905 return cxloc::translateSourceRange(getCursorContext(C), R);
1906 }
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00001907
Ted Kremenek9a700d22010-05-12 06:16:13 +00001908 if (C.kind < CXCursor_FirstDecl || C.kind > CXCursor_LastDecl)
Douglas Gregor5352ac02010-01-28 00:27:43 +00001909 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001910
Douglas Gregora7bde202010-01-19 00:34:46 +00001911 Decl *D = getCursorDecl(C);
Douglas Gregor2ca54fe2010-03-22 15:53:50 +00001912 return cxloc::translateSourceRange(getCursorContext(C), D->getSourceRange());
Douglas Gregora7bde202010-01-19 00:34:46 +00001913}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001914
1915CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001916 if (clang_isInvalid(C.kind))
1917 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001918
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001919 ASTUnit *CXXUnit = getCursorASTUnit(C);
Douglas Gregorb6998662010-01-19 19:34:47 +00001920 if (clang_isDeclaration(C.kind))
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001921 return C;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001922
Douglas Gregor97b98722010-01-19 23:20:36 +00001923 if (clang_isExpression(C.kind)) {
1924 Decl *D = getDeclFromExpr(getCursorExpr(C));
1925 if (D)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001926 return MakeCXCursor(D, CXXUnit);
Douglas Gregor97b98722010-01-19 23:20:36 +00001927 return clang_getNullCursor();
1928 }
1929
Douglas Gregorbf7efa22010-03-18 18:23:03 +00001930 if (C.kind == CXCursor_MacroInstantiation) {
1931 if (MacroDefinition *Def = getCursorMacroInstantiation(C)->getDefinition())
1932 return MakeMacroDefinitionCursor(Def, CXXUnit);
1933 }
1934
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001935 if (!clang_isReference(C.kind))
1936 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001937
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001938 switch (C.kind) {
1939 case CXCursor_ObjCSuperClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001940 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001941
1942 case CXCursor_ObjCProtocolRef: {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001943 return MakeCXCursor(getCursorObjCProtocolRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001944
1945 case CXCursor_ObjCClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001946 return MakeCXCursor(getCursorObjCClassRef(C).first, CXXUnit);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001947
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001948 case CXCursor_TypeRef:
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001949 return MakeCXCursor(getCursorTypeRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001950
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001951 default:
1952 // We would prefer to enumerate all non-reference cursor kinds here.
1953 llvm_unreachable("Unhandled reference cursor kind");
1954 break;
1955 }
1956 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001957
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001958 return clang_getNullCursor();
1959}
1960
Douglas Gregorb6998662010-01-19 19:34:47 +00001961CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001962 if (clang_isInvalid(C.kind))
1963 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001964
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001965 ASTUnit *CXXUnit = getCursorASTUnit(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001966
Douglas Gregorb6998662010-01-19 19:34:47 +00001967 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00001968 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00001969 C = clang_getCursorReferenced(C);
1970 WasReference = true;
1971 }
1972
Douglas Gregorbf7efa22010-03-18 18:23:03 +00001973 if (C.kind == CXCursor_MacroInstantiation)
1974 return clang_getCursorReferenced(C);
1975
Douglas Gregorb6998662010-01-19 19:34:47 +00001976 if (!clang_isDeclaration(C.kind))
1977 return clang_getNullCursor();
1978
1979 Decl *D = getCursorDecl(C);
1980 if (!D)
1981 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001982
Douglas Gregorb6998662010-01-19 19:34:47 +00001983 switch (D->getKind()) {
1984 // Declaration kinds that don't really separate the notions of
1985 // declaration and definition.
1986 case Decl::Namespace:
1987 case Decl::Typedef:
1988 case Decl::TemplateTypeParm:
1989 case Decl::EnumConstant:
1990 case Decl::Field:
1991 case Decl::ObjCIvar:
1992 case Decl::ObjCAtDefsField:
1993 case Decl::ImplicitParam:
1994 case Decl::ParmVar:
1995 case Decl::NonTypeTemplateParm:
1996 case Decl::TemplateTemplateParm:
1997 case Decl::ObjCCategoryImpl:
1998 case Decl::ObjCImplementation:
1999 case Decl::LinkageSpec:
2000 case Decl::ObjCPropertyImpl:
2001 case Decl::FileScopeAsm:
2002 case Decl::StaticAssert:
2003 case Decl::Block:
2004 return C;
2005
2006 // Declaration kinds that don't make any sense here, but are
2007 // nonetheless harmless.
2008 case Decl::TranslationUnit:
Douglas Gregorb6998662010-01-19 19:34:47 +00002009 break;
2010
2011 // Declaration kinds for which the definition is not resolvable.
2012 case Decl::UnresolvedUsingTypename:
2013 case Decl::UnresolvedUsingValue:
2014 break;
2015
2016 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002017 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
2018 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002019
2020 case Decl::NamespaceAlias:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002021 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002022
2023 case Decl::Enum:
2024 case Decl::Record:
2025 case Decl::CXXRecord:
2026 case Decl::ClassTemplateSpecialization:
2027 case Decl::ClassTemplatePartialSpecialization:
Douglas Gregor952b0172010-02-11 01:04:33 +00002028 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002029 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002030 return clang_getNullCursor();
2031
2032 case Decl::Function:
2033 case Decl::CXXMethod:
2034 case Decl::CXXConstructor:
2035 case Decl::CXXDestructor:
2036 case Decl::CXXConversion: {
2037 const FunctionDecl *Def = 0;
2038 if (cast<FunctionDecl>(D)->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002039 return MakeCXCursor(const_cast<FunctionDecl *>(Def), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002040 return clang_getNullCursor();
2041 }
2042
2043 case Decl::Var: {
Sebastian Redl31310a22010-02-01 20:16:42 +00002044 // Ask the variable if it has a definition.
2045 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
2046 return MakeCXCursor(Def, CXXUnit);
2047 return clang_getNullCursor();
Douglas Gregorb6998662010-01-19 19:34:47 +00002048 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002049
Douglas Gregorb6998662010-01-19 19:34:47 +00002050 case Decl::FunctionTemplate: {
2051 const FunctionDecl *Def = 0;
2052 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002053 return MakeCXCursor(Def->getDescribedFunctionTemplate(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002054 return clang_getNullCursor();
2055 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002056
Douglas Gregorb6998662010-01-19 19:34:47 +00002057 case Decl::ClassTemplate: {
2058 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
Douglas Gregor952b0172010-02-11 01:04:33 +00002059 ->getDefinition())
Douglas Gregorb6998662010-01-19 19:34:47 +00002060 return MakeCXCursor(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002061 cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002062 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002063 return clang_getNullCursor();
2064 }
2065
2066 case Decl::Using: {
2067 UsingDecl *Using = cast<UsingDecl>(D);
2068 CXCursor Def = clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002069 for (UsingDecl::shadow_iterator S = Using->shadow_begin(),
2070 SEnd = Using->shadow_end();
Douglas Gregorb6998662010-01-19 19:34:47 +00002071 S != SEnd; ++S) {
2072 if (Def != clang_getNullCursor()) {
2073 // FIXME: We have no way to return multiple results.
2074 return clang_getNullCursor();
2075 }
2076
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002077 Def = clang_getCursorDefinition(MakeCXCursor((*S)->getTargetDecl(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002078 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002079 }
2080
2081 return Def;
2082 }
2083
2084 case Decl::UsingShadow:
2085 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002086 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002087 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002088
2089 case Decl::ObjCMethod: {
2090 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
2091 if (Method->isThisDeclarationADefinition())
2092 return C;
2093
2094 // Dig out the method definition in the associated
2095 // @implementation, if we have it.
2096 // FIXME: The ASTs should make finding the definition easier.
2097 if (ObjCInterfaceDecl *Class
2098 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
2099 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
2100 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
2101 Method->isInstanceMethod()))
2102 if (Def->isThisDeclarationADefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002103 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002104
2105 return clang_getNullCursor();
2106 }
2107
2108 case Decl::ObjCCategory:
2109 if (ObjCCategoryImplDecl *Impl
2110 = cast<ObjCCategoryDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002111 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002112 return clang_getNullCursor();
2113
2114 case Decl::ObjCProtocol:
2115 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
2116 return C;
2117 return clang_getNullCursor();
2118
2119 case Decl::ObjCInterface:
2120 // There are two notions of a "definition" for an Objective-C
2121 // class: the interface and its implementation. When we resolved a
2122 // reference to an Objective-C class, produce the @interface as
2123 // the definition; when we were provided with the interface,
2124 // produce the @implementation as the definition.
2125 if (WasReference) {
2126 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
2127 return C;
2128 } else if (ObjCImplementationDecl *Impl
2129 = cast<ObjCInterfaceDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002130 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002131 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002132
Douglas Gregorb6998662010-01-19 19:34:47 +00002133 case Decl::ObjCProperty:
2134 // FIXME: We don't really know where to find the
2135 // ObjCPropertyImplDecls that implement this property.
2136 return clang_getNullCursor();
2137
2138 case Decl::ObjCCompatibleAlias:
2139 if (ObjCInterfaceDecl *Class
2140 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
2141 if (!Class->isForwardDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002142 return MakeCXCursor(Class, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002143
Douglas Gregorb6998662010-01-19 19:34:47 +00002144 return clang_getNullCursor();
2145
2146 case Decl::ObjCForwardProtocol: {
2147 ObjCForwardProtocolDecl *Forward = cast<ObjCForwardProtocolDecl>(D);
2148 if (Forward->protocol_size() == 1)
2149 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002150 MakeCXCursor(*Forward->protocol_begin(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002151 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002152
2153 // FIXME: Cannot return multiple definitions.
2154 return clang_getNullCursor();
2155 }
2156
2157 case Decl::ObjCClass: {
2158 ObjCClassDecl *Class = cast<ObjCClassDecl>(D);
2159 if (Class->size() == 1) {
2160 ObjCInterfaceDecl *IFace = Class->begin()->getInterface();
2161 if (!IFace->isForwardDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002162 return MakeCXCursor(IFace, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002163 return clang_getNullCursor();
2164 }
2165
2166 // FIXME: Cannot return multiple definitions.
2167 return clang_getNullCursor();
2168 }
2169
2170 case Decl::Friend:
2171 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002172 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002173 return clang_getNullCursor();
2174
2175 case Decl::FriendTemplate:
2176 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002177 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002178 return clang_getNullCursor();
2179 }
2180
2181 return clang_getNullCursor();
2182}
2183
2184unsigned clang_isCursorDefinition(CXCursor C) {
2185 if (!clang_isDeclaration(C.kind))
2186 return 0;
2187
2188 return clang_getCursorDefinition(C) == C;
2189}
2190
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002191void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00002192 const char **startBuf,
2193 const char **endBuf,
2194 unsigned *startLine,
2195 unsigned *startColumn,
2196 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002197 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00002198 assert(getCursorDecl(C) && "CXCursor has null decl");
2199 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00002200 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
2201 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002202
Steve Naroff4ade6d62009-09-23 17:52:52 +00002203 SourceManager &SM = FD->getASTContext().getSourceManager();
2204 *startBuf = SM.getCharacterData(Body->getLBracLoc());
2205 *endBuf = SM.getCharacterData(Body->getRBracLoc());
2206 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
2207 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
2208 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
2209 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
2210}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002211
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002212void clang_enableStackTraces(void) {
2213 llvm::sys::PrintStackTraceOnErrorSignal();
2214}
2215
Ted Kremenekfb480492010-01-13 21:46:36 +00002216} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00002217
Ted Kremenekfb480492010-01-13 21:46:36 +00002218//===----------------------------------------------------------------------===//
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002219// Token-based Operations.
2220//===----------------------------------------------------------------------===//
2221
2222/* CXToken layout:
2223 * int_data[0]: a CXTokenKind
2224 * int_data[1]: starting token location
2225 * int_data[2]: token length
2226 * int_data[3]: reserved
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002227 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002228 * otherwise unused.
2229 */
2230extern "C" {
2231
2232CXTokenKind clang_getTokenKind(CXToken CXTok) {
2233 return static_cast<CXTokenKind>(CXTok.int_data[0]);
2234}
2235
2236CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
2237 switch (clang_getTokenKind(CXTok)) {
2238 case CXToken_Identifier:
2239 case CXToken_Keyword:
2240 // We know we have an IdentifierInfo*, so use that.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002241 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
2242 ->getNameStart());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002243
2244 case CXToken_Literal: {
2245 // We have stashed the starting pointer in the ptr_data field. Use it.
2246 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002247 return createCXString(llvm::StringRef(Text, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002248 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002249
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002250 case CXToken_Punctuation:
2251 case CXToken_Comment:
2252 break;
2253 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002254
2255 // We have to find the starting buffer pointer the hard way, by
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002256 // deconstructing the source location.
2257 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2258 if (!CXXUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002259 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002260
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002261 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
2262 std::pair<FileID, unsigned> LocInfo
2263 = CXXUnit->getSourceManager().getDecomposedLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +00002264 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002265 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00002266 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
2267 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00002268 return createCXString("");
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002269
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002270 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002271}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002272
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002273CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
2274 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2275 if (!CXXUnit)
2276 return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002277
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002278 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
2279 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
2280}
2281
2282CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
2283 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregor5352ac02010-01-28 00:27:43 +00002284 if (!CXXUnit)
2285 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002286
2287 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002288 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
2289}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002290
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002291void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
2292 CXToken **Tokens, unsigned *NumTokens) {
2293 if (Tokens)
2294 *Tokens = 0;
2295 if (NumTokens)
2296 *NumTokens = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002297
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002298 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2299 if (!CXXUnit || !Tokens || !NumTokens)
2300 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002301
Douglas Gregorbdf60622010-03-05 21:16:25 +00002302 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
2303
Daniel Dunbar85b988f2010-02-14 08:31:57 +00002304 SourceRange R = cxloc::translateCXSourceRange(Range);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002305 if (R.isInvalid())
2306 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002307
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002308 SourceManager &SourceMgr = CXXUnit->getSourceManager();
2309 std::pair<FileID, unsigned> BeginLocInfo
2310 = SourceMgr.getDecomposedLoc(R.getBegin());
2311 std::pair<FileID, unsigned> EndLocInfo
2312 = SourceMgr.getDecomposedLoc(R.getEnd());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002313
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002314 // Cannot tokenize across files.
2315 if (BeginLocInfo.first != EndLocInfo.first)
2316 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002317
2318 // Create a lexer
Douglas Gregorf715ca12010-03-16 00:06:06 +00002319 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002320 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00002321 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
Douglas Gregor47a3fcd2010-03-16 20:26:15 +00002322 if (Invalid)
2323 return;
Douglas Gregoraea67db2010-03-15 22:54:52 +00002324
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002325 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
2326 CXXUnit->getASTContext().getLangOptions(),
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002327 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002328 Lex.SetCommentRetentionState(true);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002329
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002330 // Lex tokens until we hit the end of the range.
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002331 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002332 llvm::SmallVector<CXToken, 32> CXTokens;
2333 Token Tok;
2334 do {
2335 // Lex the next token
2336 Lex.LexFromRawLexer(Tok);
2337 if (Tok.is(tok::eof))
2338 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002339
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002340 // Initialize the CXToken.
2341 CXToken CXTok;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002342
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002343 // - Common fields
2344 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
2345 CXTok.int_data[2] = Tok.getLength();
2346 CXTok.int_data[3] = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002347
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002348 // - Kind-specific fields
2349 if (Tok.isLiteral()) {
2350 CXTok.int_data[0] = CXToken_Literal;
2351 CXTok.ptr_data = (void *)Tok.getLiteralData();
2352 } else if (Tok.is(tok::identifier)) {
Douglas Gregoraea67db2010-03-15 22:54:52 +00002353 // Lookup the identifier to determine whether we have a keyword.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002354 std::pair<FileID, unsigned> LocInfo
2355 = SourceMgr.getDecomposedLoc(Tok.getLocation());
Douglas Gregorf715ca12010-03-16 00:06:06 +00002356 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002357 llvm::StringRef Buf
Douglas Gregorf715ca12010-03-16 00:06:06 +00002358 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
2359 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00002360 return;
2361
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002362 const char *StartPos = Buf.data() + LocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002363 IdentifierInfo *II
2364 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok, StartPos);
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00002365
2366 if (II->getObjCKeywordID() != tok::objc_not_keyword) {
2367 CXTok.int_data[0] = CXToken_Keyword;
2368 }
2369 else {
2370 CXTok.int_data[0] = II->getTokenID() == tok::identifier?
2371 CXToken_Identifier
2372 : CXToken_Keyword;
2373 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002374 CXTok.ptr_data = II;
2375 } else if (Tok.is(tok::comment)) {
2376 CXTok.int_data[0] = CXToken_Comment;
2377 CXTok.ptr_data = 0;
2378 } else {
2379 CXTok.int_data[0] = CXToken_Punctuation;
2380 CXTok.ptr_data = 0;
2381 }
2382 CXTokens.push_back(CXTok);
2383 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002384
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002385 if (CXTokens.empty())
2386 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002387
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002388 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
2389 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
2390 *NumTokens = CXTokens.size();
2391}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002392
Ted Kremenek6db61092010-05-05 00:55:15 +00002393void clang_disposeTokens(CXTranslationUnit TU,
2394 CXToken *Tokens, unsigned NumTokens) {
2395 free(Tokens);
2396}
2397
2398} // end: extern "C"
2399
2400//===----------------------------------------------------------------------===//
2401// Token annotation APIs.
2402//===----------------------------------------------------------------------===//
2403
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002404typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002405static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
2406 CXCursor parent,
2407 CXClientData client_data);
Ted Kremenek6db61092010-05-05 00:55:15 +00002408namespace {
2409class AnnotateTokensWorker {
2410 AnnotateTokensData &Annotated;
Ted Kremenek11949cb2010-05-05 00:55:17 +00002411 CXToken *Tokens;
2412 CXCursor *Cursors;
2413 unsigned NumTokens;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002414 unsigned TokIdx;
2415 CursorVisitor AnnotateVis;
2416 SourceManager &SrcMgr;
2417
2418 bool MoreTokens() const { return TokIdx < NumTokens; }
2419 unsigned NextToken() const { return TokIdx; }
2420 void AdvanceToken() { ++TokIdx; }
2421 SourceLocation GetTokenLoc(unsigned tokI) {
2422 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
2423 }
2424
Ted Kremenek6db61092010-05-05 00:55:15 +00002425public:
Ted Kremenek11949cb2010-05-05 00:55:17 +00002426 AnnotateTokensWorker(AnnotateTokensData &annotated,
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002427 CXToken *tokens, CXCursor *cursors, unsigned numTokens,
2428 ASTUnit *CXXUnit, SourceRange RegionOfInterest)
Ted Kremenek11949cb2010-05-05 00:55:17 +00002429 : Annotated(annotated), Tokens(tokens), Cursors(cursors),
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002430 NumTokens(numTokens), TokIdx(0),
2431 AnnotateVis(CXXUnit, AnnotateTokensVisitor, this,
2432 Decl::MaxPCHLevel, RegionOfInterest),
2433 SrcMgr(CXXUnit->getSourceManager()) {}
Ted Kremenek11949cb2010-05-05 00:55:17 +00002434
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002435 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
Ted Kremenek6db61092010-05-05 00:55:15 +00002436 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002437 void AnnotateTokens(CXCursor parent);
Ted Kremenek6db61092010-05-05 00:55:15 +00002438};
2439}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002440
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002441void AnnotateTokensWorker::AnnotateTokens(CXCursor parent) {
2442 // Walk the AST within the region of interest, annotating tokens
2443 // along the way.
2444 VisitChildren(parent);
Ted Kremenek11949cb2010-05-05 00:55:17 +00002445
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002446 for (unsigned I = 0 ; I < TokIdx ; ++I) {
2447 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
2448 if (Pos != Annotated.end())
2449 Cursors[I] = Pos->second;
2450 }
2451
2452 // Finish up annotating any tokens left.
2453 if (!MoreTokens())
2454 return;
2455
2456 const CXCursor &C = clang_getNullCursor();
2457 for (unsigned I = TokIdx ; I < NumTokens ; ++I) {
2458 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
2459 Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second;
Ted Kremenek11949cb2010-05-05 00:55:17 +00002460 }
2461}
2462
Ted Kremenek6db61092010-05-05 00:55:15 +00002463enum CXChildVisitResult
2464AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002465 CXSourceLocation Loc = clang_getCursorLocation(cursor);
2466 // We can always annotate a preprocessing directive/macro instantiation.
2467 if (clang_isPreprocessing(cursor.kind)) {
2468 Annotated[Loc.int_data] = cursor;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002469 return CXChildVisit_Recurse;
2470 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002471
2472 CXSourceRange cursorExtent = clang_getCursorExtent(cursor);
2473 SourceRange cursorRange = cxloc::translateCXSourceRange(cursorExtent);
Ted Kremeneka333c662010-05-12 05:29:33 +00002474
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002475 if (cursorRange.isInvalid())
2476 return CXChildVisit_Continue;
Ted Kremeneka333c662010-05-12 05:29:33 +00002477
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002478 SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data);
2479
Ted Kremeneka333c662010-05-12 05:29:33 +00002480 // Adjust the annotated range based specific declarations.
2481 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
2482 if (cursorK >= CXCursor_FirstDecl && cursorK <= CXCursor_LastDecl) {
2483 if (const DeclaratorDecl *DD =
2484 dyn_cast<DeclaratorDecl>(cxcursor::getCursorDecl(cursor))) {
2485 if (TypeSourceInfo *TI = DD->getTypeSourceInfo()) {
2486 TypeLoc TL = TI->getTypeLoc();
2487 SourceLocation TLoc = TL.getFullSourceRange().getBegin();
Ted Kremenek6bfd5332010-05-13 15:38:38 +00002488 if (TLoc.isValid() &&
2489 SrcMgr.isBeforeInTranslationUnit(TLoc, L))
Ted Kremeneka333c662010-05-12 05:29:33 +00002490 cursorRange.setBegin(TLoc);
Ted Kremeneka333c662010-05-12 05:29:33 +00002491 }
2492 }
2493 }
2494
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002495 const enum CXCursorKind K = clang_getCursorKind(parent);
2496 const CXCursor updateC =
2497 (clang_isInvalid(K) || K == CXCursor_TranslationUnit ||
2498 L.isMacroID())
2499 ? clang_getNullCursor() : parent;
2500
2501 while (MoreTokens()) {
2502 const unsigned I = NextToken();
2503 SourceLocation TokLoc = GetTokenLoc(I);
2504 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
2505 case RangeBefore:
2506 Cursors[I] = updateC;
2507 AdvanceToken();
2508 continue;
2509 case RangeAfter:
2510 return CXChildVisit_Continue;
2511 case RangeOverlap:
2512 break;
2513 }
2514 break;
2515 }
2516
2517 // Visit children to get their cursor information.
2518 const unsigned BeforeChildren = NextToken();
2519 VisitChildren(cursor);
2520 const unsigned AfterChildren = NextToken();
2521
2522 // Adjust 'Last' to the last token within the extent of the cursor.
2523 while (MoreTokens()) {
2524 const unsigned I = NextToken();
2525 SourceLocation TokLoc = GetTokenLoc(I);
2526 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
2527 case RangeBefore:
2528 assert(0 && "Infeasible");
2529 case RangeAfter:
2530 break;
2531 case RangeOverlap:
2532 Cursors[I] = updateC;
2533 AdvanceToken();
2534 continue;
2535 }
2536 break;
2537 }
2538 const unsigned Last = NextToken();
Ted Kremenek6db61092010-05-05 00:55:15 +00002539
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002540 // Scan the tokens that are at the beginning of the cursor, but are not
2541 // capture by the child cursors.
2542
2543 // For AST elements within macros, rely on a post-annotate pass to
2544 // to correctly annotate the tokens with cursors. Otherwise we can
2545 // get confusing results of having tokens that map to cursors that really
2546 // are expanded by an instantiation.
2547 if (L.isMacroID())
2548 cursor = clang_getNullCursor();
2549
2550 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
2551 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
2552 break;
2553 Cursors[I] = cursor;
2554 }
2555 // Scan the tokens that are at the end of the cursor, but are not captured
2556 // but the child cursors.
2557 for (unsigned I = AfterChildren; I != Last; ++I)
2558 Cursors[I] = cursor;
2559
2560 TokIdx = Last;
2561 return CXChildVisit_Continue;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002562}
2563
Ted Kremenek6db61092010-05-05 00:55:15 +00002564static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
2565 CXCursor parent,
2566 CXClientData client_data) {
2567 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
2568}
2569
2570extern "C" {
2571
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002572void clang_annotateTokens(CXTranslationUnit TU,
2573 CXToken *Tokens, unsigned NumTokens,
2574 CXCursor *Cursors) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002575
2576 if (NumTokens == 0 || !Tokens || !Cursors)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002577 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002578
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002579 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002580 if (!CXXUnit) {
2581 // Any token we don't specifically annotate will have a NULL cursor.
2582 const CXCursor &C = clang_getNullCursor();
2583 for (unsigned I = 0; I != NumTokens; ++I)
2584 Cursors[I] = C;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002585 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002586 }
2587
Douglas Gregorbdf60622010-03-05 21:16:25 +00002588 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002589
Douglas Gregor0396f462010-03-19 05:22:59 +00002590 // Determine the region of interest, which contains all of the tokens.
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002591 SourceRange RegionOfInterest;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002592 RegionOfInterest.setBegin(cxloc::translateSourceLocation(
2593 clang_getTokenLocation(TU, Tokens[0])));
2594
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002595 SourceLocation End
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002596 = cxloc::translateSourceLocation(clang_getTokenLocation(TU,
2597 Tokens[NumTokens - 1]));
Daniel Dunbard52864b2010-02-14 10:02:57 +00002598 RegionOfInterest.setEnd(CXXUnit->getPreprocessor().getLocForEndOfToken(End));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002599
Douglas Gregor0396f462010-03-19 05:22:59 +00002600 // A mapping from the source locations found when re-lexing or traversing the
2601 // region of interest to the corresponding cursors.
2602 AnnotateTokensData Annotated;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002603
2604 // Relex the tokens within the source range to look for preprocessing
Douglas Gregor0396f462010-03-19 05:22:59 +00002605 // directives.
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002606 SourceManager &SourceMgr = CXXUnit->getSourceManager();
2607 std::pair<FileID, unsigned> BeginLocInfo
2608 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
2609 std::pair<FileID, unsigned> EndLocInfo
2610 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002611
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002612 llvm::StringRef Buffer;
Douglas Gregor0396f462010-03-19 05:22:59 +00002613 bool Invalid = false;
2614 if (BeginLocInfo.first == EndLocInfo.first &&
2615 ((Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid)),true) &&
2616 !Invalid) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002617 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
2618 CXXUnit->getASTContext().getLangOptions(),
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002619 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002620 Buffer.end());
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002621 Lex.SetCommentRetentionState(true);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002622
2623 // Lex tokens in raw mode until we hit the end of the range, to avoid
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002624 // entering #includes or expanding macros.
Douglas Gregor48072312010-03-18 15:23:44 +00002625 while (true) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002626 Token Tok;
2627 Lex.LexFromRawLexer(Tok);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002628
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002629 reprocess:
2630 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
2631 // We have found a preprocessing directive. Gobble it up so that we
2632 // don't see it while preprocessing these tokens later, but keep track of
2633 // all of the token locations inside this preprocessing directive so that
2634 // we can annotate them appropriately.
2635 //
2636 // FIXME: Some simple tests here could identify macro definitions and
2637 // #undefs, to provide specific cursor kinds for those.
2638 std::vector<SourceLocation> Locations;
2639 do {
2640 Locations.push_back(Tok.getLocation());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002641 Lex.LexFromRawLexer(Tok);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002642 } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002643
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002644 using namespace cxcursor;
2645 CXCursor Cursor
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002646 = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
2647 Locations.back()),
Ted Kremenek6db61092010-05-05 00:55:15 +00002648 CXXUnit);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002649 for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
2650 Annotated[Locations[I].getRawEncoding()] = Cursor;
2651 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002652
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002653 if (Tok.isAtStartOfLine())
2654 goto reprocess;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002655
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002656 continue;
2657 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002658
Douglas Gregor48072312010-03-18 15:23:44 +00002659 if (Tok.is(tok::eof))
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002660 break;
2661 }
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002662 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002663
Douglas Gregor0396f462010-03-19 05:22:59 +00002664 // Annotate all of the source locations in the region of interest that map to
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002665 // a specific cursor.
2666 AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens,
2667 CXXUnit, RegionOfInterest);
2668 W.AnnotateTokens(clang_getTranslationUnitCursor(CXXUnit));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002669}
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002670} // end: extern "C"
2671
2672//===----------------------------------------------------------------------===//
Ted Kremenek16b42592010-03-03 06:36:57 +00002673// Operations for querying linkage of a cursor.
2674//===----------------------------------------------------------------------===//
2675
2676extern "C" {
2677CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
Douglas Gregor0396f462010-03-19 05:22:59 +00002678 if (!clang_isDeclaration(cursor.kind))
2679 return CXLinkage_Invalid;
2680
Ted Kremenek16b42592010-03-03 06:36:57 +00002681 Decl *D = cxcursor::getCursorDecl(cursor);
2682 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
2683 switch (ND->getLinkage()) {
2684 case NoLinkage: return CXLinkage_NoLinkage;
2685 case InternalLinkage: return CXLinkage_Internal;
2686 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
2687 case ExternalLinkage: return CXLinkage_External;
2688 };
2689
2690 return CXLinkage_Invalid;
2691}
2692} // end: extern "C"
2693
2694//===----------------------------------------------------------------------===//
Ted Kremenek45e1dae2010-04-12 21:22:16 +00002695// Operations for querying language of a cursor.
2696//===----------------------------------------------------------------------===//
2697
2698static CXLanguageKind getDeclLanguage(const Decl *D) {
2699 switch (D->getKind()) {
2700 default:
2701 break;
2702 case Decl::ImplicitParam:
2703 case Decl::ObjCAtDefsField:
2704 case Decl::ObjCCategory:
2705 case Decl::ObjCCategoryImpl:
2706 case Decl::ObjCClass:
2707 case Decl::ObjCCompatibleAlias:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00002708 case Decl::ObjCForwardProtocol:
2709 case Decl::ObjCImplementation:
2710 case Decl::ObjCInterface:
2711 case Decl::ObjCIvar:
2712 case Decl::ObjCMethod:
2713 case Decl::ObjCProperty:
2714 case Decl::ObjCPropertyImpl:
2715 case Decl::ObjCProtocol:
2716 return CXLanguage_ObjC;
2717 case Decl::CXXConstructor:
2718 case Decl::CXXConversion:
2719 case Decl::CXXDestructor:
2720 case Decl::CXXMethod:
2721 case Decl::CXXRecord:
2722 case Decl::ClassTemplate:
2723 case Decl::ClassTemplatePartialSpecialization:
2724 case Decl::ClassTemplateSpecialization:
2725 case Decl::Friend:
2726 case Decl::FriendTemplate:
2727 case Decl::FunctionTemplate:
2728 case Decl::LinkageSpec:
2729 case Decl::Namespace:
2730 case Decl::NamespaceAlias:
2731 case Decl::NonTypeTemplateParm:
2732 case Decl::StaticAssert:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00002733 case Decl::TemplateTemplateParm:
2734 case Decl::TemplateTypeParm:
2735 case Decl::UnresolvedUsingTypename:
2736 case Decl::UnresolvedUsingValue:
2737 case Decl::Using:
2738 case Decl::UsingDirective:
2739 case Decl::UsingShadow:
2740 return CXLanguage_CPlusPlus;
2741 }
2742
2743 return CXLanguage_C;
2744}
2745
2746extern "C" {
2747CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
2748 if (clang_isDeclaration(cursor.kind))
2749 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
2750
2751 return CXLanguage_Invalid;
2752}
2753} // end: extern "C"
2754
Ted Kremenek9ada39a2010-05-17 20:06:56 +00002755
2756//===----------------------------------------------------------------------===//
2757// C++ AST instrospection.
2758//===----------------------------------------------------------------------===//
2759
2760extern "C" {
2761unsigned clang_CXXMethod_isStatic(CXCursor C) {
2762 if (!clang_isDeclaration(C.kind))
2763 return 0;
2764 CXXMethodDecl *D = dyn_cast<CXXMethodDecl>(cxcursor::getCursorDecl(C));
2765 return (D && D->isStatic()) ? 1 : 0;
2766} // end: extern "C"
2767
Ted Kremenek45e1dae2010-04-12 21:22:16 +00002768//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00002769// CXString Operations.
2770//===----------------------------------------------------------------------===//
2771
2772extern "C" {
2773const char *clang_getCString(CXString string) {
2774 return string.Spelling;
2775}
2776
2777void clang_disposeString(CXString string) {
2778 if (string.MustFreeString && string.Spelling)
2779 free((void*)string.Spelling);
2780}
Ted Kremenek04bb7162010-01-22 22:44:15 +00002781
Ted Kremenekfb480492010-01-13 21:46:36 +00002782} // end: extern "C"
Ted Kremenek04bb7162010-01-22 22:44:15 +00002783
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002784namespace clang { namespace cxstring {
2785CXString createCXString(const char *String, bool DupString){
2786 CXString Str;
2787 if (DupString) {
2788 Str.Spelling = strdup(String);
2789 Str.MustFreeString = 1;
2790 } else {
2791 Str.Spelling = String;
2792 Str.MustFreeString = 0;
2793 }
2794 return Str;
2795}
2796
2797CXString createCXString(llvm::StringRef String, bool DupString) {
2798 CXString Result;
2799 if (DupString || (!String.empty() && String.data()[String.size()] != 0)) {
2800 char *Spelling = (char *)malloc(String.size() + 1);
2801 memmove(Spelling, String.data(), String.size());
2802 Spelling[String.size()] = 0;
2803 Result.Spelling = Spelling;
2804 Result.MustFreeString = 1;
2805 } else {
2806 Result.Spelling = String.data();
2807 Result.MustFreeString = 0;
2808 }
2809 return Result;
2810}
2811}}
2812
Ted Kremenek04bb7162010-01-22 22:44:15 +00002813//===----------------------------------------------------------------------===//
2814// Misc. utility functions.
2815//===----------------------------------------------------------------------===//
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002816
Ted Kremenek04bb7162010-01-22 22:44:15 +00002817extern "C" {
2818
Ted Kremeneka2a9d6e2010-02-12 22:54:40 +00002819CXString clang_getClangVersion() {
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002820 return createCXString(getClangFullVersion());
Ted Kremenek04bb7162010-01-22 22:44:15 +00002821}
2822
2823} // end: extern "C"