blob: efc61a06451b95479cc6cfe03f422589065577d7 [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
Ted Kremenekd7ffd082010-05-22 00:06:46 +000047#ifdef USE_CRASHTRACER
Ted Kremenek8a8da7d2010-01-06 03:42:32 +000048#include "clang/Analysis/Support/SaveAndRestore.h"
49// Integrate with crash reporter.
Daniel Dunbar439794e2010-05-20 23:50:23 +000050static const char *__crashreporter_info__ = 0;
51asm(".desc ___crashreporter_info__, 0x10");
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,
Chris Lattner0a76aae2010-06-18 22:45:06 +0000180 const CharSourceRange &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();
Chris Lattner0a76aae2010-06-18 22:45:06 +0000185 if (R.isTokenRange() && !EndLoc.isInvalid() && EndLoc.isFileID()) {
Douglas Gregor6a5a23f2010-03-19 21:51:54 +0000186 unsigned Length = Lexer::MeasureTokenLength(EndLoc, SM, LangOpts);
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000187 EndLoc = EndLoc.getFileLocWithOffset(Length);
188 }
189
190 CXSourceRange Result = { { (void *)&SM, (void *)&LangOpts },
191 R.getBegin().getRawEncoding(),
192 EndLoc.getRawEncoding() };
193 return Result;
194}
Douglas Gregor1db19de2010-01-19 21:36:55 +0000195
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000196//===----------------------------------------------------------------------===//
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000197// Cursor visitor.
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000198//===----------------------------------------------------------------------===//
199
Steve Naroff89922f82009-08-31 00:59:03 +0000200namespace {
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000201
Douglas Gregorb1373d02010-01-20 20:59:29 +0000202// Cursor visitor.
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000203class CursorVisitor : public DeclVisitor<CursorVisitor, bool>,
Douglas Gregora59e3902010-01-21 23:27:09 +0000204 public TypeLocVisitor<CursorVisitor, bool>,
205 public StmtVisitor<CursorVisitor, bool>
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000206{
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000207 /// \brief The translation unit we are traversing.
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000208 ASTUnit *TU;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000209
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000210 /// \brief The parent cursor whose children we are traversing.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000211 CXCursor Parent;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000212
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000213 /// \brief The declaration that serves at the parent of any statement or
214 /// expression nodes.
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000215 Decl *StmtParent;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000216
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000217 /// \brief The visitor function.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000218 CXCursorVisitor Visitor;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000219
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000220 /// \brief The opaque client data, to be passed along to the visitor.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000221 CXClientData ClientData;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000222
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000223 // MaxPCHLevel - the maximum PCH level of declarations that we will pass on
224 // to the visitor. Declarations with a PCH level greater than this value will
225 // be suppressed.
226 unsigned MaxPCHLevel;
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000227
228 /// \brief When valid, a source range to which the cursor should restrict
229 /// its search.
230 SourceRange RegionOfInterest;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000231
Douglas Gregorb1373d02010-01-20 20:59:29 +0000232 using DeclVisitor<CursorVisitor, bool>::Visit;
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000233 using TypeLocVisitor<CursorVisitor, bool>::Visit;
Douglas Gregora59e3902010-01-21 23:27:09 +0000234 using StmtVisitor<CursorVisitor, bool>::Visit;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000235
236 /// \brief Determine whether this particular source range comes before, comes
237 /// after, or overlaps the region of interest.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000238 ///
Daniel Dunbard52864b2010-02-14 10:02:57 +0000239 /// \param R a half-open source range retrieved from the abstract syntax tree.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000240 RangeComparisonResult CompareRegionOfInterest(SourceRange R);
241
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000242 class SetParentRAII {
243 CXCursor &Parent;
244 Decl *&StmtParent;
245 CXCursor OldParent;
246
247 public:
248 SetParentRAII(CXCursor &Parent, Decl *&StmtParent, CXCursor NewParent)
249 : Parent(Parent), StmtParent(StmtParent), OldParent(Parent)
250 {
251 Parent = NewParent;
252 if (clang_isDeclaration(Parent.kind))
253 StmtParent = getCursorDecl(Parent);
254 }
255
256 ~SetParentRAII() {
257 Parent = OldParent;
258 if (clang_isDeclaration(Parent.kind))
259 StmtParent = getCursorDecl(Parent);
260 }
261 };
262
Steve Naroff89922f82009-08-31 00:59:03 +0000263public:
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000264 CursorVisitor(ASTUnit *TU, CXCursorVisitor Visitor, CXClientData ClientData,
265 unsigned MaxPCHLevel,
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000266 SourceRange RegionOfInterest = SourceRange())
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000267 : TU(TU), Visitor(Visitor), ClientData(ClientData),
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000268 MaxPCHLevel(MaxPCHLevel), RegionOfInterest(RegionOfInterest)
Douglas Gregorb1373d02010-01-20 20:59:29 +0000269 {
270 Parent.kind = CXCursor_NoDeclFound;
271 Parent.data[0] = 0;
272 Parent.data[1] = 0;
273 Parent.data[2] = 0;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000274 StmtParent = 0;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000275 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000276
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000277 bool Visit(CXCursor Cursor, bool CheckedRegionOfInterest = false);
Douglas Gregor788f5a12010-03-20 00:41:21 +0000278
279 std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
280 getPreprocessedEntities();
281
Douglas Gregorb1373d02010-01-20 20:59:29 +0000282 bool VisitChildren(CXCursor Parent);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000283
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000284 // Declaration visitors
Ted Kremenek09dfa372010-02-18 05:46:33 +0000285 bool VisitAttributes(Decl *D);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000286 bool VisitBlockDecl(BlockDecl *B);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000287 bool VisitDeclContext(DeclContext *DC);
Ted Kremenek4540c9c2010-02-18 18:47:08 +0000288 bool VisitTranslationUnitDecl(TranslationUnitDecl *D);
289 bool VisitTypedefDecl(TypedefDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000290 bool VisitTagDecl(TagDecl *D);
291 bool VisitEnumConstantDecl(EnumConstantDecl *D);
292 bool VisitDeclaratorDecl(DeclaratorDecl *DD);
293 bool VisitFunctionDecl(FunctionDecl *ND);
294 bool VisitFieldDecl(FieldDecl *D);
Ted Kremenek4540c9c2010-02-18 18:47:08 +0000295 bool VisitVarDecl(VarDecl *);
Ted Kremenek79758f62010-02-18 22:36:18 +0000296 bool VisitObjCMethodDecl(ObjCMethodDecl *ND);
297 bool VisitObjCContainerDecl(ObjCContainerDecl *D);
298 bool VisitObjCCategoryDecl(ObjCCategoryDecl *ND);
299 bool VisitObjCProtocolDecl(ObjCProtocolDecl *PID);
Ted Kremenek23173d72010-05-18 21:09:07 +0000300 bool VisitObjCPropertyDecl(ObjCPropertyDecl *PD);
Ted Kremenek79758f62010-02-18 22:36:18 +0000301 bool VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
302 bool VisitObjCImplDecl(ObjCImplDecl *D);
303 bool VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
304 bool VisitObjCImplementationDecl(ObjCImplementationDecl *D);
305 // FIXME: ObjCPropertyDecl requires TypeSourceInfo, getter/setter locations,
306 // etc.
307 // FIXME: ObjCCompatibleAliasDecl requires aliased-class locations.
308 bool VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D);
309 bool VisitObjCClassDecl(ObjCClassDecl *D);
Ted Kremeneka0536d82010-05-07 01:04:29 +0000310 bool VisitLinkageSpecDecl(LinkageSpecDecl *D);
Ted Kremenek8f06e0e2010-05-06 23:38:21 +0000311 bool VisitNamespaceDecl(NamespaceDecl *D);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000312
313 // Type visitors
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000314 // FIXME: QualifiedTypeLoc doesn't provide any location information
315 bool VisitBuiltinTypeLoc(BuiltinTypeLoc TL);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000316 bool VisitTypedefTypeLoc(TypedefTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000317 bool VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL);
318 bool VisitTagTypeLoc(TagTypeLoc TL);
319 // FIXME: TemplateTypeParmTypeLoc doesn't provide any location information
320 bool VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL);
John McCallc12c5bb2010-05-15 11:32:37 +0000321 bool VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000322 bool VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL);
323 bool VisitPointerTypeLoc(PointerTypeLoc TL);
324 bool VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL);
325 bool VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL);
326 bool VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL);
327 bool VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL);
328 bool VisitFunctionTypeLoc(FunctionTypeLoc TL);
329 bool VisitArrayTypeLoc(ArrayTypeLoc TL);
Douglas Gregor2332c112010-01-21 20:48:56 +0000330 // FIXME: Implement for TemplateSpecializationTypeLoc
331 // FIXME: Implement visitors here when the unimplemented TypeLocs get
332 // implemented
333 bool VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL);
334 bool VisitTypeOfTypeLoc(TypeOfTypeLoc TL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000335
Douglas Gregora59e3902010-01-21 23:27:09 +0000336 // Statement visitors
337 bool VisitStmt(Stmt *S);
338 bool VisitDeclStmt(DeclStmt *S);
Douglas Gregorf5bab412010-01-22 01:00:11 +0000339 // FIXME: LabelStmt label?
340 bool VisitIfStmt(IfStmt *S);
341 bool VisitSwitchStmt(SwitchStmt *S);
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000342 bool VisitCaseStmt(CaseStmt *S);
Douglas Gregor263b47b2010-01-25 16:12:32 +0000343 bool VisitWhileStmt(WhileStmt *S);
344 bool VisitForStmt(ForStmt *S);
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000345// bool VisitSwitchCase(SwitchCase *S);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000346
Douglas Gregor336fd812010-01-23 00:40:08 +0000347 // Expression visitors
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000348 bool VisitBlockExpr(BlockExpr *B);
Douglas Gregor336fd812010-01-23 00:40:08 +0000349 bool VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000350 bool VisitExplicitCastExpr(ExplicitCastExpr *E);
Douglas Gregorc2350e52010-03-08 16:40:19 +0000351 bool VisitObjCMessageExpr(ObjCMessageExpr *E);
Douglas Gregor81d34662010-04-20 15:39:42 +0000352 bool VisitObjCEncodeExpr(ObjCEncodeExpr *E);
Douglas Gregor8ecdb652010-04-28 22:16:22 +0000353 bool VisitOffsetOfExpr(OffsetOfExpr *E);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000354 bool VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E);
Steve Naroff89922f82009-08-31 00:59:03 +0000355};
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000356
Ted Kremenekab188932010-01-05 19:32:54 +0000357} // end anonymous namespace
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000358
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000359RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000360 return RangeCompare(TU->getSourceManager(), R, RegionOfInterest);
361}
362
Douglas Gregorb1373d02010-01-20 20:59:29 +0000363/// \brief Visit the given cursor and, if requested by the visitor,
364/// its children.
365///
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000366/// \param Cursor the cursor to visit.
367///
368/// \param CheckRegionOfInterest if true, then the caller already checked that
369/// this cursor is within the region of interest.
370///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000371/// \returns true if the visitation should be aborted, false if it
372/// should continue.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000373bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
Douglas Gregorb1373d02010-01-20 20:59:29 +0000374 if (clang_isInvalid(Cursor.kind))
375 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000376
Douglas Gregorb1373d02010-01-20 20:59:29 +0000377 if (clang_isDeclaration(Cursor.kind)) {
378 Decl *D = getCursorDecl(Cursor);
379 assert(D && "Invalid declaration cursor");
380 if (D->getPCHLevel() > MaxPCHLevel)
381 return false;
382
383 if (D->isImplicit())
384 return false;
385 }
386
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000387 // If we have a range of interest, and this cursor doesn't intersect with it,
388 // we're done.
389 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
Daniel Dunbarf408f322010-02-14 08:32:05 +0000390 SourceRange Range =
391 cxloc::translateCXSourceRange(clang_getCursorExtent(Cursor));
392 if (Range.isInvalid() || CompareRegionOfInterest(Range))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000393 return false;
394 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000395
Douglas Gregorb1373d02010-01-20 20:59:29 +0000396 switch (Visitor(Cursor, Parent, ClientData)) {
397 case CXChildVisit_Break:
398 return true;
399
400 case CXChildVisit_Continue:
401 return false;
402
403 case CXChildVisit_Recurse:
404 return VisitChildren(Cursor);
405 }
406
Douglas Gregorfd643772010-01-25 16:45:46 +0000407 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000408}
409
Douglas Gregor788f5a12010-03-20 00:41:21 +0000410std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
411CursorVisitor::getPreprocessedEntities() {
412 PreprocessingRecord &PPRec
413 = *TU->getPreprocessor().getPreprocessingRecord();
414
415 bool OnlyLocalDecls
416 = !TU->isMainFileAST() && TU->getOnlyLocalDecls();
417
418 // There is no region of interest; we have to walk everything.
419 if (RegionOfInterest.isInvalid())
420 return std::make_pair(PPRec.begin(OnlyLocalDecls),
421 PPRec.end(OnlyLocalDecls));
422
423 // Find the file in which the region of interest lands.
424 SourceManager &SM = TU->getSourceManager();
425 std::pair<FileID, unsigned> Begin
426 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getBegin());
427 std::pair<FileID, unsigned> End
428 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getEnd());
429
430 // The region of interest spans files; we have to walk everything.
431 if (Begin.first != End.first)
432 return std::make_pair(PPRec.begin(OnlyLocalDecls),
433 PPRec.end(OnlyLocalDecls));
434
435 ASTUnit::PreprocessedEntitiesByFileMap &ByFileMap
436 = TU->getPreprocessedEntitiesByFile();
437 if (ByFileMap.empty()) {
438 // Build the mapping from files to sets of preprocessed entities.
439 for (PreprocessingRecord::iterator E = PPRec.begin(OnlyLocalDecls),
440 EEnd = PPRec.end(OnlyLocalDecls);
441 E != EEnd; ++E) {
442 std::pair<FileID, unsigned> P
443 = SM.getDecomposedInstantiationLoc((*E)->getSourceRange().getBegin());
444 ByFileMap[P.first].push_back(*E);
445 }
446 }
447
448 return std::make_pair(ByFileMap[Begin.first].begin(),
449 ByFileMap[Begin.first].end());
450}
451
Douglas Gregorb1373d02010-01-20 20:59:29 +0000452/// \brief Visit the children of the given cursor.
453///
454/// \returns true if the visitation should be aborted, false if it
455/// should continue.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000456bool CursorVisitor::VisitChildren(CXCursor Cursor) {
Douglas Gregora59e3902010-01-21 23:27:09 +0000457 if (clang_isReference(Cursor.kind)) {
458 // By definition, references have no children.
459 return false;
460 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000461
462 // Set the Parent field to Cursor, then back to its old value once we're
Douglas Gregorb1373d02010-01-20 20:59:29 +0000463 // done.
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000464 SetParentRAII SetParent(Parent, StmtParent, Cursor);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000465
Douglas Gregorb1373d02010-01-20 20:59:29 +0000466 if (clang_isDeclaration(Cursor.kind)) {
467 Decl *D = getCursorDecl(Cursor);
468 assert(D && "Invalid declaration cursor");
Ted Kremenek539311e2010-02-18 18:47:01 +0000469 return VisitAttributes(D) || Visit(D);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000470 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000471
Douglas Gregora59e3902010-01-21 23:27:09 +0000472 if (clang_isStatement(Cursor.kind))
473 return Visit(getCursorStmt(Cursor));
474 if (clang_isExpression(Cursor.kind))
475 return Visit(getCursorExpr(Cursor));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000476
Douglas Gregorb1373d02010-01-20 20:59:29 +0000477 if (clang_isTranslationUnit(Cursor.kind)) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000478 ASTUnit *CXXUnit = getCursorASTUnit(Cursor);
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000479 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
480 RegionOfInterest.isInvalid()) {
Douglas Gregor7b691f332010-01-20 21:13:59 +0000481 const std::vector<Decl*> &TLDs = CXXUnit->getTopLevelDecls();
482 for (std::vector<Decl*>::const_iterator it = TLDs.begin(),
483 ie = TLDs.end(); it != ie; ++it) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000484 if (Visit(MakeCXCursor(*it, CXXUnit), true))
Douglas Gregor7b691f332010-01-20 21:13:59 +0000485 return true;
486 }
Douglas Gregor0396f462010-03-19 05:22:59 +0000487 } else if (VisitDeclContext(
488 CXXUnit->getASTContext().getTranslationUnitDecl()))
489 return true;
Bob Wilson3178cb62010-03-19 03:57:57 +0000490
Douglas Gregor0396f462010-03-19 05:22:59 +0000491 // Walk the preprocessing record.
Daniel Dunbar8de30ff2010-03-20 01:11:56 +0000492 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000493 // FIXME: Once we have the ability to deserialize a preprocessing record,
494 // do so.
Douglas Gregor788f5a12010-03-20 00:41:21 +0000495 PreprocessingRecord::iterator E, EEnd;
496 for (llvm::tie(E, EEnd) = getPreprocessedEntities(); E != EEnd; ++E) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000497 if (MacroInstantiation *MI = dyn_cast<MacroInstantiation>(*E)) {
498 if (Visit(MakeMacroInstantiationCursor(MI, CXXUnit)))
499 return true;
Douglas Gregor788f5a12010-03-20 00:41:21 +0000500
Douglas Gregor0396f462010-03-19 05:22:59 +0000501 continue;
502 }
503
504 if (MacroDefinition *MD = dyn_cast<MacroDefinition>(*E)) {
505 if (Visit(MakeMacroDefinitionCursor(MD, CXXUnit)))
506 return true;
507
508 continue;
509 }
510 }
511 }
Douglas Gregor7b691f332010-01-20 21:13:59 +0000512 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000513 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000514
Douglas Gregorb1373d02010-01-20 20:59:29 +0000515 // Nothing to visit at the moment.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000516 return false;
517}
518
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000519bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
John McCallfc929202010-06-04 22:33:30 +0000520 if (Visit(B->getSignatureAsWritten()->getTypeLoc()))
521 return true;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000522
523 return Visit(MakeCXCursor(B->getBody(), StmtParent, TU));
524}
525
Douglas Gregorb1373d02010-01-20 20:59:29 +0000526bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000527 for (DeclContext::decl_iterator
Douglas Gregorb1373d02010-01-20 20:59:29 +0000528 I = DC->decls_begin(), E = DC->decls_end(); I != E; ++I) {
Ted Kremenek09dfa372010-02-18 05:46:33 +0000529
Ted Kremenek23173d72010-05-18 21:09:07 +0000530 Decl *D = *I;
531 if (D->getLexicalDeclContext() != DC)
532 continue;
533
534 CXCursor Cursor = MakeCXCursor(D, TU);
Daniel Dunbard52864b2010-02-14 10:02:57 +0000535
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000536 if (RegionOfInterest.isValid()) {
Daniel Dunbard52864b2010-02-14 10:02:57 +0000537 SourceRange Range =
538 cxloc::translateCXSourceRange(clang_getCursorExtent(Cursor));
539 if (Range.isInvalid())
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000540 continue;
Daniel Dunbard52864b2010-02-14 10:02:57 +0000541
542 switch (CompareRegionOfInterest(Range)) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000543 case RangeBefore:
544 // This declaration comes before the region of interest; skip it.
545 continue;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000546
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000547 case RangeAfter:
548 // This declaration comes after the region of interest; we're done.
549 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000550
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000551 case RangeOverlap:
552 // This declaration overlaps the region of interest; visit it.
553 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000554 }
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000555 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000556
Daniel Dunbard52864b2010-02-14 10:02:57 +0000557 if (Visit(Cursor, true))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000558 return true;
559 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000560
Douglas Gregorb1373d02010-01-20 20:59:29 +0000561 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000562}
563
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000564bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
565 llvm_unreachable("Translation units are visited directly by Visit()");
566 return false;
567}
568
569bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
570 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
571 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000572
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000573 return false;
574}
575
576bool CursorVisitor::VisitTagDecl(TagDecl *D) {
577 return VisitDeclContext(D);
578}
579
580bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
581 if (Expr *Init = D->getInitExpr())
582 return Visit(MakeCXCursor(Init, StmtParent, TU));
583 return false;
584}
585
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000586bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
587 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
588 if (Visit(TSInfo->getTypeLoc()))
589 return true;
590
591 return false;
592}
593
Douglas Gregorb1373d02010-01-20 20:59:29 +0000594bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000595 if (VisitDeclaratorDecl(ND))
596 return true;
597
Douglas Gregora59e3902010-01-21 23:27:09 +0000598 if (ND->isThisDeclarationADefinition() &&
599 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
600 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000601
Douglas Gregorb1373d02010-01-20 20:59:29 +0000602 return false;
603}
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000604
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000605bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
606 if (VisitDeclaratorDecl(D))
607 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000608
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000609 if (Expr *BitWidth = D->getBitWidth())
610 return Visit(MakeCXCursor(BitWidth, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000611
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000612 return false;
613}
614
615bool CursorVisitor::VisitVarDecl(VarDecl *D) {
616 if (VisitDeclaratorDecl(D))
617 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000618
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000619 if (Expr *Init = D->getInit())
620 return Visit(MakeCXCursor(Init, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000621
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000622 return false;
623}
624
625bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
Douglas Gregor4bc1cb62010-03-08 14:59:44 +0000626 if (TypeSourceInfo *TSInfo = ND->getResultTypeSourceInfo())
627 if (Visit(TSInfo->getTypeLoc()))
628 return true;
629
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000630 for (ObjCMethodDecl::param_iterator P = ND->param_begin(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000631 PEnd = ND->param_end();
632 P != PEnd; ++P) {
633 if (Visit(MakeCXCursor(*P, TU)))
634 return true;
635 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000636
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000637 if (ND->isThisDeclarationADefinition() &&
638 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
639 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000640
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000641 return false;
642}
643
Douglas Gregora59e3902010-01-21 23:27:09 +0000644bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
645 return VisitDeclContext(D);
646}
647
Douglas Gregorb1373d02010-01-20 20:59:29 +0000648bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000649 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
650 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000651 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000652
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000653 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
654 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
655 E = ND->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000656 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000657 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000658
Douglas Gregora59e3902010-01-21 23:27:09 +0000659 return VisitObjCContainerDecl(ND);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000660}
661
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000662bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
663 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
664 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
665 E = PID->protocol_end(); I != E; ++I, ++PL)
666 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
667 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000668
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000669 return VisitObjCContainerDecl(PID);
670}
671
Ted Kremenek23173d72010-05-18 21:09:07 +0000672bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
John McCallfc929202010-06-04 22:33:30 +0000673 if (Visit(PD->getTypeSourceInfo()->getTypeLoc()))
674 return true;
675
Ted Kremenek23173d72010-05-18 21:09:07 +0000676 // FIXME: This implements a workaround with @property declarations also being
677 // installed in the DeclContext for the @interface. Eventually this code
678 // should be removed.
679 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
680 if (!CDecl || !CDecl->IsClassExtension())
681 return false;
682
683 ObjCInterfaceDecl *ID = CDecl->getClassInterface();
684 if (!ID)
685 return false;
686
687 IdentifierInfo *PropertyId = PD->getIdentifier();
688 ObjCPropertyDecl *prevDecl =
689 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId);
690
691 if (!prevDecl)
692 return false;
693
694 // Visit synthesized methods since they will be skipped when visiting
695 // the @interface.
696 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
697 if (MD->isSynthesized())
698 if (Visit(MakeCXCursor(MD, TU)))
699 return true;
700
701 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
702 if (MD->isSynthesized())
703 if (Visit(MakeCXCursor(MD, TU)))
704 return true;
705
706 return false;
707}
708
Douglas Gregorb1373d02010-01-20 20:59:29 +0000709bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000710 // Issue callbacks for super class.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000711 if (D->getSuperClass() &&
712 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000713 D->getSuperClassLoc(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000714 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000715 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000716
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000717 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
718 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
719 E = D->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000720 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000721 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000722
Douglas Gregora59e3902010-01-21 23:27:09 +0000723 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000724}
725
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000726bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
727 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000728}
729
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000730bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
Ted Kremenekebfa3392010-03-19 20:39:03 +0000731 // 'ID' could be null when dealing with invalid code.
732 if (ObjCInterfaceDecl *ID = D->getClassInterface())
733 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
734 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000735
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000736 return VisitObjCImplDecl(D);
737}
738
739bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
740#if 0
741 // Issue callbacks for super class.
742 // FIXME: No source location information!
743 if (D->getSuperClass() &&
744 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000745 D->getSuperClassLoc(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000746 TU)))
747 return true;
748#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000749
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000750 return VisitObjCImplDecl(D);
751}
752
753bool CursorVisitor::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D) {
754 ObjCForwardProtocolDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
755 for (ObjCForwardProtocolDecl::protocol_iterator I = D->protocol_begin(),
756 E = D->protocol_end();
757 I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000758 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000759 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000760
761 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000762}
763
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000764bool CursorVisitor::VisitObjCClassDecl(ObjCClassDecl *D) {
765 for (ObjCClassDecl::iterator C = D->begin(), CEnd = D->end(); C != CEnd; ++C)
766 if (Visit(MakeCursorObjCClassRef(C->getInterface(), C->getLocation(), TU)))
767 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000768
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000769 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000770}
771
Ted Kremenek8f06e0e2010-05-06 23:38:21 +0000772bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
773 return VisitDeclContext(D);
774}
775
Ted Kremeneka0536d82010-05-07 01:04:29 +0000776bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
777 return VisitDeclContext(D);
778}
779
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000780bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
781 ASTContext &Context = TU->getASTContext();
782
783 // Some builtin types (such as Objective-C's "id", "sel", and
784 // "Class") have associated declarations. Create cursors for those.
785 QualType VisitType;
786 switch (TL.getType()->getAs<BuiltinType>()->getKind()) {
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000787 case BuiltinType::Void:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000788 case BuiltinType::Bool:
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000789 case BuiltinType::Char_U:
790 case BuiltinType::UChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000791 case BuiltinType::Char16:
792 case BuiltinType::Char32:
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000793 case BuiltinType::UShort:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000794 case BuiltinType::UInt:
795 case BuiltinType::ULong:
796 case BuiltinType::ULongLong:
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000797 case BuiltinType::UInt128:
798 case BuiltinType::Char_S:
799 case BuiltinType::SChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000800 case BuiltinType::WChar:
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000801 case BuiltinType::Short:
802 case BuiltinType::Int:
803 case BuiltinType::Long:
804 case BuiltinType::LongLong:
805 case BuiltinType::Int128:
806 case BuiltinType::Float:
807 case BuiltinType::Double:
808 case BuiltinType::LongDouble:
809 case BuiltinType::NullPtr:
810 case BuiltinType::Overload:
811 case BuiltinType::Dependent:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000812 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000813
814 case BuiltinType::UndeducedAuto: // FIXME: Deserves a cursor?
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000815 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000816
Ted Kremenekc4174cc2010-02-18 18:52:18 +0000817 case BuiltinType::ObjCId:
818 VisitType = Context.getObjCIdType();
819 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000820
821 case BuiltinType::ObjCClass:
822 VisitType = Context.getObjCClassType();
823 break;
824
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000825 case BuiltinType::ObjCSel:
826 VisitType = Context.getObjCSelType();
827 break;
828 }
829
830 if (!VisitType.isNull()) {
831 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000832 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000833 TU));
834 }
835
836 return false;
837}
838
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000839bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
840 return Visit(MakeCursorTypeRef(TL.getTypedefDecl(), TL.getNameLoc(), TU));
841}
842
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000843bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
844 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
845}
846
847bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
848 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
849}
850
851bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
852 if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
853 return true;
854
John McCallc12c5bb2010-05-15 11:32:37 +0000855 return false;
856}
857
858bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
859 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
860 return true;
861
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000862 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
863 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
864 TU)))
865 return true;
866 }
867
868 return false;
869}
870
871bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
John McCallc12c5bb2010-05-15 11:32:37 +0000872 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000873}
874
875bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
876 return Visit(TL.getPointeeLoc());
877}
878
879bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
880 return Visit(TL.getPointeeLoc());
881}
882
883bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
884 return Visit(TL.getPointeeLoc());
885}
886
887bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000888 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000889}
890
891bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000892 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000893}
894
895bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
896 if (Visit(TL.getResultLoc()))
897 return true;
898
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000899 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
Ted Kremenek5dbacb42010-04-07 00:27:13 +0000900 if (Decl *D = TL.getArg(I))
901 if (Visit(MakeCXCursor(D, TU)))
902 return true;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000903
904 return false;
905}
906
907bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
908 if (Visit(TL.getElementLoc()))
909 return true;
910
911 if (Expr *Size = TL.getSizeExpr())
912 return Visit(MakeCXCursor(Size, StmtParent, TU));
913
914 return false;
915}
916
Douglas Gregor2332c112010-01-21 20:48:56 +0000917bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
918 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
919}
920
921bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
922 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
923 return Visit(TSInfo->getTypeLoc());
924
925 return false;
926}
927
Douglas Gregora59e3902010-01-21 23:27:09 +0000928bool CursorVisitor::VisitStmt(Stmt *S) {
929 for (Stmt::child_iterator Child = S->child_begin(), ChildEnd = S->child_end();
930 Child != ChildEnd; ++Child) {
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000931 if (Stmt *C = *Child)
932 if (Visit(MakeCXCursor(C, StmtParent, TU)))
933 return true;
Douglas Gregora59e3902010-01-21 23:27:09 +0000934 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000935
Douglas Gregora59e3902010-01-21 23:27:09 +0000936 return false;
937}
938
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000939bool CursorVisitor::VisitCaseStmt(CaseStmt *S) {
940 // Specially handle CaseStmts because they can be nested, e.g.:
941 //
942 // case 1:
943 // case 2:
944 //
945 // In this case the second CaseStmt is the child of the first. Walking
946 // these recursively can blow out the stack.
947 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU);
948 while (true) {
949 // Set the Parent field to Cursor, then back to its old value once we're
950 // done.
951 SetParentRAII SetParent(Parent, StmtParent, Cursor);
952
953 if (Stmt *LHS = S->getLHS())
954 if (Visit(MakeCXCursor(LHS, StmtParent, TU)))
955 return true;
956 if (Stmt *RHS = S->getRHS())
957 if (Visit(MakeCXCursor(RHS, StmtParent, TU)))
958 return true;
959 if (Stmt *SubStmt = S->getSubStmt()) {
960 if (!isa<CaseStmt>(SubStmt))
961 return Visit(MakeCXCursor(SubStmt, StmtParent, TU));
962
963 // Specially handle 'CaseStmt' so that we don't blow out the stack.
964 CaseStmt *CS = cast<CaseStmt>(SubStmt);
965 Cursor = MakeCXCursor(CS, StmtParent, TU);
966 if (RegionOfInterest.isValid()) {
967 SourceRange Range = CS->getSourceRange();
968 if (Range.isInvalid() || CompareRegionOfInterest(Range))
969 return false;
970 }
971
972 switch (Visitor(Cursor, Parent, ClientData)) {
973 case CXChildVisit_Break: return true;
974 case CXChildVisit_Continue: return false;
975 case CXChildVisit_Recurse:
976 // Perform tail-recursion manually.
977 S = CS;
978 continue;
979 }
980 }
981 return false;
982 }
983}
984
Douglas Gregora59e3902010-01-21 23:27:09 +0000985bool CursorVisitor::VisitDeclStmt(DeclStmt *S) {
986 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
987 D != DEnd; ++D) {
Douglas Gregor263b47b2010-01-25 16:12:32 +0000988 if (*D && Visit(MakeCXCursor(*D, TU)))
Douglas Gregora59e3902010-01-21 23:27:09 +0000989 return true;
990 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000991
Douglas Gregora59e3902010-01-21 23:27:09 +0000992 return false;
993}
994
Douglas Gregorf5bab412010-01-22 01:00:11 +0000995bool CursorVisitor::VisitIfStmt(IfStmt *S) {
996 if (VarDecl *Var = S->getConditionVariable()) {
997 if (Visit(MakeCXCursor(Var, TU)))
998 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000999 }
1000
Douglas Gregor263b47b2010-01-25 16:12:32 +00001001 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1002 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +00001003 if (S->getThen() && Visit(MakeCXCursor(S->getThen(), StmtParent, TU)))
1004 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +00001005 if (S->getElse() && Visit(MakeCXCursor(S->getElse(), StmtParent, TU)))
1006 return true;
1007
1008 return false;
1009}
1010
1011bool CursorVisitor::VisitSwitchStmt(SwitchStmt *S) {
1012 if (VarDecl *Var = S->getConditionVariable()) {
1013 if (Visit(MakeCXCursor(Var, TU)))
1014 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001015 }
1016
Douglas Gregor263b47b2010-01-25 16:12:32 +00001017 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1018 return true;
1019 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
1020 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001021
Douglas Gregor263b47b2010-01-25 16:12:32 +00001022 return false;
1023}
1024
1025bool CursorVisitor::VisitWhileStmt(WhileStmt *S) {
1026 if (VarDecl *Var = S->getConditionVariable()) {
1027 if (Visit(MakeCXCursor(Var, TU)))
1028 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001029 }
1030
Douglas Gregor263b47b2010-01-25 16:12:32 +00001031 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1032 return true;
1033 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
Douglas Gregorf5bab412010-01-22 01:00:11 +00001034 return true;
1035
Douglas Gregor263b47b2010-01-25 16:12:32 +00001036 return false;
1037}
1038
1039bool CursorVisitor::VisitForStmt(ForStmt *S) {
1040 if (S->getInit() && Visit(MakeCXCursor(S->getInit(), StmtParent, TU)))
1041 return true;
1042 if (VarDecl *Var = S->getConditionVariable()) {
1043 if (Visit(MakeCXCursor(Var, TU)))
1044 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001045 }
1046
Douglas Gregor263b47b2010-01-25 16:12:32 +00001047 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1048 return true;
1049 if (S->getInc() && Visit(MakeCXCursor(S->getInc(), StmtParent, TU)))
1050 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +00001051 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
1052 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001053
Douglas Gregorf5bab412010-01-22 01:00:11 +00001054 return false;
1055}
1056
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00001057bool CursorVisitor::VisitBlockExpr(BlockExpr *B) {
1058 return Visit(B->getBlockDecl());
1059}
1060
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001061bool CursorVisitor::VisitOffsetOfExpr(OffsetOfExpr *E) {
1062 // FIXME: Visit fields as well?
1063 if (Visit(E->getTypeSourceInfo()->getTypeLoc()))
1064 return true;
1065
1066 return VisitExpr(E);
1067}
1068
Douglas Gregor336fd812010-01-23 00:40:08 +00001069bool CursorVisitor::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E) {
1070 if (E->isArgumentType()) {
1071 if (TypeSourceInfo *TSInfo = E->getArgumentTypeInfo())
1072 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001073
Douglas Gregor336fd812010-01-23 00:40:08 +00001074 return false;
1075 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001076
Douglas Gregor336fd812010-01-23 00:40:08 +00001077 return VisitExpr(E);
1078}
1079
1080bool CursorVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
1081 if (TypeSourceInfo *TSInfo = E->getTypeInfoAsWritten())
1082 if (Visit(TSInfo->getTypeLoc()))
1083 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001084
Douglas Gregor336fd812010-01-23 00:40:08 +00001085 return VisitCastExpr(E);
1086}
1087
1088bool CursorVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
1089 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
1090 if (Visit(TSInfo->getTypeLoc()))
1091 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001092
Douglas Gregor336fd812010-01-23 00:40:08 +00001093 return VisitExpr(E);
1094}
1095
Douglas Gregorc2350e52010-03-08 16:40:19 +00001096bool CursorVisitor::VisitObjCMessageExpr(ObjCMessageExpr *E) {
Douglas Gregor04badcf2010-04-21 00:45:42 +00001097 if (TypeSourceInfo *TSInfo = E->getClassReceiverTypeInfo())
1098 if (Visit(TSInfo->getTypeLoc()))
1099 return true;
Douglas Gregorc2350e52010-03-08 16:40:19 +00001100
1101 return VisitExpr(E);
1102}
1103
Douglas Gregor81d34662010-04-20 15:39:42 +00001104bool CursorVisitor::VisitObjCEncodeExpr(ObjCEncodeExpr *E) {
1105 return Visit(E->getEncodedTypeSourceInfo()->getTypeLoc());
1106}
1107
1108
Ted Kremenek09dfa372010-02-18 05:46:33 +00001109bool CursorVisitor::VisitAttributes(Decl *D) {
1110 for (const Attr *A = D->getAttrs(); A; A = A->getNext())
1111 if (Visit(MakeCXCursor(A, D, TU)))
1112 return true;
1113
1114 return false;
1115}
1116
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00001117extern "C" {
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001118CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
1119 int displayDiagnostics) {
Douglas Gregora030b7c2010-01-22 20:35:53 +00001120 CIndexer *CIdxr = new CIndexer();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001121 if (excludeDeclarationsFromPCH)
1122 CIdxr->setOnlyLocalDecls();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001123 if (displayDiagnostics)
1124 CIdxr->setDisplayDiagnostics();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001125 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +00001126}
1127
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001128void clang_disposeIndex(CXIndex CIdx) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001129 if (CIdx)
1130 delete static_cast<CIndexer *>(CIdx);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00001131}
1132
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001133void clang_setUseExternalASTGeneration(CXIndex CIdx, int value) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001134 if (CIdx) {
1135 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
1136 CXXIdx->setUseExternalASTGeneration(value);
1137 }
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001138}
1139
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001140CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
Douglas Gregora88084b2010-02-18 18:08:43 +00001141 const char *ast_filename) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001142 if (!CIdx)
1143 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001144
Douglas Gregor7d1d49d2009-10-16 20:01:17 +00001145 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001146
Douglas Gregor28019772010-04-05 23:52:57 +00001147 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
1148 return ASTUnit::LoadFromPCHFile(ast_filename, Diags,
Douglas Gregora88084b2010-02-18 18:08:43 +00001149 CXXIdx->getOnlyLocalDecls(),
1150 0, 0, true);
Steve Naroff600866c2009-08-27 19:51:58 +00001151}
1152
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001153CXTranslationUnit
1154clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
1155 const char *source_filename,
1156 int num_command_line_args,
Douglas Gregor4db64a42010-01-23 00:14:00 +00001157 const char **command_line_args,
1158 unsigned num_unsaved_files,
Douglas Gregora88084b2010-02-18 18:08:43 +00001159 struct CXUnsavedFile *unsaved_files) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001160 if (!CIdx)
1161 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001162
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001163 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
1164
Douglas Gregor5352ac02010-01-28 00:27:43 +00001165 // Configure the diagnostics.
1166 DiagnosticOptions DiagOpts;
Douglas Gregor28019772010-04-05 23:52:57 +00001167 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
1168 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001169
Douglas Gregor4db64a42010-01-23 00:14:00 +00001170 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
1171 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattnera0a270c2010-04-05 22:42:27 +00001172 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001173 const llvm::MemoryBuffer *Buffer
Chris Lattnera0a270c2010-04-05 22:42:27 +00001174 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregor4db64a42010-01-23 00:14:00 +00001175 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
1176 Buffer));
1177 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001178
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001179 if (!CXXIdx->getUseExternalASTGeneration()) {
1180 llvm::SmallVector<const char *, 16> Args;
1181
1182 // The 'source_filename' argument is optional. If the caller does not
1183 // specify it then it is assumed that the source file is specified
1184 // in the actual argument list.
1185 if (source_filename)
1186 Args.push_back(source_filename);
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00001187
1188 // Since the Clang C library is primarily used by batch tools dealing with
1189 // (often very broken) source code, where spell-checking can have a
1190 // significant negative impact on performance (particularly when
1191 // precompiled headers are involved), we disable it by default.
1192 // Note that we place this argument early in the list, so that it can be
1193 // overridden by the caller with "-fspell-checking".
Douglas Gregora0068fc2010-07-09 17:35:33 +00001194 Args.push_back("-fno-spell-checking");
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00001195
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001196 Args.insert(Args.end(), command_line_args,
1197 command_line_args + num_command_line_args);
Douglas Gregor94dc8f62010-03-19 16:15:56 +00001198 Args.push_back("-Xclang");
1199 Args.push_back("-detailed-preprocessing-record");
Douglas Gregor5352ac02010-01-28 00:27:43 +00001200 unsigned NumErrors = Diags->getNumErrors();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001201
Ted Kremenek29b72842010-01-07 22:49:05 +00001202#ifdef USE_CRASHTRACER
1203 ArgsCrashTracerInfo ACTI(Args);
Ted Kremenek8a8da7d2010-01-06 03:42:32 +00001204#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001205
Daniel Dunbar94220972009-12-05 02:17:18 +00001206 llvm::OwningPtr<ASTUnit> Unit(
1207 ASTUnit::LoadFromCommandLine(Args.data(), Args.data() + Args.size(),
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001208 Diags,
Daniel Dunbar869824e2009-12-13 03:46:13 +00001209 CXXIdx->getClangResourcesPath(),
Daniel Dunbar94220972009-12-05 02:17:18 +00001210 CXXIdx->getOnlyLocalDecls(),
Douglas Gregor4db64a42010-01-23 00:14:00 +00001211 RemappedFiles.data(),
Douglas Gregora88084b2010-02-18 18:08:43 +00001212 RemappedFiles.size(),
Douglas Gregor94dc8f62010-03-19 16:15:56 +00001213 /*CaptureDiagnostics=*/true));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001214
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001215 if (NumErrors != Diags->getNumErrors()) {
Ted Kremenek34f6a322010-03-05 22:43:29 +00001216 // Make sure to check that 'Unit' is non-NULL.
1217 if (CXXIdx->getDisplayDiagnostics() && Unit.get()) {
Douglas Gregor405634b2010-04-05 18:10:21 +00001218 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
1219 DEnd = Unit->stored_diag_end();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001220 D != DEnd; ++D) {
1221 CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOptions());
Douglas Gregor274f1902010-02-22 23:17:23 +00001222 CXString Msg = clang_formatDiagnostic(&Diag,
1223 clang_defaultDiagnosticDisplayOptions());
1224 fprintf(stderr, "%s\n", clang_getCString(Msg));
1225 clang_disposeString(Msg);
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001226 }
Douglas Gregor274f1902010-02-22 23:17:23 +00001227#ifdef LLVM_ON_WIN32
1228 // On Windows, force a flush, since there may be multiple copies of
1229 // stderr and stdout in the file system, all with different buffers
1230 // but writing to the same device.
1231 fflush(stderr);
Ted Kremenek83c51842010-03-26 01:34:51 +00001232#endif
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001233 }
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001234 }
Daniel Dunbar94220972009-12-05 02:17:18 +00001235
1236 return Unit.take();
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001237 }
1238
Ted Kremenek139ba862009-10-22 00:03:57 +00001239 // Build up the arguments for invoking 'clang'.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001240 std::vector<const char *> argv;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001241
Ted Kremenek139ba862009-10-22 00:03:57 +00001242 // First add the complete path to the 'clang' executable.
1243 llvm::sys::Path ClangPath = static_cast<CIndexer *>(CIdx)->getClangPath();
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00001244 argv.push_back(ClangPath.c_str());
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001245
Ted Kremenek139ba862009-10-22 00:03:57 +00001246 // Add the '-emit-ast' option as our execution mode for 'clang'.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001247 argv.push_back("-emit-ast");
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001248
Ted Kremenek139ba862009-10-22 00:03:57 +00001249 // The 'source_filename' argument is optional. If the caller does not
1250 // specify it then it is assumed that the source file is specified
1251 // in the actual argument list.
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001252 if (source_filename)
1253 argv.push_back(source_filename);
Ted Kremenek139ba862009-10-22 00:03:57 +00001254
Steve Naroff37b5ac22009-10-15 20:50:09 +00001255 // Generate a temporary name for the AST file.
Ted Kremenek139ba862009-10-22 00:03:57 +00001256 argv.push_back("-o");
Benjamin Kramerc2a98162010-03-13 21:22:49 +00001257 char astTmpFile[L_tmpnam];
1258 argv.push_back(tmpnam(astTmpFile));
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00001259
1260 // Since the Clang C library is primarily used by batch tools dealing with
1261 // (often very broken) source code, where spell-checking can have a
1262 // significant negative impact on performance (particularly when
1263 // precompiled headers are involved), we disable it by default.
1264 // Note that we place this argument early in the list, so that it can be
1265 // overridden by the caller with "-fspell-checking".
Douglas Gregora0068fc2010-07-09 17:35:33 +00001266 argv.push_back("-fno-spell-checking");
Ted Kremenek139ba862009-10-22 00:03:57 +00001267
Douglas Gregor4db64a42010-01-23 00:14:00 +00001268 // Remap any unsaved files to temporary files.
1269 std::vector<llvm::sys::Path> TemporaryFiles;
1270 std::vector<std::string> RemapArgs;
1271 if (RemapFiles(num_unsaved_files, unsaved_files, RemapArgs, TemporaryFiles))
1272 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001273
Douglas Gregor4db64a42010-01-23 00:14:00 +00001274 // The pointers into the elements of RemapArgs are stable because we
1275 // won't be adding anything to RemapArgs after this point.
1276 for (unsigned i = 0, e = RemapArgs.size(); i != e; ++i)
1277 argv.push_back(RemapArgs[i].c_str());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001278
Ted Kremenek139ba862009-10-22 00:03:57 +00001279 // Process the compiler options, stripping off '-o', '-c', '-fsyntax-only'.
1280 for (int i = 0; i < num_command_line_args; ++i)
1281 if (const char *arg = command_line_args[i]) {
1282 if (strcmp(arg, "-o") == 0) {
1283 ++i; // Also skip the matching argument.
1284 continue;
1285 }
1286 if (strcmp(arg, "-emit-ast") == 0 ||
1287 strcmp(arg, "-c") == 0 ||
1288 strcmp(arg, "-fsyntax-only") == 0) {
1289 continue;
1290 }
1291
1292 // Keep the argument.
1293 argv.push_back(arg);
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001294 }
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001295
Douglas Gregord93256e2010-01-28 06:00:51 +00001296 // Generate a temporary name for the diagnostics file.
Benjamin Kramerc2a98162010-03-13 21:22:49 +00001297 char tmpFileResults[L_tmpnam];
1298 char *tmpResultsFileName = tmpnam(tmpFileResults);
1299 llvm::sys::Path DiagnosticsFile(tmpResultsFileName);
Douglas Gregord93256e2010-01-28 06:00:51 +00001300 TemporaryFiles.push_back(DiagnosticsFile);
1301 argv.push_back("-fdiagnostics-binary");
1302
Douglas Gregor94dc8f62010-03-19 16:15:56 +00001303 argv.push_back("-Xclang");
1304 argv.push_back("-detailed-preprocessing-record");
1305
Ted Kremenek139ba862009-10-22 00:03:57 +00001306 // Add the null terminator.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001307 argv.push_back(NULL);
1308
Ted Kremenekfeb15e32009-10-26 22:14:08 +00001309 // Invoke 'clang'.
1310 llvm::sys::Path DevNull; // leave empty, causes redirection to /dev/null
1311 // on Unix or NUL (Windows).
Ted Kremenek379afec2009-10-22 03:24:01 +00001312 std::string ErrMsg;
Douglas Gregord93256e2010-01-28 06:00:51 +00001313 const llvm::sys::Path *Redirects[] = { &DevNull, &DevNull, &DiagnosticsFile,
1314 NULL };
Ted Kremenek379afec2009-10-22 03:24:01 +00001315 llvm::sys::Program::ExecuteAndWait(ClangPath, &argv[0], /* env */ NULL,
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001316 /* redirects */ &Redirects[0],
Ted Kremenek379afec2009-10-22 03:24:01 +00001317 /* secondsToWait */ 0, /* memoryLimits */ 0, &ErrMsg);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001318
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001319 if (!ErrMsg.empty()) {
1320 std::string AllArgs;
Ted Kremenek379afec2009-10-22 03:24:01 +00001321 for (std::vector<const char*>::iterator I = argv.begin(), E = argv.end();
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001322 I != E; ++I) {
1323 AllArgs += ' ';
Ted Kremenek779e5f42009-10-26 22:08:39 +00001324 if (*I)
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001325 AllArgs += *I;
Ted Kremenek779e5f42009-10-26 22:08:39 +00001326 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001327
Daniel Dunbar32141c82010-02-23 20:23:45 +00001328 Diags->Report(diag::err_fe_invoking) << AllArgs << ErrMsg;
Ted Kremenek379afec2009-10-22 03:24:01 +00001329 }
Benjamin Kramer0829a832009-10-18 11:19:36 +00001330
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001331 ASTUnit *ATU = ASTUnit::LoadFromPCHFile(astTmpFile, Diags,
Douglas Gregor4db64a42010-01-23 00:14:00 +00001332 CXXIdx->getOnlyLocalDecls(),
Douglas Gregor4db64a42010-01-23 00:14:00 +00001333 RemappedFiles.data(),
Douglas Gregora88084b2010-02-18 18:08:43 +00001334 RemappedFiles.size(),
1335 /*CaptureDiagnostics=*/true);
Douglas Gregora88084b2010-02-18 18:08:43 +00001336 if (ATU) {
1337 LoadSerializedDiagnostics(DiagnosticsFile,
1338 num_unsaved_files, unsaved_files,
1339 ATU->getFileManager(),
1340 ATU->getSourceManager(),
Douglas Gregor405634b2010-04-05 18:10:21 +00001341 ATU->getStoredDiagnostics());
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001342 } else if (CXXIdx->getDisplayDiagnostics()) {
1343 // We failed to load the ASTUnit, but we can still deserialize the
1344 // diagnostics and emit them.
1345 FileManager FileMgr;
Douglas Gregorf715ca12010-03-16 00:06:06 +00001346 Diagnostic Diag;
1347 SourceManager SourceMgr(Diag);
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001348 // FIXME: Faked LangOpts!
1349 LangOptions LangOpts;
1350 llvm::SmallVector<StoredDiagnostic, 4> Diags;
1351 LoadSerializedDiagnostics(DiagnosticsFile,
1352 num_unsaved_files, unsaved_files,
1353 FileMgr, SourceMgr, Diags);
1354 for (llvm::SmallVector<StoredDiagnostic, 4>::iterator D = Diags.begin(),
1355 DEnd = Diags.end();
1356 D != DEnd; ++D) {
1357 CXStoredDiagnostic Diag(*D, LangOpts);
Douglas Gregor274f1902010-02-22 23:17:23 +00001358 CXString Msg = clang_formatDiagnostic(&Diag,
1359 clang_defaultDiagnosticDisplayOptions());
1360 fprintf(stderr, "%s\n", clang_getCString(Msg));
1361 clang_disposeString(Msg);
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001362 }
Douglas Gregor274f1902010-02-22 23:17:23 +00001363
1364#ifdef LLVM_ON_WIN32
1365 // On Windows, force a flush, since there may be multiple copies of
1366 // stderr and stdout in the file system, all with different buffers
1367 // but writing to the same device.
1368 fflush(stderr);
1369#endif
Douglas Gregora88084b2010-02-18 18:08:43 +00001370 }
Douglas Gregord93256e2010-01-28 06:00:51 +00001371
Douglas Gregor313e26c2010-02-18 23:35:40 +00001372 if (ATU) {
1373 // Make the translation unit responsible for destroying all temporary files.
1374 for (unsigned i = 0, e = TemporaryFiles.size(); i != e; ++i)
1375 ATU->addTemporaryFile(TemporaryFiles[i]);
1376 ATU->addTemporaryFile(llvm::sys::Path(ATU->getPCHFileName()));
1377 } else {
1378 // Destroy all of the temporary files now; they can't be referenced any
1379 // longer.
1380 llvm::sys::Path(astTmpFile).eraseFromDisk();
1381 for (unsigned i = 0, e = TemporaryFiles.size(); i != e; ++i)
1382 TemporaryFiles[i].eraseFromDisk();
1383 }
1384
Steve Naroffe19944c2009-10-15 22:23:48 +00001385 return ATU;
Steve Naroff5b7d8e22009-10-15 20:04:39 +00001386}
1387
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001388void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001389 if (CTUnit)
1390 delete static_cast<ASTUnit *>(CTUnit);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00001391}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001392
Douglas Gregorabc563f2010-07-19 21:46:24 +00001393int clang_reparseTranslationUnit(CXTranslationUnit TU,
1394 unsigned num_unsaved_files,
1395 struct CXUnsavedFile *unsaved_files) {
1396 if (!TU)
1397 return 1;
1398
1399 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
1400 for (unsigned I = 0; I != num_unsaved_files; ++I) {
1401 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
1402 const llvm::MemoryBuffer *Buffer
1403 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
1404 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
1405 Buffer));
1406 }
1407
1408 return static_cast<ASTUnit *>(TU)->Reparse(RemappedFiles.data(),
1409 RemappedFiles.size())? 1 : 0;
1410}
1411
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001412CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001413 if (!CTUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001414 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001415
Steve Naroff77accc12009-09-03 18:19:54 +00001416 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001417 return createCXString(CXXUnit->getOriginalSourceFileName(), true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +00001418}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +00001419
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001420CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001421 CXCursor Result = { CXCursor_TranslationUnit, { 0, 0, TU } };
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001422 return Result;
1423}
1424
Ted Kremenekfb480492010-01-13 21:46:36 +00001425} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +00001426
Ted Kremenekfb480492010-01-13 21:46:36 +00001427//===----------------------------------------------------------------------===//
Douglas Gregor1db19de2010-01-19 21:36:55 +00001428// CXSourceLocation and CXSourceRange Operations.
1429//===----------------------------------------------------------------------===//
1430
Douglas Gregorb9790342010-01-22 21:44:22 +00001431extern "C" {
1432CXSourceLocation clang_getNullLocation() {
Douglas Gregor5352ac02010-01-28 00:27:43 +00001433 CXSourceLocation Result = { { 0, 0 }, 0 };
Douglas Gregorb9790342010-01-22 21:44:22 +00001434 return Result;
1435}
1436
1437unsigned clang_equalLocations(CXSourceLocation loc1, CXSourceLocation loc2) {
Daniel Dunbar90a6b9e2010-01-30 23:58:27 +00001438 return (loc1.ptr_data[0] == loc2.ptr_data[0] &&
1439 loc1.ptr_data[1] == loc2.ptr_data[1] &&
1440 loc1.int_data == loc2.int_data);
Douglas Gregorb9790342010-01-22 21:44:22 +00001441}
1442
1443CXSourceLocation clang_getLocation(CXTranslationUnit tu,
1444 CXFile file,
1445 unsigned line,
1446 unsigned column) {
Douglas Gregor42748ec2010-04-30 19:45:53 +00001447 if (!tu || !file)
Douglas Gregorb9790342010-01-22 21:44:22 +00001448 return clang_getNullLocation();
Douglas Gregor42748ec2010-04-30 19:45:53 +00001449
Douglas Gregorb9790342010-01-22 21:44:22 +00001450 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
1451 SourceLocation SLoc
1452 = CXXUnit->getSourceManager().getLocation(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001453 static_cast<const FileEntry *>(file),
Douglas Gregorb9790342010-01-22 21:44:22 +00001454 line, column);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001455
Ted Kremenek1a9a0bc2010-06-28 23:54:17 +00001456 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
Douglas Gregorb9790342010-01-22 21:44:22 +00001457}
1458
Douglas Gregor5352ac02010-01-28 00:27:43 +00001459CXSourceRange clang_getNullRange() {
1460 CXSourceRange Result = { { 0, 0 }, 0, 0 };
1461 return Result;
1462}
Daniel Dunbard52864b2010-02-14 10:02:57 +00001463
Douglas Gregor5352ac02010-01-28 00:27:43 +00001464CXSourceRange clang_getRange(CXSourceLocation begin, CXSourceLocation end) {
1465 if (begin.ptr_data[0] != end.ptr_data[0] ||
1466 begin.ptr_data[1] != end.ptr_data[1])
1467 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001468
1469 CXSourceRange Result = { { begin.ptr_data[0], begin.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00001470 begin.int_data, end.int_data };
Douglas Gregorb9790342010-01-22 21:44:22 +00001471 return Result;
1472}
1473
Douglas Gregor46766dc2010-01-26 19:19:08 +00001474void clang_getInstantiationLocation(CXSourceLocation location,
1475 CXFile *file,
1476 unsigned *line,
1477 unsigned *column,
1478 unsigned *offset) {
Douglas Gregor1db19de2010-01-19 21:36:55 +00001479 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
1480
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00001481 if (!location.ptr_data[0] || Loc.isInvalid()) {
Douglas Gregor46766dc2010-01-26 19:19:08 +00001482 if (file)
1483 *file = 0;
1484 if (line)
1485 *line = 0;
1486 if (column)
1487 *column = 0;
1488 if (offset)
1489 *offset = 0;
1490 return;
1491 }
1492
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00001493 const SourceManager &SM =
1494 *static_cast<const SourceManager*>(location.ptr_data[0]);
Douglas Gregor1db19de2010-01-19 21:36:55 +00001495 SourceLocation InstLoc = SM.getInstantiationLoc(Loc);
Douglas Gregor1db19de2010-01-19 21:36:55 +00001496
1497 if (file)
1498 *file = (void *)SM.getFileEntryForID(SM.getFileID(InstLoc));
1499 if (line)
1500 *line = SM.getInstantiationLineNumber(InstLoc);
1501 if (column)
1502 *column = SM.getInstantiationColumnNumber(InstLoc);
Douglas Gregore69517c2010-01-26 03:07:15 +00001503 if (offset)
Douglas Gregor46766dc2010-01-26 19:19:08 +00001504 *offset = SM.getDecomposedLoc(InstLoc).second;
Douglas Gregore69517c2010-01-26 03:07:15 +00001505}
1506
Douglas Gregor1db19de2010-01-19 21:36:55 +00001507CXSourceLocation clang_getRangeStart(CXSourceRange range) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001508 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00001509 range.begin_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00001510 return Result;
1511}
1512
1513CXSourceLocation clang_getRangeEnd(CXSourceRange range) {
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00001514 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00001515 range.end_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00001516 return Result;
1517}
1518
Douglas Gregorb9790342010-01-22 21:44:22 +00001519} // end: extern "C"
1520
Douglas Gregor1db19de2010-01-19 21:36:55 +00001521//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00001522// CXFile Operations.
1523//===----------------------------------------------------------------------===//
1524
1525extern "C" {
Ted Kremenek74844072010-02-17 00:41:20 +00001526CXString clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00001527 if (!SFile)
Ted Kremenek74844072010-02-17 00:41:20 +00001528 return createCXString(NULL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001529
Steve Naroff88145032009-10-27 14:35:18 +00001530 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Ted Kremenek74844072010-02-17 00:41:20 +00001531 return createCXString(FEnt->getName());
Steve Naroff88145032009-10-27 14:35:18 +00001532}
1533
1534time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00001535 if (!SFile)
1536 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001537
Steve Naroff88145032009-10-27 14:35:18 +00001538 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
1539 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +00001540}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001541
Douglas Gregorb9790342010-01-22 21:44:22 +00001542CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
1543 if (!tu)
1544 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001545
Douglas Gregorb9790342010-01-22 21:44:22 +00001546 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001547
Douglas Gregorb9790342010-01-22 21:44:22 +00001548 FileManager &FMgr = CXXUnit->getFileManager();
1549 const FileEntry *File = FMgr.getFile(file_name, file_name+strlen(file_name));
1550 return const_cast<FileEntry *>(File);
1551}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001552
Ted Kremenekfb480492010-01-13 21:46:36 +00001553} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +00001554
Ted Kremenekfb480492010-01-13 21:46:36 +00001555//===----------------------------------------------------------------------===//
1556// CXCursor Operations.
1557//===----------------------------------------------------------------------===//
1558
Ted Kremenekfb480492010-01-13 21:46:36 +00001559static Decl *getDeclFromExpr(Stmt *E) {
1560 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
1561 return RefExpr->getDecl();
1562 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
1563 return ME->getMemberDecl();
1564 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
1565 return RE->getDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001566
Ted Kremenekfb480492010-01-13 21:46:36 +00001567 if (CallExpr *CE = dyn_cast<CallExpr>(E))
1568 return getDeclFromExpr(CE->getCallee());
1569 if (CastExpr *CE = dyn_cast<CastExpr>(E))
1570 return getDeclFromExpr(CE->getSubExpr());
1571 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
1572 return OME->getMethodDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001573
Ted Kremenekfb480492010-01-13 21:46:36 +00001574 return 0;
1575}
1576
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00001577static SourceLocation getLocationFromExpr(Expr *E) {
1578 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
1579 return /*FIXME:*/Msg->getLeftLoc();
1580 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
1581 return DRE->getLocation();
1582 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
1583 return Member->getMemberLoc();
1584 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
1585 return Ivar->getLocation();
1586 return E->getLocStart();
1587}
1588
Ted Kremenekfb480492010-01-13 21:46:36 +00001589extern "C" {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001590
1591unsigned clang_visitChildren(CXCursor parent,
Douglas Gregorb1373d02010-01-20 20:59:29 +00001592 CXCursorVisitor visitor,
1593 CXClientData client_data) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001594 ASTUnit *CXXUnit = getCursorASTUnit(parent);
Douglas Gregorb1373d02010-01-20 20:59:29 +00001595
1596 unsigned PCHLevel = Decl::MaxPCHLevel;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001597
Douglas Gregorb1373d02010-01-20 20:59:29 +00001598 // Set the PCHLevel to filter out unwanted decls if requested.
1599 if (CXXUnit->getOnlyLocalDecls()) {
1600 PCHLevel = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001601
Douglas Gregorb1373d02010-01-20 20:59:29 +00001602 // If the main input was an AST, bump the level.
1603 if (CXXUnit->isMainFileAST())
1604 ++PCHLevel;
1605 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001606
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001607 CursorVisitor CursorVis(CXXUnit, visitor, client_data, PCHLevel);
Douglas Gregorb1373d02010-01-20 20:59:29 +00001608 return CursorVis.VisitChildren(parent);
1609}
1610
Douglas Gregor78205d42010-01-20 21:45:58 +00001611static CXString getDeclSpelling(Decl *D) {
1612 NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
1613 if (!ND)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001614 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001615
Douglas Gregor78205d42010-01-20 21:45:58 +00001616 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001617 return createCXString(OMD->getSelector().getAsString());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001618
Douglas Gregor78205d42010-01-20 21:45:58 +00001619 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
1620 // No, this isn't the same as the code below. getIdentifier() is non-virtual
1621 // and returns different names. NamedDecl returns the class name and
1622 // ObjCCategoryImplDecl returns the category name.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001623 return createCXString(CIMP->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001624
Ted Kremenek50aa6ac2010-05-19 21:51:10 +00001625 llvm::SmallString<1024> S;
1626 llvm::raw_svector_ostream os(S);
1627 ND->printName(os);
1628
1629 return createCXString(os.str());
Douglas Gregor78205d42010-01-20 21:45:58 +00001630}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001631
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001632CXString clang_getCursorSpelling(CXCursor C) {
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001633 if (clang_isTranslationUnit(C.kind))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001634 return clang_getTranslationUnitSpelling(C.data[2]);
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001635
Steve Narofff334b4e2009-09-02 18:26:48 +00001636 if (clang_isReference(C.kind)) {
1637 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00001638 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +00001639 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001640 return createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00001641 }
1642 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +00001643 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001644 return createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00001645 }
1646 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +00001647 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +00001648 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001649 return createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00001650 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001651 case CXCursor_TypeRef: {
1652 TypeDecl *Type = getCursorTypeRef(C).first;
1653 assert(Type && "Missing type decl");
1654
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001655 return createCXString(getCursorContext(C).getTypeDeclType(Type).
1656 getAsString());
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001657 }
1658
Daniel Dunbaracca7252009-11-30 20:42:49 +00001659 default:
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001660 return createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +00001661 }
1662 }
Douglas Gregor97b98722010-01-19 23:20:36 +00001663
1664 if (clang_isExpression(C.kind)) {
1665 Decl *D = getDeclFromExpr(getCursorExpr(C));
1666 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +00001667 return getDeclSpelling(D);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001668 return createCXString("");
Douglas Gregor97b98722010-01-19 23:20:36 +00001669 }
1670
Douglas Gregor4ae8f292010-03-18 17:52:52 +00001671 if (C.kind == CXCursor_MacroInstantiation)
1672 return createCXString(getCursorMacroInstantiation(C)->getName()
1673 ->getNameStart());
1674
Douglas Gregor572feb22010-03-18 18:04:21 +00001675 if (C.kind == CXCursor_MacroDefinition)
1676 return createCXString(getCursorMacroDefinition(C)->getName()
1677 ->getNameStart());
1678
Douglas Gregor60cbfac2010-01-25 16:56:17 +00001679 if (clang_isDeclaration(C.kind))
1680 return getDeclSpelling(getCursorDecl(C));
Ted Kremeneke68fff62010-02-17 00:41:32 +00001681
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001682 return createCXString("");
Steve Narofff334b4e2009-09-02 18:26:48 +00001683}
1684
Ted Kremeneke68fff62010-02-17 00:41:32 +00001685CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00001686 switch (Kind) {
Ted Kremeneke68fff62010-02-17 00:41:32 +00001687 case CXCursor_FunctionDecl:
1688 return createCXString("FunctionDecl");
1689 case CXCursor_TypedefDecl:
1690 return createCXString("TypedefDecl");
1691 case CXCursor_EnumDecl:
1692 return createCXString("EnumDecl");
1693 case CXCursor_EnumConstantDecl:
1694 return createCXString("EnumConstantDecl");
1695 case CXCursor_StructDecl:
1696 return createCXString("StructDecl");
1697 case CXCursor_UnionDecl:
1698 return createCXString("UnionDecl");
1699 case CXCursor_ClassDecl:
1700 return createCXString("ClassDecl");
1701 case CXCursor_FieldDecl:
1702 return createCXString("FieldDecl");
1703 case CXCursor_VarDecl:
1704 return createCXString("VarDecl");
1705 case CXCursor_ParmDecl:
1706 return createCXString("ParmDecl");
1707 case CXCursor_ObjCInterfaceDecl:
1708 return createCXString("ObjCInterfaceDecl");
1709 case CXCursor_ObjCCategoryDecl:
1710 return createCXString("ObjCCategoryDecl");
1711 case CXCursor_ObjCProtocolDecl:
1712 return createCXString("ObjCProtocolDecl");
1713 case CXCursor_ObjCPropertyDecl:
1714 return createCXString("ObjCPropertyDecl");
1715 case CXCursor_ObjCIvarDecl:
1716 return createCXString("ObjCIvarDecl");
1717 case CXCursor_ObjCInstanceMethodDecl:
1718 return createCXString("ObjCInstanceMethodDecl");
1719 case CXCursor_ObjCClassMethodDecl:
1720 return createCXString("ObjCClassMethodDecl");
1721 case CXCursor_ObjCImplementationDecl:
1722 return createCXString("ObjCImplementationDecl");
1723 case CXCursor_ObjCCategoryImplDecl:
1724 return createCXString("ObjCCategoryImplDecl");
Ted Kremenek8bd5a692010-04-13 23:39:06 +00001725 case CXCursor_CXXMethod:
1726 return createCXString("CXXMethod");
Ted Kremeneke68fff62010-02-17 00:41:32 +00001727 case CXCursor_UnexposedDecl:
1728 return createCXString("UnexposedDecl");
1729 case CXCursor_ObjCSuperClassRef:
1730 return createCXString("ObjCSuperClassRef");
1731 case CXCursor_ObjCProtocolRef:
1732 return createCXString("ObjCProtocolRef");
1733 case CXCursor_ObjCClassRef:
1734 return createCXString("ObjCClassRef");
1735 case CXCursor_TypeRef:
1736 return createCXString("TypeRef");
1737 case CXCursor_UnexposedExpr:
1738 return createCXString("UnexposedExpr");
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00001739 case CXCursor_BlockExpr:
1740 return createCXString("BlockExpr");
Ted Kremeneke68fff62010-02-17 00:41:32 +00001741 case CXCursor_DeclRefExpr:
1742 return createCXString("DeclRefExpr");
1743 case CXCursor_MemberRefExpr:
1744 return createCXString("MemberRefExpr");
1745 case CXCursor_CallExpr:
1746 return createCXString("CallExpr");
1747 case CXCursor_ObjCMessageExpr:
1748 return createCXString("ObjCMessageExpr");
1749 case CXCursor_UnexposedStmt:
1750 return createCXString("UnexposedStmt");
1751 case CXCursor_InvalidFile:
1752 return createCXString("InvalidFile");
Ted Kremenek292db642010-03-19 20:39:05 +00001753 case CXCursor_InvalidCode:
1754 return createCXString("InvalidCode");
Ted Kremeneke68fff62010-02-17 00:41:32 +00001755 case CXCursor_NoDeclFound:
1756 return createCXString("NoDeclFound");
1757 case CXCursor_NotImplemented:
1758 return createCXString("NotImplemented");
1759 case CXCursor_TranslationUnit:
1760 return createCXString("TranslationUnit");
Ted Kremeneke77f4432010-02-18 03:09:07 +00001761 case CXCursor_UnexposedAttr:
1762 return createCXString("UnexposedAttr");
1763 case CXCursor_IBActionAttr:
1764 return createCXString("attribute(ibaction)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00001765 case CXCursor_IBOutletAttr:
1766 return createCXString("attribute(iboutlet)");
Ted Kremenek857e9182010-05-19 17:38:06 +00001767 case CXCursor_IBOutletCollectionAttr:
1768 return createCXString("attribute(iboutletcollection)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00001769 case CXCursor_PreprocessingDirective:
1770 return createCXString("preprocessing directive");
Douglas Gregor572feb22010-03-18 18:04:21 +00001771 case CXCursor_MacroDefinition:
1772 return createCXString("macro definition");
Douglas Gregor48072312010-03-18 15:23:44 +00001773 case CXCursor_MacroInstantiation:
1774 return createCXString("macro instantiation");
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00001775 case CXCursor_Namespace:
1776 return createCXString("Namespace");
Ted Kremeneka0536d82010-05-07 01:04:29 +00001777 case CXCursor_LinkageSpec:
1778 return createCXString("LinkageSpec");
Steve Naroff89922f82009-08-31 00:59:03 +00001779 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00001780
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00001781 llvm_unreachable("Unhandled CXCursorKind");
Ted Kremeneke68fff62010-02-17 00:41:32 +00001782 return createCXString(NULL);
Steve Naroff600866c2009-08-27 19:51:58 +00001783}
Steve Naroff89922f82009-08-31 00:59:03 +00001784
Ted Kremeneke68fff62010-02-17 00:41:32 +00001785enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
1786 CXCursor parent,
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001787 CXClientData client_data) {
1788 CXCursor *BestCursor = static_cast<CXCursor *>(client_data);
1789 *BestCursor = cursor;
1790 return CXChildVisit_Recurse;
1791}
Ted Kremeneke68fff62010-02-17 00:41:32 +00001792
Douglas Gregorb9790342010-01-22 21:44:22 +00001793CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
1794 if (!TU)
Ted Kremenekf4629892010-01-14 01:51:23 +00001795 return clang_getNullCursor();
Ted Kremeneke68fff62010-02-17 00:41:32 +00001796
Douglas Gregorb9790342010-01-22 21:44:22 +00001797 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
1798
Douglas Gregorbdf60622010-03-05 21:16:25 +00001799 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
1800
Ted Kremeneka297de22010-01-25 22:34:44 +00001801 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001802 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
1803 if (SLoc.isValid()) {
Daniel Dunbard52864b2010-02-14 10:02:57 +00001804 SourceRange RegionOfInterest(SLoc, SLoc.getFileLocWithOffset(1));
Ted Kremeneke68fff62010-02-17 00:41:32 +00001805
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001806 // FIXME: Would be great to have a "hint" cursor, then walk from that
1807 // hint cursor upward until we find a cursor whose source range encloses
1808 // the region of interest, rather than starting from the translation unit.
1809 CXCursor Parent = clang_getTranslationUnitCursor(CXXUnit);
Ted Kremeneke68fff62010-02-17 00:41:32 +00001810 CursorVisitor CursorVis(CXXUnit, GetCursorVisitor, &Result,
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001811 Decl::MaxPCHLevel, RegionOfInterest);
1812 CursorVis.VisitChildren(Parent);
Steve Naroff77128dd2009-09-15 20:25:34 +00001813 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00001814 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00001815}
1816
Ted Kremenek73885552009-11-17 19:28:59 +00001817CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00001818 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00001819}
1820
1821unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00001822 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00001823}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001824
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001825unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00001826 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
1827}
1828
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001829unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +00001830 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
1831}
Steve Naroff2d4d6292009-08-31 14:26:51 +00001832
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001833unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00001834 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
1835}
1836
Douglas Gregor97b98722010-01-19 23:20:36 +00001837unsigned clang_isExpression(enum CXCursorKind K) {
1838 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
1839}
1840
1841unsigned clang_isStatement(enum CXCursorKind K) {
1842 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
1843}
1844
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001845unsigned clang_isTranslationUnit(enum CXCursorKind K) {
1846 return K == CXCursor_TranslationUnit;
1847}
1848
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00001849unsigned clang_isPreprocessing(enum CXCursorKind K) {
1850 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
1851}
1852
Ted Kremenekad6eff62010-03-08 21:17:29 +00001853unsigned clang_isUnexposed(enum CXCursorKind K) {
1854 switch (K) {
1855 case CXCursor_UnexposedDecl:
1856 case CXCursor_UnexposedExpr:
1857 case CXCursor_UnexposedStmt:
1858 case CXCursor_UnexposedAttr:
1859 return true;
1860 default:
1861 return false;
1862 }
1863}
1864
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001865CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00001866 return C.kind;
1867}
1868
Douglas Gregor98258af2010-01-18 22:46:11 +00001869CXSourceLocation clang_getCursorLocation(CXCursor C) {
1870 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00001871 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001872 case CXCursor_ObjCSuperClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00001873 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1874 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001875 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001876 }
1877
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001878 case CXCursor_ObjCProtocolRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00001879 std::pair<ObjCProtocolDecl *, SourceLocation> P
1880 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001881 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001882 }
1883
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001884 case CXCursor_ObjCClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00001885 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1886 = getCursorObjCClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001887 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001888 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001889
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001890 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001891 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001892 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001893 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001894
Douglas Gregorf46034a2010-01-18 23:41:10 +00001895 default:
1896 // FIXME: Need a way to enumerate all non-reference cases.
1897 llvm_unreachable("Missed a reference kind");
1898 }
Douglas Gregor98258af2010-01-18 22:46:11 +00001899 }
Douglas Gregor97b98722010-01-19 23:20:36 +00001900
1901 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001902 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00001903 getLocationFromExpr(getCursorExpr(C)));
1904
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00001905 if (C.kind == CXCursor_PreprocessingDirective) {
1906 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
1907 return cxloc::translateSourceLocation(getCursorContext(C), L);
1908 }
Douglas Gregor48072312010-03-18 15:23:44 +00001909
1910 if (C.kind == CXCursor_MacroInstantiation) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00001911 SourceLocation L
1912 = cxcursor::getCursorMacroInstantiation(C)->getSourceRange().getBegin();
Douglas Gregor48072312010-03-18 15:23:44 +00001913 return cxloc::translateSourceLocation(getCursorContext(C), L);
1914 }
Douglas Gregor572feb22010-03-18 18:04:21 +00001915
1916 if (C.kind == CXCursor_MacroDefinition) {
1917 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
1918 return cxloc::translateSourceLocation(getCursorContext(C), L);
1919 }
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00001920
Ted Kremenek9a700d22010-05-12 06:16:13 +00001921 if (C.kind < CXCursor_FirstDecl || C.kind > CXCursor_LastDecl)
Douglas Gregor5352ac02010-01-28 00:27:43 +00001922 return clang_getNullLocation();
Douglas Gregor98258af2010-01-18 22:46:11 +00001923
Douglas Gregorf46034a2010-01-18 23:41:10 +00001924 Decl *D = getCursorDecl(C);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001925 SourceLocation Loc = D->getLocation();
1926 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
1927 Loc = Class->getClassLoc();
Douglas Gregor2ca54fe2010-03-22 15:53:50 +00001928 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00001929}
Douglas Gregora7bde202010-01-19 00:34:46 +00001930
1931CXSourceRange clang_getCursorExtent(CXCursor C) {
1932 if (clang_isReference(C.kind)) {
1933 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001934 case CXCursor_ObjCSuperClassRef: {
Douglas Gregora7bde202010-01-19 00:34:46 +00001935 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1936 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001937 return cxloc::translateSourceRange(P.first->getASTContext(), P.second);
Douglas Gregora7bde202010-01-19 00:34:46 +00001938 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001939
1940 case CXCursor_ObjCProtocolRef: {
Douglas Gregora7bde202010-01-19 00:34:46 +00001941 std::pair<ObjCProtocolDecl *, SourceLocation> P
1942 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001943 return cxloc::translateSourceRange(P.first->getASTContext(), P.second);
Douglas Gregora7bde202010-01-19 00:34:46 +00001944 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001945
1946 case CXCursor_ObjCClassRef: {
Douglas Gregora7bde202010-01-19 00:34:46 +00001947 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1948 = getCursorObjCClassRef(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001949
Ted Kremeneka297de22010-01-25 22:34:44 +00001950 return cxloc::translateSourceRange(P.first->getASTContext(), P.second);
Douglas Gregora7bde202010-01-19 00:34:46 +00001951 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001952
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001953 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001954 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001955 return cxloc::translateSourceRange(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001956 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001957
Douglas Gregora7bde202010-01-19 00:34:46 +00001958 default:
1959 // FIXME: Need a way to enumerate all non-reference cases.
1960 llvm_unreachable("Missed a reference kind");
1961 }
1962 }
Douglas Gregor97b98722010-01-19 23:20:36 +00001963
1964 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001965 return cxloc::translateSourceRange(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00001966 getCursorExpr(C)->getSourceRange());
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001967
1968 if (clang_isStatement(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001969 return cxloc::translateSourceRange(getCursorContext(C),
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001970 getCursorStmt(C)->getSourceRange());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001971
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00001972 if (C.kind == CXCursor_PreprocessingDirective) {
1973 SourceRange R = cxcursor::getCursorPreprocessingDirective(C);
1974 return cxloc::translateSourceRange(getCursorContext(C), R);
1975 }
Douglas Gregor48072312010-03-18 15:23:44 +00001976
1977 if (C.kind == CXCursor_MacroInstantiation) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00001978 SourceRange R = cxcursor::getCursorMacroInstantiation(C)->getSourceRange();
Douglas Gregor48072312010-03-18 15:23:44 +00001979 return cxloc::translateSourceRange(getCursorContext(C), R);
1980 }
Douglas Gregor572feb22010-03-18 18:04:21 +00001981
1982 if (C.kind == CXCursor_MacroDefinition) {
1983 SourceRange R = cxcursor::getCursorMacroDefinition(C)->getSourceRange();
1984 return cxloc::translateSourceRange(getCursorContext(C), R);
1985 }
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00001986
Ted Kremenek9a700d22010-05-12 06:16:13 +00001987 if (C.kind < CXCursor_FirstDecl || C.kind > CXCursor_LastDecl)
Douglas Gregor5352ac02010-01-28 00:27:43 +00001988 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001989
Douglas Gregora7bde202010-01-19 00:34:46 +00001990 Decl *D = getCursorDecl(C);
Douglas Gregor2ca54fe2010-03-22 15:53:50 +00001991 return cxloc::translateSourceRange(getCursorContext(C), D->getSourceRange());
Douglas Gregora7bde202010-01-19 00:34:46 +00001992}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001993
1994CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001995 if (clang_isInvalid(C.kind))
1996 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001997
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001998 ASTUnit *CXXUnit = getCursorASTUnit(C);
Douglas Gregorb6998662010-01-19 19:34:47 +00001999 if (clang_isDeclaration(C.kind))
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002000 return C;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002001
Douglas Gregor97b98722010-01-19 23:20:36 +00002002 if (clang_isExpression(C.kind)) {
2003 Decl *D = getDeclFromExpr(getCursorExpr(C));
2004 if (D)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002005 return MakeCXCursor(D, CXXUnit);
Douglas Gregor97b98722010-01-19 23:20:36 +00002006 return clang_getNullCursor();
2007 }
2008
Douglas Gregorbf7efa22010-03-18 18:23:03 +00002009 if (C.kind == CXCursor_MacroInstantiation) {
2010 if (MacroDefinition *Def = getCursorMacroInstantiation(C)->getDefinition())
2011 return MakeMacroDefinitionCursor(Def, CXXUnit);
2012 }
2013
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002014 if (!clang_isReference(C.kind))
2015 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002016
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002017 switch (C.kind) {
2018 case CXCursor_ObjCSuperClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002019 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002020
2021 case CXCursor_ObjCProtocolRef: {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002022 return MakeCXCursor(getCursorObjCProtocolRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002023
2024 case CXCursor_ObjCClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002025 return MakeCXCursor(getCursorObjCClassRef(C).first, CXXUnit);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002026
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002027 case CXCursor_TypeRef:
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002028 return MakeCXCursor(getCursorTypeRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002029
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002030 default:
2031 // We would prefer to enumerate all non-reference cursor kinds here.
2032 llvm_unreachable("Unhandled reference cursor kind");
2033 break;
2034 }
2035 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002036
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002037 return clang_getNullCursor();
2038}
2039
Douglas Gregorb6998662010-01-19 19:34:47 +00002040CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002041 if (clang_isInvalid(C.kind))
2042 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002043
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002044 ASTUnit *CXXUnit = getCursorASTUnit(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002045
Douglas Gregorb6998662010-01-19 19:34:47 +00002046 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00002047 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00002048 C = clang_getCursorReferenced(C);
2049 WasReference = true;
2050 }
2051
Douglas Gregorbf7efa22010-03-18 18:23:03 +00002052 if (C.kind == CXCursor_MacroInstantiation)
2053 return clang_getCursorReferenced(C);
2054
Douglas Gregorb6998662010-01-19 19:34:47 +00002055 if (!clang_isDeclaration(C.kind))
2056 return clang_getNullCursor();
2057
2058 Decl *D = getCursorDecl(C);
2059 if (!D)
2060 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002061
Douglas Gregorb6998662010-01-19 19:34:47 +00002062 switch (D->getKind()) {
2063 // Declaration kinds that don't really separate the notions of
2064 // declaration and definition.
2065 case Decl::Namespace:
2066 case Decl::Typedef:
2067 case Decl::TemplateTypeParm:
2068 case Decl::EnumConstant:
2069 case Decl::Field:
2070 case Decl::ObjCIvar:
2071 case Decl::ObjCAtDefsField:
2072 case Decl::ImplicitParam:
2073 case Decl::ParmVar:
2074 case Decl::NonTypeTemplateParm:
2075 case Decl::TemplateTemplateParm:
2076 case Decl::ObjCCategoryImpl:
2077 case Decl::ObjCImplementation:
Abramo Bagnara6206d532010-06-05 05:09:32 +00002078 case Decl::AccessSpec:
Douglas Gregorb6998662010-01-19 19:34:47 +00002079 case Decl::LinkageSpec:
2080 case Decl::ObjCPropertyImpl:
2081 case Decl::FileScopeAsm:
2082 case Decl::StaticAssert:
2083 case Decl::Block:
2084 return C;
2085
2086 // Declaration kinds that don't make any sense here, but are
2087 // nonetheless harmless.
2088 case Decl::TranslationUnit:
Douglas Gregorb6998662010-01-19 19:34:47 +00002089 break;
2090
2091 // Declaration kinds for which the definition is not resolvable.
2092 case Decl::UnresolvedUsingTypename:
2093 case Decl::UnresolvedUsingValue:
2094 break;
2095
2096 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002097 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
2098 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002099
2100 case Decl::NamespaceAlias:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002101 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002102
2103 case Decl::Enum:
2104 case Decl::Record:
2105 case Decl::CXXRecord:
2106 case Decl::ClassTemplateSpecialization:
2107 case Decl::ClassTemplatePartialSpecialization:
Douglas Gregor952b0172010-02-11 01:04:33 +00002108 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002109 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002110 return clang_getNullCursor();
2111
2112 case Decl::Function:
2113 case Decl::CXXMethod:
2114 case Decl::CXXConstructor:
2115 case Decl::CXXDestructor:
2116 case Decl::CXXConversion: {
2117 const FunctionDecl *Def = 0;
2118 if (cast<FunctionDecl>(D)->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002119 return MakeCXCursor(const_cast<FunctionDecl *>(Def), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002120 return clang_getNullCursor();
2121 }
2122
2123 case Decl::Var: {
Sebastian Redl31310a22010-02-01 20:16:42 +00002124 // Ask the variable if it has a definition.
2125 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
2126 return MakeCXCursor(Def, CXXUnit);
2127 return clang_getNullCursor();
Douglas Gregorb6998662010-01-19 19:34:47 +00002128 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002129
Douglas Gregorb6998662010-01-19 19:34:47 +00002130 case Decl::FunctionTemplate: {
2131 const FunctionDecl *Def = 0;
2132 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002133 return MakeCXCursor(Def->getDescribedFunctionTemplate(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002134 return clang_getNullCursor();
2135 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002136
Douglas Gregorb6998662010-01-19 19:34:47 +00002137 case Decl::ClassTemplate: {
2138 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
Douglas Gregor952b0172010-02-11 01:04:33 +00002139 ->getDefinition())
Douglas Gregorb6998662010-01-19 19:34:47 +00002140 return MakeCXCursor(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002141 cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002142 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002143 return clang_getNullCursor();
2144 }
2145
2146 case Decl::Using: {
2147 UsingDecl *Using = cast<UsingDecl>(D);
2148 CXCursor Def = clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002149 for (UsingDecl::shadow_iterator S = Using->shadow_begin(),
2150 SEnd = Using->shadow_end();
Douglas Gregorb6998662010-01-19 19:34:47 +00002151 S != SEnd; ++S) {
2152 if (Def != clang_getNullCursor()) {
2153 // FIXME: We have no way to return multiple results.
2154 return clang_getNullCursor();
2155 }
2156
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002157 Def = clang_getCursorDefinition(MakeCXCursor((*S)->getTargetDecl(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002158 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002159 }
2160
2161 return Def;
2162 }
2163
2164 case Decl::UsingShadow:
2165 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002166 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002167 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002168
2169 case Decl::ObjCMethod: {
2170 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
2171 if (Method->isThisDeclarationADefinition())
2172 return C;
2173
2174 // Dig out the method definition in the associated
2175 // @implementation, if we have it.
2176 // FIXME: The ASTs should make finding the definition easier.
2177 if (ObjCInterfaceDecl *Class
2178 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
2179 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
2180 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
2181 Method->isInstanceMethod()))
2182 if (Def->isThisDeclarationADefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002183 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002184
2185 return clang_getNullCursor();
2186 }
2187
2188 case Decl::ObjCCategory:
2189 if (ObjCCategoryImplDecl *Impl
2190 = cast<ObjCCategoryDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002191 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002192 return clang_getNullCursor();
2193
2194 case Decl::ObjCProtocol:
2195 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
2196 return C;
2197 return clang_getNullCursor();
2198
2199 case Decl::ObjCInterface:
2200 // There are two notions of a "definition" for an Objective-C
2201 // class: the interface and its implementation. When we resolved a
2202 // reference to an Objective-C class, produce the @interface as
2203 // the definition; when we were provided with the interface,
2204 // produce the @implementation as the definition.
2205 if (WasReference) {
2206 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
2207 return C;
2208 } else if (ObjCImplementationDecl *Impl
2209 = cast<ObjCInterfaceDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002210 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002211 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002212
Douglas Gregorb6998662010-01-19 19:34:47 +00002213 case Decl::ObjCProperty:
2214 // FIXME: We don't really know where to find the
2215 // ObjCPropertyImplDecls that implement this property.
2216 return clang_getNullCursor();
2217
2218 case Decl::ObjCCompatibleAlias:
2219 if (ObjCInterfaceDecl *Class
2220 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
2221 if (!Class->isForwardDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002222 return MakeCXCursor(Class, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002223
Douglas Gregorb6998662010-01-19 19:34:47 +00002224 return clang_getNullCursor();
2225
2226 case Decl::ObjCForwardProtocol: {
2227 ObjCForwardProtocolDecl *Forward = cast<ObjCForwardProtocolDecl>(D);
2228 if (Forward->protocol_size() == 1)
2229 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002230 MakeCXCursor(*Forward->protocol_begin(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002231 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002232
2233 // FIXME: Cannot return multiple definitions.
2234 return clang_getNullCursor();
2235 }
2236
2237 case Decl::ObjCClass: {
2238 ObjCClassDecl *Class = cast<ObjCClassDecl>(D);
2239 if (Class->size() == 1) {
2240 ObjCInterfaceDecl *IFace = Class->begin()->getInterface();
2241 if (!IFace->isForwardDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002242 return MakeCXCursor(IFace, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002243 return clang_getNullCursor();
2244 }
2245
2246 // FIXME: Cannot return multiple definitions.
2247 return clang_getNullCursor();
2248 }
2249
2250 case Decl::Friend:
2251 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002252 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002253 return clang_getNullCursor();
2254
2255 case Decl::FriendTemplate:
2256 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002257 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002258 return clang_getNullCursor();
2259 }
2260
2261 return clang_getNullCursor();
2262}
2263
2264unsigned clang_isCursorDefinition(CXCursor C) {
2265 if (!clang_isDeclaration(C.kind))
2266 return 0;
2267
2268 return clang_getCursorDefinition(C) == C;
2269}
2270
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002271void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00002272 const char **startBuf,
2273 const char **endBuf,
2274 unsigned *startLine,
2275 unsigned *startColumn,
2276 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002277 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00002278 assert(getCursorDecl(C) && "CXCursor has null decl");
2279 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00002280 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
2281 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002282
Steve Naroff4ade6d62009-09-23 17:52:52 +00002283 SourceManager &SM = FD->getASTContext().getSourceManager();
2284 *startBuf = SM.getCharacterData(Body->getLBracLoc());
2285 *endBuf = SM.getCharacterData(Body->getRBracLoc());
2286 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
2287 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
2288 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
2289 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
2290}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002291
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002292void clang_enableStackTraces(void) {
2293 llvm::sys::PrintStackTraceOnErrorSignal();
2294}
2295
Ted Kremenekfb480492010-01-13 21:46:36 +00002296} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00002297
Ted Kremenekfb480492010-01-13 21:46:36 +00002298//===----------------------------------------------------------------------===//
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002299// Token-based Operations.
2300//===----------------------------------------------------------------------===//
2301
2302/* CXToken layout:
2303 * int_data[0]: a CXTokenKind
2304 * int_data[1]: starting token location
2305 * int_data[2]: token length
2306 * int_data[3]: reserved
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002307 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002308 * otherwise unused.
2309 */
2310extern "C" {
2311
2312CXTokenKind clang_getTokenKind(CXToken CXTok) {
2313 return static_cast<CXTokenKind>(CXTok.int_data[0]);
2314}
2315
2316CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
2317 switch (clang_getTokenKind(CXTok)) {
2318 case CXToken_Identifier:
2319 case CXToken_Keyword:
2320 // We know we have an IdentifierInfo*, so use that.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002321 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
2322 ->getNameStart());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002323
2324 case CXToken_Literal: {
2325 // We have stashed the starting pointer in the ptr_data field. Use it.
2326 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002327 return createCXString(llvm::StringRef(Text, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002328 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002329
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002330 case CXToken_Punctuation:
2331 case CXToken_Comment:
2332 break;
2333 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002334
2335 // We have to find the starting buffer pointer the hard way, by
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002336 // deconstructing the source location.
2337 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2338 if (!CXXUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002339 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002340
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002341 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
2342 std::pair<FileID, unsigned> LocInfo
2343 = CXXUnit->getSourceManager().getDecomposedLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +00002344 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002345 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00002346 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
2347 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00002348 return createCXString("");
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002349
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002350 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002351}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002352
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002353CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
2354 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2355 if (!CXXUnit)
2356 return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002357
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002358 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
2359 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
2360}
2361
2362CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
2363 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregor5352ac02010-01-28 00:27:43 +00002364 if (!CXXUnit)
2365 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002366
2367 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002368 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
2369}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002370
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002371void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
2372 CXToken **Tokens, unsigned *NumTokens) {
2373 if (Tokens)
2374 *Tokens = 0;
2375 if (NumTokens)
2376 *NumTokens = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002377
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002378 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2379 if (!CXXUnit || !Tokens || !NumTokens)
2380 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002381
Douglas Gregorbdf60622010-03-05 21:16:25 +00002382 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
2383
Daniel Dunbar85b988f2010-02-14 08:31:57 +00002384 SourceRange R = cxloc::translateCXSourceRange(Range);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002385 if (R.isInvalid())
2386 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002387
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002388 SourceManager &SourceMgr = CXXUnit->getSourceManager();
2389 std::pair<FileID, unsigned> BeginLocInfo
2390 = SourceMgr.getDecomposedLoc(R.getBegin());
2391 std::pair<FileID, unsigned> EndLocInfo
2392 = SourceMgr.getDecomposedLoc(R.getEnd());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002393
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002394 // Cannot tokenize across files.
2395 if (BeginLocInfo.first != EndLocInfo.first)
2396 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002397
2398 // Create a lexer
Douglas Gregorf715ca12010-03-16 00:06:06 +00002399 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002400 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00002401 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
Douglas Gregor47a3fcd2010-03-16 20:26:15 +00002402 if (Invalid)
2403 return;
Douglas Gregoraea67db2010-03-15 22:54:52 +00002404
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002405 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
2406 CXXUnit->getASTContext().getLangOptions(),
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002407 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002408 Lex.SetCommentRetentionState(true);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002409
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002410 // Lex tokens until we hit the end of the range.
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002411 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002412 llvm::SmallVector<CXToken, 32> CXTokens;
2413 Token Tok;
2414 do {
2415 // Lex the next token
2416 Lex.LexFromRawLexer(Tok);
2417 if (Tok.is(tok::eof))
2418 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002419
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002420 // Initialize the CXToken.
2421 CXToken CXTok;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002422
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002423 // - Common fields
2424 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
2425 CXTok.int_data[2] = Tok.getLength();
2426 CXTok.int_data[3] = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002427
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002428 // - Kind-specific fields
2429 if (Tok.isLiteral()) {
2430 CXTok.int_data[0] = CXToken_Literal;
2431 CXTok.ptr_data = (void *)Tok.getLiteralData();
2432 } else if (Tok.is(tok::identifier)) {
Douglas Gregoraea67db2010-03-15 22:54:52 +00002433 // Lookup the identifier to determine whether we have a keyword.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002434 std::pair<FileID, unsigned> LocInfo
2435 = SourceMgr.getDecomposedLoc(Tok.getLocation());
Douglas Gregorf715ca12010-03-16 00:06:06 +00002436 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002437 llvm::StringRef Buf
Douglas Gregorf715ca12010-03-16 00:06:06 +00002438 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
2439 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00002440 return;
2441
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002442 const char *StartPos = Buf.data() + LocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002443 IdentifierInfo *II
2444 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok, StartPos);
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00002445
2446 if (II->getObjCKeywordID() != tok::objc_not_keyword) {
2447 CXTok.int_data[0] = CXToken_Keyword;
2448 }
2449 else {
2450 CXTok.int_data[0] = II->getTokenID() == tok::identifier?
2451 CXToken_Identifier
2452 : CXToken_Keyword;
2453 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002454 CXTok.ptr_data = II;
2455 } else if (Tok.is(tok::comment)) {
2456 CXTok.int_data[0] = CXToken_Comment;
2457 CXTok.ptr_data = 0;
2458 } else {
2459 CXTok.int_data[0] = CXToken_Punctuation;
2460 CXTok.ptr_data = 0;
2461 }
2462 CXTokens.push_back(CXTok);
2463 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002464
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002465 if (CXTokens.empty())
2466 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002467
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002468 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
2469 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
2470 *NumTokens = CXTokens.size();
2471}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002472
Ted Kremenek6db61092010-05-05 00:55:15 +00002473void clang_disposeTokens(CXTranslationUnit TU,
2474 CXToken *Tokens, unsigned NumTokens) {
2475 free(Tokens);
2476}
2477
2478} // end: extern "C"
2479
2480//===----------------------------------------------------------------------===//
2481// Token annotation APIs.
2482//===----------------------------------------------------------------------===//
2483
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002484typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002485static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
2486 CXCursor parent,
2487 CXClientData client_data);
Ted Kremenek6db61092010-05-05 00:55:15 +00002488namespace {
2489class AnnotateTokensWorker {
2490 AnnotateTokensData &Annotated;
Ted Kremenek11949cb2010-05-05 00:55:17 +00002491 CXToken *Tokens;
2492 CXCursor *Cursors;
2493 unsigned NumTokens;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002494 unsigned TokIdx;
2495 CursorVisitor AnnotateVis;
2496 SourceManager &SrcMgr;
2497
2498 bool MoreTokens() const { return TokIdx < NumTokens; }
2499 unsigned NextToken() const { return TokIdx; }
2500 void AdvanceToken() { ++TokIdx; }
2501 SourceLocation GetTokenLoc(unsigned tokI) {
2502 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
2503 }
2504
Ted Kremenek6db61092010-05-05 00:55:15 +00002505public:
Ted Kremenek11949cb2010-05-05 00:55:17 +00002506 AnnotateTokensWorker(AnnotateTokensData &annotated,
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002507 CXToken *tokens, CXCursor *cursors, unsigned numTokens,
2508 ASTUnit *CXXUnit, SourceRange RegionOfInterest)
Ted Kremenek11949cb2010-05-05 00:55:17 +00002509 : Annotated(annotated), Tokens(tokens), Cursors(cursors),
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002510 NumTokens(numTokens), TokIdx(0),
2511 AnnotateVis(CXXUnit, AnnotateTokensVisitor, this,
2512 Decl::MaxPCHLevel, RegionOfInterest),
2513 SrcMgr(CXXUnit->getSourceManager()) {}
Ted Kremenek11949cb2010-05-05 00:55:17 +00002514
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002515 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
Ted Kremenek6db61092010-05-05 00:55:15 +00002516 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002517 void AnnotateTokens(CXCursor parent);
Ted Kremenek6db61092010-05-05 00:55:15 +00002518};
2519}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002520
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002521void AnnotateTokensWorker::AnnotateTokens(CXCursor parent) {
2522 // Walk the AST within the region of interest, annotating tokens
2523 // along the way.
2524 VisitChildren(parent);
Ted Kremenek11949cb2010-05-05 00:55:17 +00002525
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002526 for (unsigned I = 0 ; I < TokIdx ; ++I) {
2527 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
2528 if (Pos != Annotated.end())
2529 Cursors[I] = Pos->second;
2530 }
2531
2532 // Finish up annotating any tokens left.
2533 if (!MoreTokens())
2534 return;
2535
2536 const CXCursor &C = clang_getNullCursor();
2537 for (unsigned I = TokIdx ; I < NumTokens ; ++I) {
2538 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
2539 Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second;
Ted Kremenek11949cb2010-05-05 00:55:17 +00002540 }
2541}
2542
Ted Kremenek6db61092010-05-05 00:55:15 +00002543enum CXChildVisitResult
2544AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002545 CXSourceLocation Loc = clang_getCursorLocation(cursor);
2546 // We can always annotate a preprocessing directive/macro instantiation.
2547 if (clang_isPreprocessing(cursor.kind)) {
2548 Annotated[Loc.int_data] = cursor;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002549 return CXChildVisit_Recurse;
2550 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002551
2552 CXSourceRange cursorExtent = clang_getCursorExtent(cursor);
2553 SourceRange cursorRange = cxloc::translateCXSourceRange(cursorExtent);
Ted Kremeneka333c662010-05-12 05:29:33 +00002554
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002555 if (cursorRange.isInvalid())
2556 return CXChildVisit_Continue;
Ted Kremeneka333c662010-05-12 05:29:33 +00002557
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002558 SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data);
2559
Ted Kremeneka333c662010-05-12 05:29:33 +00002560 // Adjust the annotated range based specific declarations.
2561 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
2562 if (cursorK >= CXCursor_FirstDecl && cursorK <= CXCursor_LastDecl) {
Ted Kremenek23173d72010-05-18 21:09:07 +00002563 Decl *D = cxcursor::getCursorDecl(cursor);
2564 // Don't visit synthesized ObjC methods, since they have no syntatic
2565 // representation in the source.
2566 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
2567 if (MD->isSynthesized())
2568 return CXChildVisit_Continue;
2569 }
2570 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
Ted Kremeneka333c662010-05-12 05:29:33 +00002571 if (TypeSourceInfo *TI = DD->getTypeSourceInfo()) {
2572 TypeLoc TL = TI->getTypeLoc();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00002573 SourceLocation TLoc = TL.getSourceRange().getBegin();
Ted Kremenek6bfd5332010-05-13 15:38:38 +00002574 if (TLoc.isValid() &&
2575 SrcMgr.isBeforeInTranslationUnit(TLoc, L))
Ted Kremeneka333c662010-05-12 05:29:33 +00002576 cursorRange.setBegin(TLoc);
Ted Kremeneka333c662010-05-12 05:29:33 +00002577 }
2578 }
2579 }
2580
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002581 const enum CXCursorKind K = clang_getCursorKind(parent);
2582 const CXCursor updateC =
2583 (clang_isInvalid(K) || K == CXCursor_TranslationUnit ||
2584 L.isMacroID())
2585 ? clang_getNullCursor() : parent;
2586
2587 while (MoreTokens()) {
2588 const unsigned I = NextToken();
2589 SourceLocation TokLoc = GetTokenLoc(I);
2590 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
2591 case RangeBefore:
2592 Cursors[I] = updateC;
2593 AdvanceToken();
2594 continue;
2595 case RangeAfter:
2596 return CXChildVisit_Continue;
2597 case RangeOverlap:
2598 break;
2599 }
2600 break;
2601 }
2602
2603 // Visit children to get their cursor information.
2604 const unsigned BeforeChildren = NextToken();
2605 VisitChildren(cursor);
2606 const unsigned AfterChildren = NextToken();
2607
2608 // Adjust 'Last' to the last token within the extent of the cursor.
2609 while (MoreTokens()) {
2610 const unsigned I = NextToken();
2611 SourceLocation TokLoc = GetTokenLoc(I);
2612 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
2613 case RangeBefore:
2614 assert(0 && "Infeasible");
2615 case RangeAfter:
2616 break;
2617 case RangeOverlap:
2618 Cursors[I] = updateC;
2619 AdvanceToken();
2620 continue;
2621 }
2622 break;
2623 }
2624 const unsigned Last = NextToken();
Ted Kremenek6db61092010-05-05 00:55:15 +00002625
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002626 // Scan the tokens that are at the beginning of the cursor, but are not
2627 // capture by the child cursors.
2628
2629 // For AST elements within macros, rely on a post-annotate pass to
2630 // to correctly annotate the tokens with cursors. Otherwise we can
2631 // get confusing results of having tokens that map to cursors that really
2632 // are expanded by an instantiation.
2633 if (L.isMacroID())
2634 cursor = clang_getNullCursor();
2635
2636 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
2637 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
2638 break;
2639 Cursors[I] = cursor;
2640 }
2641 // Scan the tokens that are at the end of the cursor, but are not captured
2642 // but the child cursors.
2643 for (unsigned I = AfterChildren; I != Last; ++I)
2644 Cursors[I] = cursor;
2645
2646 TokIdx = Last;
2647 return CXChildVisit_Continue;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002648}
2649
Ted Kremenek6db61092010-05-05 00:55:15 +00002650static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
2651 CXCursor parent,
2652 CXClientData client_data) {
2653 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
2654}
2655
2656extern "C" {
2657
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002658void clang_annotateTokens(CXTranslationUnit TU,
2659 CXToken *Tokens, unsigned NumTokens,
2660 CXCursor *Cursors) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002661
2662 if (NumTokens == 0 || !Tokens || !Cursors)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002663 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002664
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002665 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002666 if (!CXXUnit) {
2667 // Any token we don't specifically annotate will have a NULL cursor.
2668 const CXCursor &C = clang_getNullCursor();
2669 for (unsigned I = 0; I != NumTokens; ++I)
2670 Cursors[I] = C;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002671 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002672 }
2673
Douglas Gregorbdf60622010-03-05 21:16:25 +00002674 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002675
Douglas Gregor0396f462010-03-19 05:22:59 +00002676 // Determine the region of interest, which contains all of the tokens.
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002677 SourceRange RegionOfInterest;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002678 RegionOfInterest.setBegin(cxloc::translateSourceLocation(
2679 clang_getTokenLocation(TU, Tokens[0])));
2680
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002681 SourceLocation End
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002682 = cxloc::translateSourceLocation(clang_getTokenLocation(TU,
2683 Tokens[NumTokens - 1]));
Daniel Dunbard52864b2010-02-14 10:02:57 +00002684 RegionOfInterest.setEnd(CXXUnit->getPreprocessor().getLocForEndOfToken(End));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002685
Douglas Gregor0396f462010-03-19 05:22:59 +00002686 // A mapping from the source locations found when re-lexing or traversing the
2687 // region of interest to the corresponding cursors.
2688 AnnotateTokensData Annotated;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002689
2690 // Relex the tokens within the source range to look for preprocessing
Douglas Gregor0396f462010-03-19 05:22:59 +00002691 // directives.
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002692 SourceManager &SourceMgr = CXXUnit->getSourceManager();
2693 std::pair<FileID, unsigned> BeginLocInfo
2694 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
2695 std::pair<FileID, unsigned> EndLocInfo
2696 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002697
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002698 llvm::StringRef Buffer;
Douglas Gregor0396f462010-03-19 05:22:59 +00002699 bool Invalid = false;
2700 if (BeginLocInfo.first == EndLocInfo.first &&
2701 ((Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid)),true) &&
2702 !Invalid) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002703 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
2704 CXXUnit->getASTContext().getLangOptions(),
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002705 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002706 Buffer.end());
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002707 Lex.SetCommentRetentionState(true);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002708
2709 // Lex tokens in raw mode until we hit the end of the range, to avoid
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002710 // entering #includes or expanding macros.
Douglas Gregor48072312010-03-18 15:23:44 +00002711 while (true) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002712 Token Tok;
2713 Lex.LexFromRawLexer(Tok);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002714
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002715 reprocess:
2716 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
2717 // We have found a preprocessing directive. Gobble it up so that we
2718 // don't see it while preprocessing these tokens later, but keep track of
2719 // all of the token locations inside this preprocessing directive so that
2720 // we can annotate them appropriately.
2721 //
2722 // FIXME: Some simple tests here could identify macro definitions and
2723 // #undefs, to provide specific cursor kinds for those.
2724 std::vector<SourceLocation> Locations;
2725 do {
2726 Locations.push_back(Tok.getLocation());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002727 Lex.LexFromRawLexer(Tok);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002728 } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002729
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002730 using namespace cxcursor;
2731 CXCursor Cursor
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002732 = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
2733 Locations.back()),
Ted Kremenek6db61092010-05-05 00:55:15 +00002734 CXXUnit);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002735 for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
2736 Annotated[Locations[I].getRawEncoding()] = Cursor;
2737 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002738
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002739 if (Tok.isAtStartOfLine())
2740 goto reprocess;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002741
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002742 continue;
2743 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002744
Douglas Gregor48072312010-03-18 15:23:44 +00002745 if (Tok.is(tok::eof))
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002746 break;
2747 }
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002748 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002749
Douglas Gregor0396f462010-03-19 05:22:59 +00002750 // Annotate all of the source locations in the region of interest that map to
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002751 // a specific cursor.
2752 AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens,
2753 CXXUnit, RegionOfInterest);
2754 W.AnnotateTokens(clang_getTranslationUnitCursor(CXXUnit));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002755}
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002756} // end: extern "C"
2757
2758//===----------------------------------------------------------------------===//
Ted Kremenek16b42592010-03-03 06:36:57 +00002759// Operations for querying linkage of a cursor.
2760//===----------------------------------------------------------------------===//
2761
2762extern "C" {
2763CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
Douglas Gregor0396f462010-03-19 05:22:59 +00002764 if (!clang_isDeclaration(cursor.kind))
2765 return CXLinkage_Invalid;
2766
Ted Kremenek16b42592010-03-03 06:36:57 +00002767 Decl *D = cxcursor::getCursorDecl(cursor);
2768 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
2769 switch (ND->getLinkage()) {
2770 case NoLinkage: return CXLinkage_NoLinkage;
2771 case InternalLinkage: return CXLinkage_Internal;
2772 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
2773 case ExternalLinkage: return CXLinkage_External;
2774 };
2775
2776 return CXLinkage_Invalid;
2777}
2778} // end: extern "C"
2779
2780//===----------------------------------------------------------------------===//
Ted Kremenek45e1dae2010-04-12 21:22:16 +00002781// Operations for querying language of a cursor.
2782//===----------------------------------------------------------------------===//
2783
2784static CXLanguageKind getDeclLanguage(const Decl *D) {
2785 switch (D->getKind()) {
2786 default:
2787 break;
2788 case Decl::ImplicitParam:
2789 case Decl::ObjCAtDefsField:
2790 case Decl::ObjCCategory:
2791 case Decl::ObjCCategoryImpl:
2792 case Decl::ObjCClass:
2793 case Decl::ObjCCompatibleAlias:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00002794 case Decl::ObjCForwardProtocol:
2795 case Decl::ObjCImplementation:
2796 case Decl::ObjCInterface:
2797 case Decl::ObjCIvar:
2798 case Decl::ObjCMethod:
2799 case Decl::ObjCProperty:
2800 case Decl::ObjCPropertyImpl:
2801 case Decl::ObjCProtocol:
2802 return CXLanguage_ObjC;
2803 case Decl::CXXConstructor:
2804 case Decl::CXXConversion:
2805 case Decl::CXXDestructor:
2806 case Decl::CXXMethod:
2807 case Decl::CXXRecord:
2808 case Decl::ClassTemplate:
2809 case Decl::ClassTemplatePartialSpecialization:
2810 case Decl::ClassTemplateSpecialization:
2811 case Decl::Friend:
2812 case Decl::FriendTemplate:
2813 case Decl::FunctionTemplate:
2814 case Decl::LinkageSpec:
2815 case Decl::Namespace:
2816 case Decl::NamespaceAlias:
2817 case Decl::NonTypeTemplateParm:
2818 case Decl::StaticAssert:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00002819 case Decl::TemplateTemplateParm:
2820 case Decl::TemplateTypeParm:
2821 case Decl::UnresolvedUsingTypename:
2822 case Decl::UnresolvedUsingValue:
2823 case Decl::Using:
2824 case Decl::UsingDirective:
2825 case Decl::UsingShadow:
2826 return CXLanguage_CPlusPlus;
2827 }
2828
2829 return CXLanguage_C;
2830}
2831
2832extern "C" {
2833CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
2834 if (clang_isDeclaration(cursor.kind))
2835 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
2836
2837 return CXLanguage_Invalid;
2838}
2839} // end: extern "C"
2840
Ted Kremenek9ada39a2010-05-17 20:06:56 +00002841
2842//===----------------------------------------------------------------------===//
2843// C++ AST instrospection.
2844//===----------------------------------------------------------------------===//
2845
2846extern "C" {
2847unsigned clang_CXXMethod_isStatic(CXCursor C) {
2848 if (!clang_isDeclaration(C.kind))
2849 return 0;
2850 CXXMethodDecl *D = dyn_cast<CXXMethodDecl>(cxcursor::getCursorDecl(C));
2851 return (D && D->isStatic()) ? 1 : 0;
Ted Kremenek40b492a2010-05-17 20:12:45 +00002852}
Ted Kremenekb12903e2010-05-18 22:32:15 +00002853
Ted Kremenek9ada39a2010-05-17 20:06:56 +00002854} // end: extern "C"
2855
Ted Kremenek45e1dae2010-04-12 21:22:16 +00002856//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00002857// CXString Operations.
2858//===----------------------------------------------------------------------===//
2859
2860extern "C" {
2861const char *clang_getCString(CXString string) {
2862 return string.Spelling;
2863}
2864
2865void clang_disposeString(CXString string) {
2866 if (string.MustFreeString && string.Spelling)
2867 free((void*)string.Spelling);
2868}
Ted Kremenek04bb7162010-01-22 22:44:15 +00002869
Ted Kremenekfb480492010-01-13 21:46:36 +00002870} // end: extern "C"
Ted Kremenek04bb7162010-01-22 22:44:15 +00002871
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002872namespace clang { namespace cxstring {
2873CXString createCXString(const char *String, bool DupString){
2874 CXString Str;
2875 if (DupString) {
2876 Str.Spelling = strdup(String);
2877 Str.MustFreeString = 1;
2878 } else {
2879 Str.Spelling = String;
2880 Str.MustFreeString = 0;
2881 }
2882 return Str;
2883}
2884
2885CXString createCXString(llvm::StringRef String, bool DupString) {
2886 CXString Result;
2887 if (DupString || (!String.empty() && String.data()[String.size()] != 0)) {
2888 char *Spelling = (char *)malloc(String.size() + 1);
2889 memmove(Spelling, String.data(), String.size());
2890 Spelling[String.size()] = 0;
2891 Result.Spelling = Spelling;
2892 Result.MustFreeString = 1;
2893 } else {
2894 Result.Spelling = String.data();
2895 Result.MustFreeString = 0;
2896 }
2897 return Result;
2898}
2899}}
2900
Ted Kremenek04bb7162010-01-22 22:44:15 +00002901//===----------------------------------------------------------------------===//
2902// Misc. utility functions.
2903//===----------------------------------------------------------------------===//
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002904
Ted Kremenek04bb7162010-01-22 22:44:15 +00002905extern "C" {
2906
Ted Kremeneka2a9d6e2010-02-12 22:54:40 +00002907CXString clang_getClangVersion() {
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002908 return createCXString(getClangFullVersion());
Ted Kremenek04bb7162010-01-22 22:44:15 +00002909}
2910
2911} // end: extern "C"