blob: 51965bb8a13b3473919178b727032e6fc52ebe54 [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?");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000146 if (R1.getEnd() != R2.getBegin() &&
Daniel Dunbard52864b2010-02-14 10:02:57 +0000147 SM.isBeforeInTranslationUnit(R1.getEnd(), R2.getBegin()))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000148 return RangeBefore;
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000149 if (R2.getEnd() != R1.getBegin() &&
Daniel Dunbard52864b2010-02-14 10:02:57 +0000150 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?");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000161 if (L == R.getBegin() || L == R.getEnd())
Ted Kremenekfbd84ca2010-05-05 00:55:23 +0000162 return RangeOverlap;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +0000163 if (SM.isBeforeInTranslationUnit(L, R.getBegin()))
164 return RangeBefore;
165 if (SM.isBeforeInTranslationUnit(R.getEnd(), L))
166 return RangeAfter;
167 return RangeOverlap;
168}
169
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000170/// \brief Translate a Clang source range into a CIndex source range.
171///
172/// Clang internally represents ranges where the end location points to the
173/// start of the token at the end. However, for external clients it is more
174/// useful to have a CXSourceRange be a proper half-open interval. This routine
175/// does the appropriate translation.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000176CXSourceRange cxloc::translateSourceRange(const SourceManager &SM,
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000177 const LangOptions &LangOpts,
Chris Lattner0a76aae2010-06-18 22:45:06 +0000178 const CharSourceRange &R) {
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000179 // We want the last character in this location, so we will adjust the
Douglas Gregor6a5a23f2010-03-19 21:51:54 +0000180 // location accordingly.
181 // FIXME: How do do this with a macro instantiation location?
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000182 SourceLocation EndLoc = R.getEnd();
Chris Lattner0a76aae2010-06-18 22:45:06 +0000183 if (R.isTokenRange() && !EndLoc.isInvalid() && EndLoc.isFileID()) {
Douglas Gregor6a5a23f2010-03-19 21:51:54 +0000184 unsigned Length = Lexer::MeasureTokenLength(EndLoc, SM, LangOpts);
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000185 EndLoc = EndLoc.getFileLocWithOffset(Length);
186 }
187
188 CXSourceRange Result = { { (void *)&SM, (void *)&LangOpts },
189 R.getBegin().getRawEncoding(),
190 EndLoc.getRawEncoding() };
191 return Result;
192}
Douglas Gregor1db19de2010-01-19 21:36:55 +0000193
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000194//===----------------------------------------------------------------------===//
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000195// Cursor visitor.
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000196//===----------------------------------------------------------------------===//
197
Steve Naroff89922f82009-08-31 00:59:03 +0000198namespace {
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000199
Douglas Gregorb1373d02010-01-20 20:59:29 +0000200// Cursor visitor.
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000201class CursorVisitor : public DeclVisitor<CursorVisitor, bool>,
Douglas Gregora59e3902010-01-21 23:27:09 +0000202 public TypeLocVisitor<CursorVisitor, bool>,
203 public StmtVisitor<CursorVisitor, bool>
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000204{
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000205 /// \brief The translation unit we are traversing.
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000206 ASTUnit *TU;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000207
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000208 /// \brief The parent cursor whose children we are traversing.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000209 CXCursor Parent;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000210
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000211 /// \brief The declaration that serves at the parent of any statement or
212 /// expression nodes.
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000213 Decl *StmtParent;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000214
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000215 /// \brief The visitor function.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000216 CXCursorVisitor Visitor;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000217
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000218 /// \brief The opaque client data, to be passed along to the visitor.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000219 CXClientData ClientData;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000220
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000221 // MaxPCHLevel - the maximum PCH level of declarations that we will pass on
222 // to the visitor. Declarations with a PCH level greater than this value will
223 // be suppressed.
224 unsigned MaxPCHLevel;
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000225
226 /// \brief When valid, a source range to which the cursor should restrict
227 /// its search.
228 SourceRange RegionOfInterest;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000229
Douglas Gregorb1373d02010-01-20 20:59:29 +0000230 using DeclVisitor<CursorVisitor, bool>::Visit;
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000231 using TypeLocVisitor<CursorVisitor, bool>::Visit;
Douglas Gregora59e3902010-01-21 23:27:09 +0000232 using StmtVisitor<CursorVisitor, bool>::Visit;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000233
234 /// \brief Determine whether this particular source range comes before, comes
235 /// after, or overlaps the region of interest.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000236 ///
Daniel Dunbard52864b2010-02-14 10:02:57 +0000237 /// \param R a half-open source range retrieved from the abstract syntax tree.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000238 RangeComparisonResult CompareRegionOfInterest(SourceRange R);
239
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000240 class SetParentRAII {
241 CXCursor &Parent;
242 Decl *&StmtParent;
243 CXCursor OldParent;
244
245 public:
246 SetParentRAII(CXCursor &Parent, Decl *&StmtParent, CXCursor NewParent)
247 : Parent(Parent), StmtParent(StmtParent), OldParent(Parent)
248 {
249 Parent = NewParent;
250 if (clang_isDeclaration(Parent.kind))
251 StmtParent = getCursorDecl(Parent);
252 }
253
254 ~SetParentRAII() {
255 Parent = OldParent;
256 if (clang_isDeclaration(Parent.kind))
257 StmtParent = getCursorDecl(Parent);
258 }
259 };
260
Steve Naroff89922f82009-08-31 00:59:03 +0000261public:
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000262 CursorVisitor(ASTUnit *TU, CXCursorVisitor Visitor, CXClientData ClientData,
263 unsigned MaxPCHLevel,
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000264 SourceRange RegionOfInterest = SourceRange())
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000265 : TU(TU), Visitor(Visitor), ClientData(ClientData),
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000266 MaxPCHLevel(MaxPCHLevel), RegionOfInterest(RegionOfInterest)
Douglas Gregorb1373d02010-01-20 20:59:29 +0000267 {
268 Parent.kind = CXCursor_NoDeclFound;
269 Parent.data[0] = 0;
270 Parent.data[1] = 0;
271 Parent.data[2] = 0;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000272 StmtParent = 0;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000273 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000274
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000275 bool Visit(CXCursor Cursor, bool CheckedRegionOfInterest = false);
Douglas Gregor788f5a12010-03-20 00:41:21 +0000276
277 std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
278 getPreprocessedEntities();
279
Douglas Gregorb1373d02010-01-20 20:59:29 +0000280 bool VisitChildren(CXCursor Parent);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000281
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000282 // Declaration visitors
Ted Kremenek09dfa372010-02-18 05:46:33 +0000283 bool VisitAttributes(Decl *D);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000284 bool VisitBlockDecl(BlockDecl *B);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000285 bool VisitDeclContext(DeclContext *DC);
Ted Kremenek4540c9c2010-02-18 18:47:08 +0000286 bool VisitTranslationUnitDecl(TranslationUnitDecl *D);
287 bool VisitTypedefDecl(TypedefDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000288 bool VisitTagDecl(TagDecl *D);
289 bool VisitEnumConstantDecl(EnumConstantDecl *D);
290 bool VisitDeclaratorDecl(DeclaratorDecl *DD);
291 bool VisitFunctionDecl(FunctionDecl *ND);
292 bool VisitFieldDecl(FieldDecl *D);
Ted Kremenek4540c9c2010-02-18 18:47:08 +0000293 bool VisitVarDecl(VarDecl *);
Ted Kremenek79758f62010-02-18 22:36:18 +0000294 bool VisitObjCMethodDecl(ObjCMethodDecl *ND);
295 bool VisitObjCContainerDecl(ObjCContainerDecl *D);
296 bool VisitObjCCategoryDecl(ObjCCategoryDecl *ND);
297 bool VisitObjCProtocolDecl(ObjCProtocolDecl *PID);
Ted Kremenek23173d72010-05-18 21:09:07 +0000298 bool VisitObjCPropertyDecl(ObjCPropertyDecl *PD);
Ted Kremenek79758f62010-02-18 22:36:18 +0000299 bool VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
300 bool VisitObjCImplDecl(ObjCImplDecl *D);
301 bool VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
302 bool VisitObjCImplementationDecl(ObjCImplementationDecl *D);
303 // FIXME: ObjCPropertyDecl requires TypeSourceInfo, getter/setter locations,
304 // etc.
305 // FIXME: ObjCCompatibleAliasDecl requires aliased-class locations.
306 bool VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D);
307 bool VisitObjCClassDecl(ObjCClassDecl *D);
Ted Kremeneka0536d82010-05-07 01:04:29 +0000308 bool VisitLinkageSpecDecl(LinkageSpecDecl *D);
Ted Kremenek8f06e0e2010-05-06 23:38:21 +0000309 bool VisitNamespaceDecl(NamespaceDecl *D);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000310
311 // Type visitors
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000312 // FIXME: QualifiedTypeLoc doesn't provide any location information
313 bool VisitBuiltinTypeLoc(BuiltinTypeLoc TL);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000314 bool VisitTypedefTypeLoc(TypedefTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000315 bool VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL);
316 bool VisitTagTypeLoc(TagTypeLoc TL);
317 // FIXME: TemplateTypeParmTypeLoc doesn't provide any location information
318 bool VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL);
John McCallc12c5bb2010-05-15 11:32:37 +0000319 bool VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000320 bool VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL);
321 bool VisitPointerTypeLoc(PointerTypeLoc TL);
322 bool VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL);
323 bool VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL);
324 bool VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL);
325 bool VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL);
326 bool VisitFunctionTypeLoc(FunctionTypeLoc TL);
327 bool VisitArrayTypeLoc(ArrayTypeLoc TL);
Douglas Gregor2332c112010-01-21 20:48:56 +0000328 // FIXME: Implement for TemplateSpecializationTypeLoc
329 // FIXME: Implement visitors here when the unimplemented TypeLocs get
330 // implemented
331 bool VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL);
332 bool VisitTypeOfTypeLoc(TypeOfTypeLoc TL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000333
Douglas Gregora59e3902010-01-21 23:27:09 +0000334 // Statement visitors
335 bool VisitStmt(Stmt *S);
336 bool VisitDeclStmt(DeclStmt *S);
Douglas Gregorf5bab412010-01-22 01:00:11 +0000337 // FIXME: LabelStmt label?
338 bool VisitIfStmt(IfStmt *S);
339 bool VisitSwitchStmt(SwitchStmt *S);
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000340 bool VisitCaseStmt(CaseStmt *S);
Douglas Gregor263b47b2010-01-25 16:12:32 +0000341 bool VisitWhileStmt(WhileStmt *S);
342 bool VisitForStmt(ForStmt *S);
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000343// bool VisitSwitchCase(SwitchCase *S);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000344
Douglas Gregor336fd812010-01-23 00:40:08 +0000345 // Expression visitors
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000346 bool VisitBlockExpr(BlockExpr *B);
Douglas Gregor336fd812010-01-23 00:40:08 +0000347 bool VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000348 bool VisitExplicitCastExpr(ExplicitCastExpr *E);
Douglas Gregorc2350e52010-03-08 16:40:19 +0000349 bool VisitObjCMessageExpr(ObjCMessageExpr *E);
Douglas Gregor81d34662010-04-20 15:39:42 +0000350 bool VisitObjCEncodeExpr(ObjCEncodeExpr *E);
Douglas Gregor8ecdb652010-04-28 22:16:22 +0000351 bool VisitOffsetOfExpr(OffsetOfExpr *E);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000352 bool VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E);
Steve Naroff89922f82009-08-31 00:59:03 +0000353};
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000354
Ted Kremenekab188932010-01-05 19:32:54 +0000355} // end anonymous namespace
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000356
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000357static SourceRange getRawCursorExtent(CXCursor C);
358
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) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000390 SourceRange Range = getRawCursorExtent(Cursor);
Daniel Dunbarf408f322010-02-14 08:32:05 +0000391 if (Range.isInvalid() || CompareRegionOfInterest(Range))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000392 return false;
393 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000394
Douglas Gregorb1373d02010-01-20 20:59:29 +0000395 switch (Visitor(Cursor, Parent, ClientData)) {
396 case CXChildVisit_Break:
397 return true;
398
399 case CXChildVisit_Continue:
400 return false;
401
402 case CXChildVisit_Recurse:
403 return VisitChildren(Cursor);
404 }
405
Douglas Gregorfd643772010-01-25 16:45:46 +0000406 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000407}
408
Douglas Gregor788f5a12010-03-20 00:41:21 +0000409std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
410CursorVisitor::getPreprocessedEntities() {
411 PreprocessingRecord &PPRec
412 = *TU->getPreprocessor().getPreprocessingRecord();
413
414 bool OnlyLocalDecls
415 = !TU->isMainFileAST() && TU->getOnlyLocalDecls();
416
417 // There is no region of interest; we have to walk everything.
418 if (RegionOfInterest.isInvalid())
419 return std::make_pair(PPRec.begin(OnlyLocalDecls),
420 PPRec.end(OnlyLocalDecls));
421
422 // Find the file in which the region of interest lands.
423 SourceManager &SM = TU->getSourceManager();
424 std::pair<FileID, unsigned> Begin
425 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getBegin());
426 std::pair<FileID, unsigned> End
427 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getEnd());
428
429 // The region of interest spans files; we have to walk everything.
430 if (Begin.first != End.first)
431 return std::make_pair(PPRec.begin(OnlyLocalDecls),
432 PPRec.end(OnlyLocalDecls));
433
434 ASTUnit::PreprocessedEntitiesByFileMap &ByFileMap
435 = TU->getPreprocessedEntitiesByFile();
436 if (ByFileMap.empty()) {
437 // Build the mapping from files to sets of preprocessed entities.
438 for (PreprocessingRecord::iterator E = PPRec.begin(OnlyLocalDecls),
439 EEnd = PPRec.end(OnlyLocalDecls);
440 E != EEnd; ++E) {
441 std::pair<FileID, unsigned> P
442 = SM.getDecomposedInstantiationLoc((*E)->getSourceRange().getBegin());
443 ByFileMap[P.first].push_back(*E);
444 }
445 }
446
447 return std::make_pair(ByFileMap[Begin.first].begin(),
448 ByFileMap[Begin.first].end());
449}
450
Douglas Gregorb1373d02010-01-20 20:59:29 +0000451/// \brief Visit the children of the given cursor.
452///
453/// \returns true if the visitation should be aborted, false if it
454/// should continue.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000455bool CursorVisitor::VisitChildren(CXCursor Cursor) {
Douglas Gregora59e3902010-01-21 23:27:09 +0000456 if (clang_isReference(Cursor.kind)) {
457 // By definition, references have no children.
458 return false;
459 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000460
461 // Set the Parent field to Cursor, then back to its old value once we're
Douglas Gregorb1373d02010-01-20 20:59:29 +0000462 // done.
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000463 SetParentRAII SetParent(Parent, StmtParent, Cursor);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000464
Douglas Gregorb1373d02010-01-20 20:59:29 +0000465 if (clang_isDeclaration(Cursor.kind)) {
466 Decl *D = getCursorDecl(Cursor);
467 assert(D && "Invalid declaration cursor");
Ted Kremenek539311e2010-02-18 18:47:01 +0000468 return VisitAttributes(D) || Visit(D);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000469 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000470
Douglas Gregora59e3902010-01-21 23:27:09 +0000471 if (clang_isStatement(Cursor.kind))
472 return Visit(getCursorStmt(Cursor));
473 if (clang_isExpression(Cursor.kind))
474 return Visit(getCursorExpr(Cursor));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000475
Douglas Gregorb1373d02010-01-20 20:59:29 +0000476 if (clang_isTranslationUnit(Cursor.kind)) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000477 ASTUnit *CXXUnit = getCursorASTUnit(Cursor);
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000478 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
479 RegionOfInterest.isInvalid()) {
Douglas Gregor7b691f332010-01-20 21:13:59 +0000480 const std::vector<Decl*> &TLDs = CXXUnit->getTopLevelDecls();
481 for (std::vector<Decl*>::const_iterator it = TLDs.begin(),
482 ie = TLDs.end(); it != ie; ++it) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000483 if (Visit(MakeCXCursor(*it, CXXUnit), true))
Douglas Gregor7b691f332010-01-20 21:13:59 +0000484 return true;
485 }
Douglas Gregor0396f462010-03-19 05:22:59 +0000486 } else if (VisitDeclContext(
487 CXXUnit->getASTContext().getTranslationUnitDecl()))
488 return true;
Bob Wilson3178cb62010-03-19 03:57:57 +0000489
Douglas Gregor0396f462010-03-19 05:22:59 +0000490 // Walk the preprocessing record.
Daniel Dunbar8de30ff2010-03-20 01:11:56 +0000491 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000492 // FIXME: Once we have the ability to deserialize a preprocessing record,
493 // do so.
Douglas Gregor788f5a12010-03-20 00:41:21 +0000494 PreprocessingRecord::iterator E, EEnd;
495 for (llvm::tie(E, EEnd) = getPreprocessedEntities(); E != EEnd; ++E) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000496 if (MacroInstantiation *MI = dyn_cast<MacroInstantiation>(*E)) {
497 if (Visit(MakeMacroInstantiationCursor(MI, CXXUnit)))
498 return true;
Douglas Gregor788f5a12010-03-20 00:41:21 +0000499
Douglas Gregor0396f462010-03-19 05:22:59 +0000500 continue;
501 }
502
503 if (MacroDefinition *MD = dyn_cast<MacroDefinition>(*E)) {
504 if (Visit(MakeMacroDefinitionCursor(MD, CXXUnit)))
505 return true;
506
507 continue;
508 }
509 }
510 }
Douglas Gregor7b691f332010-01-20 21:13:59 +0000511 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000512 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000513
Douglas Gregorb1373d02010-01-20 20:59:29 +0000514 // Nothing to visit at the moment.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000515 return false;
516}
517
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000518bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
John McCallfc929202010-06-04 22:33:30 +0000519 if (Visit(B->getSignatureAsWritten()->getTypeLoc()))
520 return true;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000521
Ted Kremenek664cffd2010-07-22 11:30:19 +0000522 if (Stmt *Body = B->getBody())
523 return Visit(MakeCXCursor(Body, StmtParent, TU));
524
525 return false;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000526}
527
Douglas Gregorb1373d02010-01-20 20:59:29 +0000528bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000529 for (DeclContext::decl_iterator
Douglas Gregorb1373d02010-01-20 20:59:29 +0000530 I = DC->decls_begin(), E = DC->decls_end(); I != E; ++I) {
Ted Kremenek09dfa372010-02-18 05:46:33 +0000531
Ted Kremenek23173d72010-05-18 21:09:07 +0000532 Decl *D = *I;
533 if (D->getLexicalDeclContext() != DC)
534 continue;
535
536 CXCursor Cursor = MakeCXCursor(D, TU);
Daniel Dunbard52864b2010-02-14 10:02:57 +0000537
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000538 if (RegionOfInterest.isValid()) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000539 SourceRange Range = getRawCursorExtent(Cursor);
Daniel Dunbard52864b2010-02-14 10:02:57 +0000540 if (Range.isInvalid())
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000541 continue;
Daniel Dunbard52864b2010-02-14 10:02:57 +0000542
543 switch (CompareRegionOfInterest(Range)) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000544 case RangeBefore:
545 // This declaration comes before the region of interest; skip it.
546 continue;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000547
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000548 case RangeAfter:
549 // This declaration comes after the region of interest; we're done.
550 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000551
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000552 case RangeOverlap:
553 // This declaration overlaps the region of interest; visit it.
554 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000555 }
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000556 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000557
Daniel Dunbard52864b2010-02-14 10:02:57 +0000558 if (Visit(Cursor, true))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000559 return true;
560 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000561
Douglas Gregorb1373d02010-01-20 20:59:29 +0000562 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000563}
564
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000565bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
566 llvm_unreachable("Translation units are visited directly by Visit()");
567 return false;
568}
569
570bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
571 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
572 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000573
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000574 return false;
575}
576
577bool CursorVisitor::VisitTagDecl(TagDecl *D) {
578 return VisitDeclContext(D);
579}
580
581bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
582 if (Expr *Init = D->getInitExpr())
583 return Visit(MakeCXCursor(Init, StmtParent, TU));
584 return false;
585}
586
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000587bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
588 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
589 if (Visit(TSInfo->getTypeLoc()))
590 return true;
591
592 return false;
593}
594
Douglas Gregorb1373d02010-01-20 20:59:29 +0000595bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000596 if (VisitDeclaratorDecl(ND))
597 return true;
598
Douglas Gregora59e3902010-01-21 23:27:09 +0000599 if (ND->isThisDeclarationADefinition() &&
600 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
601 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000602
Douglas Gregorb1373d02010-01-20 20:59:29 +0000603 return false;
604}
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000605
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000606bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
607 if (VisitDeclaratorDecl(D))
608 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000609
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000610 if (Expr *BitWidth = D->getBitWidth())
611 return Visit(MakeCXCursor(BitWidth, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000612
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000613 return false;
614}
615
616bool CursorVisitor::VisitVarDecl(VarDecl *D) {
617 if (VisitDeclaratorDecl(D))
618 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000619
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000620 if (Expr *Init = D->getInit())
621 return Visit(MakeCXCursor(Init, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000622
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000623 return false;
624}
625
626bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
Douglas Gregor4bc1cb62010-03-08 14:59:44 +0000627 if (TypeSourceInfo *TSInfo = ND->getResultTypeSourceInfo())
628 if (Visit(TSInfo->getTypeLoc()))
629 return true;
630
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000631 for (ObjCMethodDecl::param_iterator P = ND->param_begin(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000632 PEnd = ND->param_end();
633 P != PEnd; ++P) {
634 if (Visit(MakeCXCursor(*P, TU)))
635 return true;
636 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000637
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000638 if (ND->isThisDeclarationADefinition() &&
639 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
640 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000641
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000642 return false;
643}
644
Douglas Gregora59e3902010-01-21 23:27:09 +0000645bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
646 return VisitDeclContext(D);
647}
648
Douglas Gregorb1373d02010-01-20 20:59:29 +0000649bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000650 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
651 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000652 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000653
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000654 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
655 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
656 E = ND->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000657 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000658 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000659
Douglas Gregora59e3902010-01-21 23:27:09 +0000660 return VisitObjCContainerDecl(ND);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000661}
662
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000663bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
664 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
665 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
666 E = PID->protocol_end(); I != E; ++I, ++PL)
667 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
668 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000669
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000670 return VisitObjCContainerDecl(PID);
671}
672
Ted Kremenek23173d72010-05-18 21:09:07 +0000673bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
John McCallfc929202010-06-04 22:33:30 +0000674 if (Visit(PD->getTypeSourceInfo()->getTypeLoc()))
675 return true;
676
Ted Kremenek23173d72010-05-18 21:09:07 +0000677 // FIXME: This implements a workaround with @property declarations also being
678 // installed in the DeclContext for the @interface. Eventually this code
679 // should be removed.
680 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
681 if (!CDecl || !CDecl->IsClassExtension())
682 return false;
683
684 ObjCInterfaceDecl *ID = CDecl->getClassInterface();
685 if (!ID)
686 return false;
687
688 IdentifierInfo *PropertyId = PD->getIdentifier();
689 ObjCPropertyDecl *prevDecl =
690 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId);
691
692 if (!prevDecl)
693 return false;
694
695 // Visit synthesized methods since they will be skipped when visiting
696 // the @interface.
697 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
698 if (MD->isSynthesized())
699 if (Visit(MakeCXCursor(MD, TU)))
700 return true;
701
702 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
703 if (MD->isSynthesized())
704 if (Visit(MakeCXCursor(MD, TU)))
705 return true;
706
707 return false;
708}
709
Douglas Gregorb1373d02010-01-20 20:59:29 +0000710bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000711 // Issue callbacks for super class.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000712 if (D->getSuperClass() &&
713 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000714 D->getSuperClassLoc(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000715 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000716 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000717
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000718 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
719 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
720 E = D->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000721 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000722 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000723
Douglas Gregora59e3902010-01-21 23:27:09 +0000724 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000725}
726
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000727bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
728 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000729}
730
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000731bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
Ted Kremenekebfa3392010-03-19 20:39:03 +0000732 // 'ID' could be null when dealing with invalid code.
733 if (ObjCInterfaceDecl *ID = D->getClassInterface())
734 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
735 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000736
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000737 return VisitObjCImplDecl(D);
738}
739
740bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
741#if 0
742 // Issue callbacks for super class.
743 // FIXME: No source location information!
744 if (D->getSuperClass() &&
745 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000746 D->getSuperClassLoc(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000747 TU)))
748 return true;
749#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000750
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000751 return VisitObjCImplDecl(D);
752}
753
754bool CursorVisitor::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D) {
755 ObjCForwardProtocolDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
756 for (ObjCForwardProtocolDecl::protocol_iterator I = D->protocol_begin(),
757 E = D->protocol_end();
758 I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000759 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000760 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000761
762 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000763}
764
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000765bool CursorVisitor::VisitObjCClassDecl(ObjCClassDecl *D) {
766 for (ObjCClassDecl::iterator C = D->begin(), CEnd = D->end(); C != CEnd; ++C)
767 if (Visit(MakeCursorObjCClassRef(C->getInterface(), C->getLocation(), TU)))
768 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000769
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000770 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000771}
772
Ted Kremenek8f06e0e2010-05-06 23:38:21 +0000773bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
774 return VisitDeclContext(D);
775}
776
Ted Kremeneka0536d82010-05-07 01:04:29 +0000777bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
778 return VisitDeclContext(D);
779}
780
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000781bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
782 ASTContext &Context = TU->getASTContext();
783
784 // Some builtin types (such as Objective-C's "id", "sel", and
785 // "Class") have associated declarations. Create cursors for those.
786 QualType VisitType;
787 switch (TL.getType()->getAs<BuiltinType>()->getKind()) {
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000788 case BuiltinType::Void:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000789 case BuiltinType::Bool:
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000790 case BuiltinType::Char_U:
791 case BuiltinType::UChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000792 case BuiltinType::Char16:
793 case BuiltinType::Char32:
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000794 case BuiltinType::UShort:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000795 case BuiltinType::UInt:
796 case BuiltinType::ULong:
797 case BuiltinType::ULongLong:
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000798 case BuiltinType::UInt128:
799 case BuiltinType::Char_S:
800 case BuiltinType::SChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000801 case BuiltinType::WChar:
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000802 case BuiltinType::Short:
803 case BuiltinType::Int:
804 case BuiltinType::Long:
805 case BuiltinType::LongLong:
806 case BuiltinType::Int128:
807 case BuiltinType::Float:
808 case BuiltinType::Double:
809 case BuiltinType::LongDouble:
810 case BuiltinType::NullPtr:
811 case BuiltinType::Overload:
812 case BuiltinType::Dependent:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000813 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000814
815 case BuiltinType::UndeducedAuto: // FIXME: Deserves a cursor?
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000816 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000817
Ted Kremenekc4174cc2010-02-18 18:52:18 +0000818 case BuiltinType::ObjCId:
819 VisitType = Context.getObjCIdType();
820 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000821
822 case BuiltinType::ObjCClass:
823 VisitType = Context.getObjCClassType();
824 break;
825
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000826 case BuiltinType::ObjCSel:
827 VisitType = Context.getObjCSelType();
828 break;
829 }
830
831 if (!VisitType.isNull()) {
832 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000833 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000834 TU));
835 }
836
837 return false;
838}
839
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000840bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
841 return Visit(MakeCursorTypeRef(TL.getTypedefDecl(), TL.getNameLoc(), TU));
842}
843
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000844bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
845 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
846}
847
848bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
849 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
850}
851
852bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
853 if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
854 return true;
855
John McCallc12c5bb2010-05-15 11:32:37 +0000856 return false;
857}
858
859bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
860 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
861 return true;
862
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000863 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
864 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
865 TU)))
866 return true;
867 }
868
869 return false;
870}
871
872bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
John McCallc12c5bb2010-05-15 11:32:37 +0000873 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000874}
875
876bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
877 return Visit(TL.getPointeeLoc());
878}
879
880bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
881 return Visit(TL.getPointeeLoc());
882}
883
884bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
885 return Visit(TL.getPointeeLoc());
886}
887
888bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000889 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000890}
891
892bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000893 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000894}
895
896bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
897 if (Visit(TL.getResultLoc()))
898 return true;
899
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000900 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
Ted Kremenek5dbacb42010-04-07 00:27:13 +0000901 if (Decl *D = TL.getArg(I))
902 if (Visit(MakeCXCursor(D, TU)))
903 return true;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000904
905 return false;
906}
907
908bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
909 if (Visit(TL.getElementLoc()))
910 return true;
911
912 if (Expr *Size = TL.getSizeExpr())
913 return Visit(MakeCXCursor(Size, StmtParent, TU));
914
915 return false;
916}
917
Douglas Gregor2332c112010-01-21 20:48:56 +0000918bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
919 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
920}
921
922bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
923 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
924 return Visit(TSInfo->getTypeLoc());
925
926 return false;
927}
928
Douglas Gregora59e3902010-01-21 23:27:09 +0000929bool CursorVisitor::VisitStmt(Stmt *S) {
930 for (Stmt::child_iterator Child = S->child_begin(), ChildEnd = S->child_end();
931 Child != ChildEnd; ++Child) {
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000932 if (Stmt *C = *Child)
933 if (Visit(MakeCXCursor(C, StmtParent, TU)))
934 return true;
Douglas Gregora59e3902010-01-21 23:27:09 +0000935 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000936
Douglas Gregora59e3902010-01-21 23:27:09 +0000937 return false;
938}
939
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000940bool CursorVisitor::VisitCaseStmt(CaseStmt *S) {
941 // Specially handle CaseStmts because they can be nested, e.g.:
942 //
943 // case 1:
944 // case 2:
945 //
946 // In this case the second CaseStmt is the child of the first. Walking
947 // these recursively can blow out the stack.
948 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU);
949 while (true) {
950 // Set the Parent field to Cursor, then back to its old value once we're
951 // done.
952 SetParentRAII SetParent(Parent, StmtParent, Cursor);
953
954 if (Stmt *LHS = S->getLHS())
955 if (Visit(MakeCXCursor(LHS, StmtParent, TU)))
956 return true;
957 if (Stmt *RHS = S->getRHS())
958 if (Visit(MakeCXCursor(RHS, StmtParent, TU)))
959 return true;
960 if (Stmt *SubStmt = S->getSubStmt()) {
961 if (!isa<CaseStmt>(SubStmt))
962 return Visit(MakeCXCursor(SubStmt, StmtParent, TU));
963
964 // Specially handle 'CaseStmt' so that we don't blow out the stack.
965 CaseStmt *CS = cast<CaseStmt>(SubStmt);
966 Cursor = MakeCXCursor(CS, StmtParent, TU);
967 if (RegionOfInterest.isValid()) {
968 SourceRange Range = CS->getSourceRange();
969 if (Range.isInvalid() || CompareRegionOfInterest(Range))
970 return false;
971 }
972
973 switch (Visitor(Cursor, Parent, ClientData)) {
974 case CXChildVisit_Break: return true;
975 case CXChildVisit_Continue: return false;
976 case CXChildVisit_Recurse:
977 // Perform tail-recursion manually.
978 S = CS;
979 continue;
980 }
981 }
982 return false;
983 }
984}
985
Douglas Gregora59e3902010-01-21 23:27:09 +0000986bool CursorVisitor::VisitDeclStmt(DeclStmt *S) {
987 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
988 D != DEnd; ++D) {
Douglas Gregor263b47b2010-01-25 16:12:32 +0000989 if (*D && Visit(MakeCXCursor(*D, TU)))
Douglas Gregora59e3902010-01-21 23:27:09 +0000990 return true;
991 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000992
Douglas Gregora59e3902010-01-21 23:27:09 +0000993 return false;
994}
995
Douglas Gregorf5bab412010-01-22 01:00:11 +0000996bool CursorVisitor::VisitIfStmt(IfStmt *S) {
997 if (VarDecl *Var = S->getConditionVariable()) {
998 if (Visit(MakeCXCursor(Var, TU)))
999 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001000 }
1001
Douglas Gregor263b47b2010-01-25 16:12:32 +00001002 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1003 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +00001004 if (S->getThen() && Visit(MakeCXCursor(S->getThen(), StmtParent, TU)))
1005 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +00001006 if (S->getElse() && Visit(MakeCXCursor(S->getElse(), StmtParent, TU)))
1007 return true;
1008
1009 return false;
1010}
1011
1012bool CursorVisitor::VisitSwitchStmt(SwitchStmt *S) {
1013 if (VarDecl *Var = S->getConditionVariable()) {
1014 if (Visit(MakeCXCursor(Var, TU)))
1015 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001016 }
1017
Douglas Gregor263b47b2010-01-25 16:12:32 +00001018 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1019 return true;
1020 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
1021 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001022
Douglas Gregor263b47b2010-01-25 16:12:32 +00001023 return false;
1024}
1025
1026bool CursorVisitor::VisitWhileStmt(WhileStmt *S) {
1027 if (VarDecl *Var = S->getConditionVariable()) {
1028 if (Visit(MakeCXCursor(Var, TU)))
1029 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001030 }
1031
Douglas Gregor263b47b2010-01-25 16:12:32 +00001032 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1033 return true;
1034 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
Douglas Gregorf5bab412010-01-22 01:00:11 +00001035 return true;
1036
Douglas Gregor263b47b2010-01-25 16:12:32 +00001037 return false;
1038}
1039
1040bool CursorVisitor::VisitForStmt(ForStmt *S) {
1041 if (S->getInit() && Visit(MakeCXCursor(S->getInit(), StmtParent, TU)))
1042 return true;
1043 if (VarDecl *Var = S->getConditionVariable()) {
1044 if (Visit(MakeCXCursor(Var, TU)))
1045 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001046 }
1047
Douglas Gregor263b47b2010-01-25 16:12:32 +00001048 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1049 return true;
1050 if (S->getInc() && Visit(MakeCXCursor(S->getInc(), StmtParent, TU)))
1051 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +00001052 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
1053 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001054
Douglas Gregorf5bab412010-01-22 01:00:11 +00001055 return false;
1056}
1057
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00001058bool CursorVisitor::VisitBlockExpr(BlockExpr *B) {
1059 return Visit(B->getBlockDecl());
1060}
1061
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001062bool CursorVisitor::VisitOffsetOfExpr(OffsetOfExpr *E) {
1063 // FIXME: Visit fields as well?
1064 if (Visit(E->getTypeSourceInfo()->getTypeLoc()))
1065 return true;
1066
1067 return VisitExpr(E);
1068}
1069
Douglas Gregor336fd812010-01-23 00:40:08 +00001070bool CursorVisitor::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E) {
1071 if (E->isArgumentType()) {
1072 if (TypeSourceInfo *TSInfo = E->getArgumentTypeInfo())
1073 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001074
Douglas Gregor336fd812010-01-23 00:40:08 +00001075 return false;
1076 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001077
Douglas Gregor336fd812010-01-23 00:40:08 +00001078 return VisitExpr(E);
1079}
1080
1081bool CursorVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
1082 if (TypeSourceInfo *TSInfo = E->getTypeInfoAsWritten())
1083 if (Visit(TSInfo->getTypeLoc()))
1084 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001085
Douglas Gregor336fd812010-01-23 00:40:08 +00001086 return VisitCastExpr(E);
1087}
1088
1089bool CursorVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
1090 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
1091 if (Visit(TSInfo->getTypeLoc()))
1092 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001093
Douglas Gregor336fd812010-01-23 00:40:08 +00001094 return VisitExpr(E);
1095}
1096
Douglas Gregorc2350e52010-03-08 16:40:19 +00001097bool CursorVisitor::VisitObjCMessageExpr(ObjCMessageExpr *E) {
Douglas Gregor04badcf2010-04-21 00:45:42 +00001098 if (TypeSourceInfo *TSInfo = E->getClassReceiverTypeInfo())
1099 if (Visit(TSInfo->getTypeLoc()))
1100 return true;
Douglas Gregorc2350e52010-03-08 16:40:19 +00001101
1102 return VisitExpr(E);
1103}
1104
Douglas Gregor81d34662010-04-20 15:39:42 +00001105bool CursorVisitor::VisitObjCEncodeExpr(ObjCEncodeExpr *E) {
1106 return Visit(E->getEncodedTypeSourceInfo()->getTypeLoc());
1107}
1108
1109
Ted Kremenek09dfa372010-02-18 05:46:33 +00001110bool CursorVisitor::VisitAttributes(Decl *D) {
1111 for (const Attr *A = D->getAttrs(); A; A = A->getNext())
1112 if (Visit(MakeCXCursor(A, D, TU)))
1113 return true;
1114
1115 return false;
1116}
1117
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00001118extern "C" {
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001119CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
1120 int displayDiagnostics) {
Douglas Gregora030b7c2010-01-22 20:35:53 +00001121 CIndexer *CIdxr = new CIndexer();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001122 if (excludeDeclarationsFromPCH)
1123 CIdxr->setOnlyLocalDecls();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001124 if (displayDiagnostics)
1125 CIdxr->setDisplayDiagnostics();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001126 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +00001127}
1128
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001129void clang_disposeIndex(CXIndex CIdx) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001130 if (CIdx)
1131 delete static_cast<CIndexer *>(CIdx);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00001132}
1133
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001134void clang_setUseExternalASTGeneration(CXIndex CIdx, int value) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001135 if (CIdx) {
1136 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
1137 CXXIdx->setUseExternalASTGeneration(value);
1138 }
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001139}
1140
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001141CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
Douglas Gregora88084b2010-02-18 18:08:43 +00001142 const char *ast_filename) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001143 if (!CIdx)
1144 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001145
Douglas Gregor7d1d49d2009-10-16 20:01:17 +00001146 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001147
Douglas Gregor28019772010-04-05 23:52:57 +00001148 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
1149 return ASTUnit::LoadFromPCHFile(ast_filename, Diags,
Douglas Gregora88084b2010-02-18 18:08:43 +00001150 CXXIdx->getOnlyLocalDecls(),
1151 0, 0, true);
Steve Naroff600866c2009-08-27 19:51:58 +00001152}
1153
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001154CXTranslationUnit
1155clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
1156 const char *source_filename,
1157 int num_command_line_args,
Douglas Gregor4db64a42010-01-23 00:14:00 +00001158 const char **command_line_args,
1159 unsigned num_unsaved_files,
Douglas Gregora88084b2010-02-18 18:08:43 +00001160 struct CXUnsavedFile *unsaved_files) {
Douglas Gregor5a430212010-07-21 18:52:53 +00001161 return clang_parseTranslationUnit(CIdx, source_filename,
1162 command_line_args, num_command_line_args,
1163 unsaved_files, num_unsaved_files,
1164 CXTranslationUnit_DetailedPreprocessingRecord);
1165}
1166
1167CXTranslationUnit clang_parseTranslationUnit(CXIndex CIdx,
1168 const char *source_filename,
1169 const char **command_line_args,
1170 int num_command_line_args,
1171 struct CXUnsavedFile *unsaved_files,
1172 unsigned num_unsaved_files,
1173 unsigned options) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001174 if (!CIdx)
1175 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001176
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001177 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
1178
Douglas Gregor5352ac02010-01-28 00:27:43 +00001179 // Configure the diagnostics.
1180 DiagnosticOptions DiagOpts;
Douglas Gregor28019772010-04-05 23:52:57 +00001181 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
1182 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001183
Douglas Gregor4db64a42010-01-23 00:14:00 +00001184 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
1185 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattnera0a270c2010-04-05 22:42:27 +00001186 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001187 const llvm::MemoryBuffer *Buffer
Chris Lattnera0a270c2010-04-05 22:42:27 +00001188 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregor4db64a42010-01-23 00:14:00 +00001189 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
1190 Buffer));
1191 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001192
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001193 if (!CXXIdx->getUseExternalASTGeneration()) {
1194 llvm::SmallVector<const char *, 16> Args;
1195
1196 // The 'source_filename' argument is optional. If the caller does not
1197 // specify it then it is assumed that the source file is specified
1198 // in the actual argument list.
1199 if (source_filename)
1200 Args.push_back(source_filename);
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00001201
1202 // Since the Clang C library is primarily used by batch tools dealing with
1203 // (often very broken) source code, where spell-checking can have a
1204 // significant negative impact on performance (particularly when
1205 // precompiled headers are involved), we disable it by default.
1206 // Note that we place this argument early in the list, so that it can be
1207 // overridden by the caller with "-fspell-checking".
Douglas Gregora0068fc2010-07-09 17:35:33 +00001208 Args.push_back("-fno-spell-checking");
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00001209
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001210 Args.insert(Args.end(), command_line_args,
1211 command_line_args + num_command_line_args);
Douglas Gregor5a430212010-07-21 18:52:53 +00001212
1213 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
1214 Args.push_back("-Xclang");
1215 Args.push_back("-detailed-preprocessing-record");
1216 }
Douglas Gregor5352ac02010-01-28 00:27:43 +00001217 unsigned NumErrors = Diags->getNumErrors();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001218
Ted Kremenek29b72842010-01-07 22:49:05 +00001219#ifdef USE_CRASHTRACER
1220 ArgsCrashTracerInfo ACTI(Args);
Ted Kremenek8a8da7d2010-01-06 03:42:32 +00001221#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001222
Daniel Dunbar94220972009-12-05 02:17:18 +00001223 llvm::OwningPtr<ASTUnit> Unit(
1224 ASTUnit::LoadFromCommandLine(Args.data(), Args.data() + Args.size(),
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001225 Diags,
Daniel Dunbar869824e2009-12-13 03:46:13 +00001226 CXXIdx->getClangResourcesPath(),
Daniel Dunbar94220972009-12-05 02:17:18 +00001227 CXXIdx->getOnlyLocalDecls(),
Douglas Gregor4db64a42010-01-23 00:14:00 +00001228 RemappedFiles.data(),
Douglas Gregora88084b2010-02-18 18:08:43 +00001229 RemappedFiles.size(),
Douglas Gregor94dc8f62010-03-19 16:15:56 +00001230 /*CaptureDiagnostics=*/true));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001231
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001232 if (NumErrors != Diags->getNumErrors()) {
Ted Kremenek34f6a322010-03-05 22:43:29 +00001233 // Make sure to check that 'Unit' is non-NULL.
1234 if (CXXIdx->getDisplayDiagnostics() && Unit.get()) {
Douglas Gregor405634b2010-04-05 18:10:21 +00001235 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
1236 DEnd = Unit->stored_diag_end();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001237 D != DEnd; ++D) {
1238 CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOptions());
Douglas Gregor274f1902010-02-22 23:17:23 +00001239 CXString Msg = clang_formatDiagnostic(&Diag,
1240 clang_defaultDiagnosticDisplayOptions());
1241 fprintf(stderr, "%s\n", clang_getCString(Msg));
1242 clang_disposeString(Msg);
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001243 }
Douglas Gregor274f1902010-02-22 23:17:23 +00001244#ifdef LLVM_ON_WIN32
1245 // On Windows, force a flush, since there may be multiple copies of
1246 // stderr and stdout in the file system, all with different buffers
1247 // but writing to the same device.
1248 fflush(stderr);
Ted Kremenek83c51842010-03-26 01:34:51 +00001249#endif
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001250 }
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001251 }
Daniel Dunbar94220972009-12-05 02:17:18 +00001252
1253 return Unit.take();
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001254 }
1255
Ted Kremenek139ba862009-10-22 00:03:57 +00001256 // Build up the arguments for invoking 'clang'.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001257 std::vector<const char *> argv;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001258
Ted Kremenek139ba862009-10-22 00:03:57 +00001259 // First add the complete path to the 'clang' executable.
1260 llvm::sys::Path ClangPath = static_cast<CIndexer *>(CIdx)->getClangPath();
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00001261 argv.push_back(ClangPath.c_str());
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001262
Ted Kremenek139ba862009-10-22 00:03:57 +00001263 // Add the '-emit-ast' option as our execution mode for 'clang'.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001264 argv.push_back("-emit-ast");
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001265
Ted Kremenek139ba862009-10-22 00:03:57 +00001266 // The 'source_filename' argument is optional. If the caller does not
1267 // specify it then it is assumed that the source file is specified
1268 // in the actual argument list.
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001269 if (source_filename)
1270 argv.push_back(source_filename);
Ted Kremenek139ba862009-10-22 00:03:57 +00001271
Steve Naroff37b5ac22009-10-15 20:50:09 +00001272 // Generate a temporary name for the AST file.
Ted Kremenek139ba862009-10-22 00:03:57 +00001273 argv.push_back("-o");
Benjamin Kramerc2a98162010-03-13 21:22:49 +00001274 char astTmpFile[L_tmpnam];
1275 argv.push_back(tmpnam(astTmpFile));
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00001276
1277 // Since the Clang C library is primarily used by batch tools dealing with
1278 // (often very broken) source code, where spell-checking can have a
1279 // significant negative impact on performance (particularly when
1280 // precompiled headers are involved), we disable it by default.
1281 // Note that we place this argument early in the list, so that it can be
1282 // overridden by the caller with "-fspell-checking".
Douglas Gregora0068fc2010-07-09 17:35:33 +00001283 argv.push_back("-fno-spell-checking");
Ted Kremenek139ba862009-10-22 00:03:57 +00001284
Douglas Gregor4db64a42010-01-23 00:14:00 +00001285 // Remap any unsaved files to temporary files.
1286 std::vector<llvm::sys::Path> TemporaryFiles;
1287 std::vector<std::string> RemapArgs;
1288 if (RemapFiles(num_unsaved_files, unsaved_files, RemapArgs, TemporaryFiles))
1289 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001290
Douglas Gregor4db64a42010-01-23 00:14:00 +00001291 // The pointers into the elements of RemapArgs are stable because we
1292 // won't be adding anything to RemapArgs after this point.
1293 for (unsigned i = 0, e = RemapArgs.size(); i != e; ++i)
1294 argv.push_back(RemapArgs[i].c_str());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001295
Ted Kremenek139ba862009-10-22 00:03:57 +00001296 // Process the compiler options, stripping off '-o', '-c', '-fsyntax-only'.
1297 for (int i = 0; i < num_command_line_args; ++i)
1298 if (const char *arg = command_line_args[i]) {
1299 if (strcmp(arg, "-o") == 0) {
1300 ++i; // Also skip the matching argument.
1301 continue;
1302 }
1303 if (strcmp(arg, "-emit-ast") == 0 ||
1304 strcmp(arg, "-c") == 0 ||
1305 strcmp(arg, "-fsyntax-only") == 0) {
1306 continue;
1307 }
1308
1309 // Keep the argument.
1310 argv.push_back(arg);
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001311 }
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001312
Douglas Gregord93256e2010-01-28 06:00:51 +00001313 // Generate a temporary name for the diagnostics file.
Benjamin Kramerc2a98162010-03-13 21:22:49 +00001314 char tmpFileResults[L_tmpnam];
1315 char *tmpResultsFileName = tmpnam(tmpFileResults);
1316 llvm::sys::Path DiagnosticsFile(tmpResultsFileName);
Douglas Gregord93256e2010-01-28 06:00:51 +00001317 TemporaryFiles.push_back(DiagnosticsFile);
1318 argv.push_back("-fdiagnostics-binary");
1319
Douglas Gregor94dc8f62010-03-19 16:15:56 +00001320 argv.push_back("-Xclang");
1321 argv.push_back("-detailed-preprocessing-record");
1322
Ted Kremenek139ba862009-10-22 00:03:57 +00001323 // Add the null terminator.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001324 argv.push_back(NULL);
1325
Ted Kremenekfeb15e32009-10-26 22:14:08 +00001326 // Invoke 'clang'.
1327 llvm::sys::Path DevNull; // leave empty, causes redirection to /dev/null
1328 // on Unix or NUL (Windows).
Ted Kremenek379afec2009-10-22 03:24:01 +00001329 std::string ErrMsg;
Douglas Gregord93256e2010-01-28 06:00:51 +00001330 const llvm::sys::Path *Redirects[] = { &DevNull, &DevNull, &DiagnosticsFile,
1331 NULL };
Ted Kremenek379afec2009-10-22 03:24:01 +00001332 llvm::sys::Program::ExecuteAndWait(ClangPath, &argv[0], /* env */ NULL,
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001333 /* redirects */ &Redirects[0],
Ted Kremenek379afec2009-10-22 03:24:01 +00001334 /* secondsToWait */ 0, /* memoryLimits */ 0, &ErrMsg);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001335
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001336 if (!ErrMsg.empty()) {
1337 std::string AllArgs;
Ted Kremenek379afec2009-10-22 03:24:01 +00001338 for (std::vector<const char*>::iterator I = argv.begin(), E = argv.end();
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001339 I != E; ++I) {
1340 AllArgs += ' ';
Ted Kremenek779e5f42009-10-26 22:08:39 +00001341 if (*I)
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001342 AllArgs += *I;
Ted Kremenek779e5f42009-10-26 22:08:39 +00001343 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001344
Daniel Dunbar32141c82010-02-23 20:23:45 +00001345 Diags->Report(diag::err_fe_invoking) << AllArgs << ErrMsg;
Ted Kremenek379afec2009-10-22 03:24:01 +00001346 }
Benjamin Kramer0829a832009-10-18 11:19:36 +00001347
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001348 ASTUnit *ATU = ASTUnit::LoadFromPCHFile(astTmpFile, Diags,
Douglas Gregor4db64a42010-01-23 00:14:00 +00001349 CXXIdx->getOnlyLocalDecls(),
Douglas Gregor4db64a42010-01-23 00:14:00 +00001350 RemappedFiles.data(),
Douglas Gregora88084b2010-02-18 18:08:43 +00001351 RemappedFiles.size(),
1352 /*CaptureDiagnostics=*/true);
Douglas Gregora88084b2010-02-18 18:08:43 +00001353 if (ATU) {
1354 LoadSerializedDiagnostics(DiagnosticsFile,
1355 num_unsaved_files, unsaved_files,
1356 ATU->getFileManager(),
1357 ATU->getSourceManager(),
Douglas Gregor405634b2010-04-05 18:10:21 +00001358 ATU->getStoredDiagnostics());
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001359 } else if (CXXIdx->getDisplayDiagnostics()) {
1360 // We failed to load the ASTUnit, but we can still deserialize the
1361 // diagnostics and emit them.
1362 FileManager FileMgr;
Douglas Gregorf715ca12010-03-16 00:06:06 +00001363 Diagnostic Diag;
1364 SourceManager SourceMgr(Diag);
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001365 // FIXME: Faked LangOpts!
1366 LangOptions LangOpts;
1367 llvm::SmallVector<StoredDiagnostic, 4> Diags;
1368 LoadSerializedDiagnostics(DiagnosticsFile,
1369 num_unsaved_files, unsaved_files,
1370 FileMgr, SourceMgr, Diags);
1371 for (llvm::SmallVector<StoredDiagnostic, 4>::iterator D = Diags.begin(),
1372 DEnd = Diags.end();
1373 D != DEnd; ++D) {
1374 CXStoredDiagnostic Diag(*D, LangOpts);
Douglas Gregor274f1902010-02-22 23:17:23 +00001375 CXString Msg = clang_formatDiagnostic(&Diag,
1376 clang_defaultDiagnosticDisplayOptions());
1377 fprintf(stderr, "%s\n", clang_getCString(Msg));
1378 clang_disposeString(Msg);
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001379 }
Douglas Gregor274f1902010-02-22 23:17:23 +00001380
1381#ifdef LLVM_ON_WIN32
1382 // On Windows, force a flush, since there may be multiple copies of
1383 // stderr and stdout in the file system, all with different buffers
1384 // but writing to the same device.
1385 fflush(stderr);
1386#endif
Douglas Gregora88084b2010-02-18 18:08:43 +00001387 }
Douglas Gregord93256e2010-01-28 06:00:51 +00001388
Douglas Gregor313e26c2010-02-18 23:35:40 +00001389 if (ATU) {
1390 // Make the translation unit responsible for destroying all temporary files.
1391 for (unsigned i = 0, e = TemporaryFiles.size(); i != e; ++i)
1392 ATU->addTemporaryFile(TemporaryFiles[i]);
1393 ATU->addTemporaryFile(llvm::sys::Path(ATU->getPCHFileName()));
1394 } else {
1395 // Destroy all of the temporary files now; they can't be referenced any
1396 // longer.
1397 llvm::sys::Path(astTmpFile).eraseFromDisk();
1398 for (unsigned i = 0, e = TemporaryFiles.size(); i != e; ++i)
1399 TemporaryFiles[i].eraseFromDisk();
1400 }
1401
Steve Naroffe19944c2009-10-15 22:23:48 +00001402 return ATU;
Steve Naroff5b7d8e22009-10-15 20:04:39 +00001403}
1404
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001405void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001406 if (CTUnit)
1407 delete static_cast<ASTUnit *>(CTUnit);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00001408}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001409
Douglas Gregorabc563f2010-07-19 21:46:24 +00001410int clang_reparseTranslationUnit(CXTranslationUnit TU,
1411 unsigned num_unsaved_files,
1412 struct CXUnsavedFile *unsaved_files) {
1413 if (!TU)
1414 return 1;
1415
1416 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
1417 for (unsigned I = 0; I != num_unsaved_files; ++I) {
1418 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
1419 const llvm::MemoryBuffer *Buffer
1420 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
1421 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
1422 Buffer));
1423 }
1424
1425 return static_cast<ASTUnit *>(TU)->Reparse(RemappedFiles.data(),
1426 RemappedFiles.size())? 1 : 0;
1427}
1428
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001429CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001430 if (!CTUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001431 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001432
Steve Naroff77accc12009-09-03 18:19:54 +00001433 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001434 return createCXString(CXXUnit->getOriginalSourceFileName(), true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +00001435}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +00001436
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001437CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001438 CXCursor Result = { CXCursor_TranslationUnit, { 0, 0, TU } };
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001439 return Result;
1440}
1441
Ted Kremenekfb480492010-01-13 21:46:36 +00001442} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +00001443
Ted Kremenekfb480492010-01-13 21:46:36 +00001444//===----------------------------------------------------------------------===//
Douglas Gregor1db19de2010-01-19 21:36:55 +00001445// CXSourceLocation and CXSourceRange Operations.
1446//===----------------------------------------------------------------------===//
1447
Douglas Gregorb9790342010-01-22 21:44:22 +00001448extern "C" {
1449CXSourceLocation clang_getNullLocation() {
Douglas Gregor5352ac02010-01-28 00:27:43 +00001450 CXSourceLocation Result = { { 0, 0 }, 0 };
Douglas Gregorb9790342010-01-22 21:44:22 +00001451 return Result;
1452}
1453
1454unsigned clang_equalLocations(CXSourceLocation loc1, CXSourceLocation loc2) {
Daniel Dunbar90a6b9e2010-01-30 23:58:27 +00001455 return (loc1.ptr_data[0] == loc2.ptr_data[0] &&
1456 loc1.ptr_data[1] == loc2.ptr_data[1] &&
1457 loc1.int_data == loc2.int_data);
Douglas Gregorb9790342010-01-22 21:44:22 +00001458}
1459
1460CXSourceLocation clang_getLocation(CXTranslationUnit tu,
1461 CXFile file,
1462 unsigned line,
1463 unsigned column) {
Douglas Gregor42748ec2010-04-30 19:45:53 +00001464 if (!tu || !file)
Douglas Gregorb9790342010-01-22 21:44:22 +00001465 return clang_getNullLocation();
Douglas Gregor42748ec2010-04-30 19:45:53 +00001466
Douglas Gregorb9790342010-01-22 21:44:22 +00001467 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
1468 SourceLocation SLoc
1469 = CXXUnit->getSourceManager().getLocation(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001470 static_cast<const FileEntry *>(file),
Douglas Gregorb9790342010-01-22 21:44:22 +00001471 line, column);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001472
Ted Kremenek1a9a0bc2010-06-28 23:54:17 +00001473 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
Douglas Gregorb9790342010-01-22 21:44:22 +00001474}
1475
Douglas Gregor5352ac02010-01-28 00:27:43 +00001476CXSourceRange clang_getNullRange() {
1477 CXSourceRange Result = { { 0, 0 }, 0, 0 };
1478 return Result;
1479}
Daniel Dunbard52864b2010-02-14 10:02:57 +00001480
Douglas Gregor5352ac02010-01-28 00:27:43 +00001481CXSourceRange clang_getRange(CXSourceLocation begin, CXSourceLocation end) {
1482 if (begin.ptr_data[0] != end.ptr_data[0] ||
1483 begin.ptr_data[1] != end.ptr_data[1])
1484 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001485
1486 CXSourceRange Result = { { begin.ptr_data[0], begin.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00001487 begin.int_data, end.int_data };
Douglas Gregorb9790342010-01-22 21:44:22 +00001488 return Result;
1489}
1490
Douglas Gregor46766dc2010-01-26 19:19:08 +00001491void clang_getInstantiationLocation(CXSourceLocation location,
1492 CXFile *file,
1493 unsigned *line,
1494 unsigned *column,
1495 unsigned *offset) {
Douglas Gregor1db19de2010-01-19 21:36:55 +00001496 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
1497
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00001498 if (!location.ptr_data[0] || Loc.isInvalid()) {
Douglas Gregor46766dc2010-01-26 19:19:08 +00001499 if (file)
1500 *file = 0;
1501 if (line)
1502 *line = 0;
1503 if (column)
1504 *column = 0;
1505 if (offset)
1506 *offset = 0;
1507 return;
1508 }
1509
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00001510 const SourceManager &SM =
1511 *static_cast<const SourceManager*>(location.ptr_data[0]);
Douglas Gregor1db19de2010-01-19 21:36:55 +00001512 SourceLocation InstLoc = SM.getInstantiationLoc(Loc);
Douglas Gregor1db19de2010-01-19 21:36:55 +00001513
1514 if (file)
1515 *file = (void *)SM.getFileEntryForID(SM.getFileID(InstLoc));
1516 if (line)
1517 *line = SM.getInstantiationLineNumber(InstLoc);
1518 if (column)
1519 *column = SM.getInstantiationColumnNumber(InstLoc);
Douglas Gregore69517c2010-01-26 03:07:15 +00001520 if (offset)
Douglas Gregor46766dc2010-01-26 19:19:08 +00001521 *offset = SM.getDecomposedLoc(InstLoc).second;
Douglas Gregore69517c2010-01-26 03:07:15 +00001522}
1523
Douglas Gregor1db19de2010-01-19 21:36:55 +00001524CXSourceLocation clang_getRangeStart(CXSourceRange range) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001525 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00001526 range.begin_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00001527 return Result;
1528}
1529
1530CXSourceLocation clang_getRangeEnd(CXSourceRange range) {
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00001531 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00001532 range.end_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00001533 return Result;
1534}
1535
Douglas Gregorb9790342010-01-22 21:44:22 +00001536} // end: extern "C"
1537
Douglas Gregor1db19de2010-01-19 21:36:55 +00001538//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00001539// CXFile Operations.
1540//===----------------------------------------------------------------------===//
1541
1542extern "C" {
Ted Kremenek74844072010-02-17 00:41:20 +00001543CXString clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00001544 if (!SFile)
Ted Kremenek74844072010-02-17 00:41:20 +00001545 return createCXString(NULL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001546
Steve Naroff88145032009-10-27 14:35:18 +00001547 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Ted Kremenek74844072010-02-17 00:41:20 +00001548 return createCXString(FEnt->getName());
Steve Naroff88145032009-10-27 14:35:18 +00001549}
1550
1551time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00001552 if (!SFile)
1553 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001554
Steve Naroff88145032009-10-27 14:35:18 +00001555 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
1556 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +00001557}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001558
Douglas Gregorb9790342010-01-22 21:44:22 +00001559CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
1560 if (!tu)
1561 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001562
Douglas Gregorb9790342010-01-22 21:44:22 +00001563 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001564
Douglas Gregorb9790342010-01-22 21:44:22 +00001565 FileManager &FMgr = CXXUnit->getFileManager();
1566 const FileEntry *File = FMgr.getFile(file_name, file_name+strlen(file_name));
1567 return const_cast<FileEntry *>(File);
1568}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001569
Ted Kremenekfb480492010-01-13 21:46:36 +00001570} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +00001571
Ted Kremenekfb480492010-01-13 21:46:36 +00001572//===----------------------------------------------------------------------===//
1573// CXCursor Operations.
1574//===----------------------------------------------------------------------===//
1575
Ted Kremenekfb480492010-01-13 21:46:36 +00001576static Decl *getDeclFromExpr(Stmt *E) {
1577 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
1578 return RefExpr->getDecl();
1579 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
1580 return ME->getMemberDecl();
1581 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
1582 return RE->getDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001583
Ted Kremenekfb480492010-01-13 21:46:36 +00001584 if (CallExpr *CE = dyn_cast<CallExpr>(E))
1585 return getDeclFromExpr(CE->getCallee());
1586 if (CastExpr *CE = dyn_cast<CastExpr>(E))
1587 return getDeclFromExpr(CE->getSubExpr());
1588 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
1589 return OME->getMethodDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001590
Ted Kremenekfb480492010-01-13 21:46:36 +00001591 return 0;
1592}
1593
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00001594static SourceLocation getLocationFromExpr(Expr *E) {
1595 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
1596 return /*FIXME:*/Msg->getLeftLoc();
1597 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
1598 return DRE->getLocation();
1599 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
1600 return Member->getMemberLoc();
1601 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
1602 return Ivar->getLocation();
1603 return E->getLocStart();
1604}
1605
Ted Kremenekfb480492010-01-13 21:46:36 +00001606extern "C" {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001607
1608unsigned clang_visitChildren(CXCursor parent,
Douglas Gregorb1373d02010-01-20 20:59:29 +00001609 CXCursorVisitor visitor,
1610 CXClientData client_data) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001611 ASTUnit *CXXUnit = getCursorASTUnit(parent);
Douglas Gregorb1373d02010-01-20 20:59:29 +00001612
1613 unsigned PCHLevel = Decl::MaxPCHLevel;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001614
Douglas Gregorb1373d02010-01-20 20:59:29 +00001615 // Set the PCHLevel to filter out unwanted decls if requested.
1616 if (CXXUnit->getOnlyLocalDecls()) {
1617 PCHLevel = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001618
Douglas Gregorb1373d02010-01-20 20:59:29 +00001619 // If the main input was an AST, bump the level.
1620 if (CXXUnit->isMainFileAST())
1621 ++PCHLevel;
1622 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001623
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001624 CursorVisitor CursorVis(CXXUnit, visitor, client_data, PCHLevel);
Douglas Gregorb1373d02010-01-20 20:59:29 +00001625 return CursorVis.VisitChildren(parent);
1626}
1627
Douglas Gregor78205d42010-01-20 21:45:58 +00001628static CXString getDeclSpelling(Decl *D) {
1629 NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
1630 if (!ND)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001631 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001632
Douglas Gregor78205d42010-01-20 21:45:58 +00001633 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001634 return createCXString(OMD->getSelector().getAsString());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001635
Douglas Gregor78205d42010-01-20 21:45:58 +00001636 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
1637 // No, this isn't the same as the code below. getIdentifier() is non-virtual
1638 // and returns different names. NamedDecl returns the class name and
1639 // ObjCCategoryImplDecl returns the category name.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001640 return createCXString(CIMP->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001641
Ted Kremenek50aa6ac2010-05-19 21:51:10 +00001642 llvm::SmallString<1024> S;
1643 llvm::raw_svector_ostream os(S);
1644 ND->printName(os);
1645
1646 return createCXString(os.str());
Douglas Gregor78205d42010-01-20 21:45:58 +00001647}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001648
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001649CXString clang_getCursorSpelling(CXCursor C) {
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001650 if (clang_isTranslationUnit(C.kind))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001651 return clang_getTranslationUnitSpelling(C.data[2]);
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001652
Steve Narofff334b4e2009-09-02 18:26:48 +00001653 if (clang_isReference(C.kind)) {
1654 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00001655 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +00001656 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001657 return createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00001658 }
1659 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +00001660 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001661 return createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00001662 }
1663 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +00001664 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +00001665 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001666 return createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00001667 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001668 case CXCursor_TypeRef: {
1669 TypeDecl *Type = getCursorTypeRef(C).first;
1670 assert(Type && "Missing type decl");
1671
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001672 return createCXString(getCursorContext(C).getTypeDeclType(Type).
1673 getAsString());
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001674 }
1675
Daniel Dunbaracca7252009-11-30 20:42:49 +00001676 default:
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001677 return createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +00001678 }
1679 }
Douglas Gregor97b98722010-01-19 23:20:36 +00001680
1681 if (clang_isExpression(C.kind)) {
1682 Decl *D = getDeclFromExpr(getCursorExpr(C));
1683 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +00001684 return getDeclSpelling(D);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001685 return createCXString("");
Douglas Gregor97b98722010-01-19 23:20:36 +00001686 }
1687
Douglas Gregor4ae8f292010-03-18 17:52:52 +00001688 if (C.kind == CXCursor_MacroInstantiation)
1689 return createCXString(getCursorMacroInstantiation(C)->getName()
1690 ->getNameStart());
1691
Douglas Gregor572feb22010-03-18 18:04:21 +00001692 if (C.kind == CXCursor_MacroDefinition)
1693 return createCXString(getCursorMacroDefinition(C)->getName()
1694 ->getNameStart());
1695
Douglas Gregor60cbfac2010-01-25 16:56:17 +00001696 if (clang_isDeclaration(C.kind))
1697 return getDeclSpelling(getCursorDecl(C));
Ted Kremeneke68fff62010-02-17 00:41:32 +00001698
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001699 return createCXString("");
Steve Narofff334b4e2009-09-02 18:26:48 +00001700}
1701
Ted Kremeneke68fff62010-02-17 00:41:32 +00001702CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00001703 switch (Kind) {
Ted Kremeneke68fff62010-02-17 00:41:32 +00001704 case CXCursor_FunctionDecl:
1705 return createCXString("FunctionDecl");
1706 case CXCursor_TypedefDecl:
1707 return createCXString("TypedefDecl");
1708 case CXCursor_EnumDecl:
1709 return createCXString("EnumDecl");
1710 case CXCursor_EnumConstantDecl:
1711 return createCXString("EnumConstantDecl");
1712 case CXCursor_StructDecl:
1713 return createCXString("StructDecl");
1714 case CXCursor_UnionDecl:
1715 return createCXString("UnionDecl");
1716 case CXCursor_ClassDecl:
1717 return createCXString("ClassDecl");
1718 case CXCursor_FieldDecl:
1719 return createCXString("FieldDecl");
1720 case CXCursor_VarDecl:
1721 return createCXString("VarDecl");
1722 case CXCursor_ParmDecl:
1723 return createCXString("ParmDecl");
1724 case CXCursor_ObjCInterfaceDecl:
1725 return createCXString("ObjCInterfaceDecl");
1726 case CXCursor_ObjCCategoryDecl:
1727 return createCXString("ObjCCategoryDecl");
1728 case CXCursor_ObjCProtocolDecl:
1729 return createCXString("ObjCProtocolDecl");
1730 case CXCursor_ObjCPropertyDecl:
1731 return createCXString("ObjCPropertyDecl");
1732 case CXCursor_ObjCIvarDecl:
1733 return createCXString("ObjCIvarDecl");
1734 case CXCursor_ObjCInstanceMethodDecl:
1735 return createCXString("ObjCInstanceMethodDecl");
1736 case CXCursor_ObjCClassMethodDecl:
1737 return createCXString("ObjCClassMethodDecl");
1738 case CXCursor_ObjCImplementationDecl:
1739 return createCXString("ObjCImplementationDecl");
1740 case CXCursor_ObjCCategoryImplDecl:
1741 return createCXString("ObjCCategoryImplDecl");
Ted Kremenek8bd5a692010-04-13 23:39:06 +00001742 case CXCursor_CXXMethod:
1743 return createCXString("CXXMethod");
Ted Kremeneke68fff62010-02-17 00:41:32 +00001744 case CXCursor_UnexposedDecl:
1745 return createCXString("UnexposedDecl");
1746 case CXCursor_ObjCSuperClassRef:
1747 return createCXString("ObjCSuperClassRef");
1748 case CXCursor_ObjCProtocolRef:
1749 return createCXString("ObjCProtocolRef");
1750 case CXCursor_ObjCClassRef:
1751 return createCXString("ObjCClassRef");
1752 case CXCursor_TypeRef:
1753 return createCXString("TypeRef");
1754 case CXCursor_UnexposedExpr:
1755 return createCXString("UnexposedExpr");
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00001756 case CXCursor_BlockExpr:
1757 return createCXString("BlockExpr");
Ted Kremeneke68fff62010-02-17 00:41:32 +00001758 case CXCursor_DeclRefExpr:
1759 return createCXString("DeclRefExpr");
1760 case CXCursor_MemberRefExpr:
1761 return createCXString("MemberRefExpr");
1762 case CXCursor_CallExpr:
1763 return createCXString("CallExpr");
1764 case CXCursor_ObjCMessageExpr:
1765 return createCXString("ObjCMessageExpr");
1766 case CXCursor_UnexposedStmt:
1767 return createCXString("UnexposedStmt");
1768 case CXCursor_InvalidFile:
1769 return createCXString("InvalidFile");
Ted Kremenek292db642010-03-19 20:39:05 +00001770 case CXCursor_InvalidCode:
1771 return createCXString("InvalidCode");
Ted Kremeneke68fff62010-02-17 00:41:32 +00001772 case CXCursor_NoDeclFound:
1773 return createCXString("NoDeclFound");
1774 case CXCursor_NotImplemented:
1775 return createCXString("NotImplemented");
1776 case CXCursor_TranslationUnit:
1777 return createCXString("TranslationUnit");
Ted Kremeneke77f4432010-02-18 03:09:07 +00001778 case CXCursor_UnexposedAttr:
1779 return createCXString("UnexposedAttr");
1780 case CXCursor_IBActionAttr:
1781 return createCXString("attribute(ibaction)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00001782 case CXCursor_IBOutletAttr:
1783 return createCXString("attribute(iboutlet)");
Ted Kremenek857e9182010-05-19 17:38:06 +00001784 case CXCursor_IBOutletCollectionAttr:
1785 return createCXString("attribute(iboutletcollection)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00001786 case CXCursor_PreprocessingDirective:
1787 return createCXString("preprocessing directive");
Douglas Gregor572feb22010-03-18 18:04:21 +00001788 case CXCursor_MacroDefinition:
1789 return createCXString("macro definition");
Douglas Gregor48072312010-03-18 15:23:44 +00001790 case CXCursor_MacroInstantiation:
1791 return createCXString("macro instantiation");
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00001792 case CXCursor_Namespace:
1793 return createCXString("Namespace");
Ted Kremeneka0536d82010-05-07 01:04:29 +00001794 case CXCursor_LinkageSpec:
1795 return createCXString("LinkageSpec");
Steve Naroff89922f82009-08-31 00:59:03 +00001796 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00001797
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00001798 llvm_unreachable("Unhandled CXCursorKind");
Ted Kremeneke68fff62010-02-17 00:41:32 +00001799 return createCXString(NULL);
Steve Naroff600866c2009-08-27 19:51:58 +00001800}
Steve Naroff89922f82009-08-31 00:59:03 +00001801
Ted Kremeneke68fff62010-02-17 00:41:32 +00001802enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
1803 CXCursor parent,
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001804 CXClientData client_data) {
1805 CXCursor *BestCursor = static_cast<CXCursor *>(client_data);
1806 *BestCursor = cursor;
1807 return CXChildVisit_Recurse;
1808}
Ted Kremeneke68fff62010-02-17 00:41:32 +00001809
Douglas Gregorb9790342010-01-22 21:44:22 +00001810CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
1811 if (!TU)
Ted Kremenekf4629892010-01-14 01:51:23 +00001812 return clang_getNullCursor();
Ted Kremeneke68fff62010-02-17 00:41:32 +00001813
Douglas Gregorb9790342010-01-22 21:44:22 +00001814 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
1815
Douglas Gregorbdf60622010-03-05 21:16:25 +00001816 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
1817
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00001818 // Translate the given source location to make it point at the beginning of
1819 // the token under the cursor.
Ted Kremeneka297de22010-01-25 22:34:44 +00001820 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00001821 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
1822 CXXUnit->getASTContext().getLangOptions());
1823
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001824 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
1825 if (SLoc.isValid()) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001826 // FIXME: Would be great to have a "hint" cursor, then walk from that
1827 // hint cursor upward until we find a cursor whose source range encloses
1828 // the region of interest, rather than starting from the translation unit.
1829 CXCursor Parent = clang_getTranslationUnitCursor(CXXUnit);
Ted Kremeneke68fff62010-02-17 00:41:32 +00001830 CursorVisitor CursorVis(CXXUnit, GetCursorVisitor, &Result,
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00001831 Decl::MaxPCHLevel, SourceLocation(SLoc));
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001832 CursorVis.VisitChildren(Parent);
Steve Naroff77128dd2009-09-15 20:25:34 +00001833 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00001834 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00001835}
1836
Ted Kremenek73885552009-11-17 19:28:59 +00001837CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00001838 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00001839}
1840
1841unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00001842 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00001843}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001844
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001845unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00001846 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
1847}
1848
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001849unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +00001850 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
1851}
Steve Naroff2d4d6292009-08-31 14:26:51 +00001852
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001853unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00001854 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
1855}
1856
Douglas Gregor97b98722010-01-19 23:20:36 +00001857unsigned clang_isExpression(enum CXCursorKind K) {
1858 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
1859}
1860
1861unsigned clang_isStatement(enum CXCursorKind K) {
1862 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
1863}
1864
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001865unsigned clang_isTranslationUnit(enum CXCursorKind K) {
1866 return K == CXCursor_TranslationUnit;
1867}
1868
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00001869unsigned clang_isPreprocessing(enum CXCursorKind K) {
1870 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
1871}
1872
Ted Kremenekad6eff62010-03-08 21:17:29 +00001873unsigned clang_isUnexposed(enum CXCursorKind K) {
1874 switch (K) {
1875 case CXCursor_UnexposedDecl:
1876 case CXCursor_UnexposedExpr:
1877 case CXCursor_UnexposedStmt:
1878 case CXCursor_UnexposedAttr:
1879 return true;
1880 default:
1881 return false;
1882 }
1883}
1884
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001885CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00001886 return C.kind;
1887}
1888
Douglas Gregor98258af2010-01-18 22:46:11 +00001889CXSourceLocation clang_getCursorLocation(CXCursor C) {
1890 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00001891 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001892 case CXCursor_ObjCSuperClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00001893 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1894 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001895 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001896 }
1897
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001898 case CXCursor_ObjCProtocolRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00001899 std::pair<ObjCProtocolDecl *, SourceLocation> P
1900 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001901 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001902 }
1903
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001904 case CXCursor_ObjCClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00001905 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1906 = getCursorObjCClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001907 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001908 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001909
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001910 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001911 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001912 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001913 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001914
Douglas Gregorf46034a2010-01-18 23:41:10 +00001915 default:
1916 // FIXME: Need a way to enumerate all non-reference cases.
1917 llvm_unreachable("Missed a reference kind");
1918 }
Douglas Gregor98258af2010-01-18 22:46:11 +00001919 }
Douglas Gregor97b98722010-01-19 23:20:36 +00001920
1921 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001922 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00001923 getLocationFromExpr(getCursorExpr(C)));
1924
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00001925 if (C.kind == CXCursor_PreprocessingDirective) {
1926 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
1927 return cxloc::translateSourceLocation(getCursorContext(C), L);
1928 }
Douglas Gregor48072312010-03-18 15:23:44 +00001929
1930 if (C.kind == CXCursor_MacroInstantiation) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00001931 SourceLocation L
1932 = cxcursor::getCursorMacroInstantiation(C)->getSourceRange().getBegin();
Douglas Gregor48072312010-03-18 15:23:44 +00001933 return cxloc::translateSourceLocation(getCursorContext(C), L);
1934 }
Douglas Gregor572feb22010-03-18 18:04:21 +00001935
1936 if (C.kind == CXCursor_MacroDefinition) {
1937 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
1938 return cxloc::translateSourceLocation(getCursorContext(C), L);
1939 }
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00001940
Ted Kremenek9a700d22010-05-12 06:16:13 +00001941 if (C.kind < CXCursor_FirstDecl || C.kind > CXCursor_LastDecl)
Douglas Gregor5352ac02010-01-28 00:27:43 +00001942 return clang_getNullLocation();
Douglas Gregor98258af2010-01-18 22:46:11 +00001943
Douglas Gregorf46034a2010-01-18 23:41:10 +00001944 Decl *D = getCursorDecl(C);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001945 SourceLocation Loc = D->getLocation();
1946 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
1947 Loc = Class->getClassLoc();
Douglas Gregor2ca54fe2010-03-22 15:53:50 +00001948 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00001949}
Douglas Gregora7bde202010-01-19 00:34:46 +00001950
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00001951} // end extern "C"
1952
1953static SourceRange getRawCursorExtent(CXCursor C) {
Douglas Gregora7bde202010-01-19 00:34:46 +00001954 if (clang_isReference(C.kind)) {
1955 switch (C.kind) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00001956 case CXCursor_ObjCSuperClassRef:
1957 return getCursorObjCSuperClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001958
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00001959 case CXCursor_ObjCProtocolRef:
1960 return getCursorObjCProtocolRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001961
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00001962 case CXCursor_ObjCClassRef:
1963 return getCursorObjCClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001964
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00001965 case CXCursor_TypeRef:
1966 return getCursorTypeRef(C).second;
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001967
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00001968 default:
1969 // FIXME: Need a way to enumerate all non-reference cases.
1970 llvm_unreachable("Missed a reference kind");
Douglas Gregora7bde202010-01-19 00:34:46 +00001971 }
1972 }
Douglas Gregor97b98722010-01-19 23:20:36 +00001973
1974 if (clang_isExpression(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00001975 return getCursorExpr(C)->getSourceRange();
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001976
1977 if (clang_isStatement(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00001978 return getCursorStmt(C)->getSourceRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001979
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00001980 if (C.kind == CXCursor_PreprocessingDirective)
1981 return cxcursor::getCursorPreprocessingDirective(C);
Douglas Gregor48072312010-03-18 15:23:44 +00001982
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00001983 if (C.kind == CXCursor_MacroInstantiation)
1984 return cxcursor::getCursorMacroInstantiation(C)->getSourceRange();
Douglas Gregor572feb22010-03-18 18:04:21 +00001985
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00001986 if (C.kind == CXCursor_MacroDefinition)
1987 return cxcursor::getCursorMacroDefinition(C)->getSourceRange();
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00001988
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00001989 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl)
1990 return getCursorDecl(C)->getSourceRange();
1991
1992 return SourceRange();
1993}
1994
1995extern "C" {
1996
1997CXSourceRange clang_getCursorExtent(CXCursor C) {
1998 SourceRange R = getRawCursorExtent(C);
1999 if (R.isInvalid())
Douglas Gregor5352ac02010-01-28 00:27:43 +00002000 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002001
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002002 return cxloc::translateSourceRange(getCursorContext(C), R);
Douglas Gregora7bde202010-01-19 00:34:46 +00002003}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002004
2005CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002006 if (clang_isInvalid(C.kind))
2007 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002008
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002009 ASTUnit *CXXUnit = getCursorASTUnit(C);
Douglas Gregorb6998662010-01-19 19:34:47 +00002010 if (clang_isDeclaration(C.kind))
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002011 return C;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002012
Douglas Gregor97b98722010-01-19 23:20:36 +00002013 if (clang_isExpression(C.kind)) {
2014 Decl *D = getDeclFromExpr(getCursorExpr(C));
2015 if (D)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002016 return MakeCXCursor(D, CXXUnit);
Douglas Gregor97b98722010-01-19 23:20:36 +00002017 return clang_getNullCursor();
2018 }
2019
Douglas Gregorbf7efa22010-03-18 18:23:03 +00002020 if (C.kind == CXCursor_MacroInstantiation) {
2021 if (MacroDefinition *Def = getCursorMacroInstantiation(C)->getDefinition())
2022 return MakeMacroDefinitionCursor(Def, CXXUnit);
2023 }
2024
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002025 if (!clang_isReference(C.kind))
2026 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002027
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002028 switch (C.kind) {
2029 case CXCursor_ObjCSuperClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002030 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002031
2032 case CXCursor_ObjCProtocolRef: {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002033 return MakeCXCursor(getCursorObjCProtocolRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002034
2035 case CXCursor_ObjCClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002036 return MakeCXCursor(getCursorObjCClassRef(C).first, CXXUnit);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002037
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002038 case CXCursor_TypeRef:
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002039 return MakeCXCursor(getCursorTypeRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002040
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002041 default:
2042 // We would prefer to enumerate all non-reference cursor kinds here.
2043 llvm_unreachable("Unhandled reference cursor kind");
2044 break;
2045 }
2046 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002047
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002048 return clang_getNullCursor();
2049}
2050
Douglas Gregorb6998662010-01-19 19:34:47 +00002051CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002052 if (clang_isInvalid(C.kind))
2053 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002054
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002055 ASTUnit *CXXUnit = getCursorASTUnit(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002056
Douglas Gregorb6998662010-01-19 19:34:47 +00002057 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00002058 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00002059 C = clang_getCursorReferenced(C);
2060 WasReference = true;
2061 }
2062
Douglas Gregorbf7efa22010-03-18 18:23:03 +00002063 if (C.kind == CXCursor_MacroInstantiation)
2064 return clang_getCursorReferenced(C);
2065
Douglas Gregorb6998662010-01-19 19:34:47 +00002066 if (!clang_isDeclaration(C.kind))
2067 return clang_getNullCursor();
2068
2069 Decl *D = getCursorDecl(C);
2070 if (!D)
2071 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002072
Douglas Gregorb6998662010-01-19 19:34:47 +00002073 switch (D->getKind()) {
2074 // Declaration kinds that don't really separate the notions of
2075 // declaration and definition.
2076 case Decl::Namespace:
2077 case Decl::Typedef:
2078 case Decl::TemplateTypeParm:
2079 case Decl::EnumConstant:
2080 case Decl::Field:
2081 case Decl::ObjCIvar:
2082 case Decl::ObjCAtDefsField:
2083 case Decl::ImplicitParam:
2084 case Decl::ParmVar:
2085 case Decl::NonTypeTemplateParm:
2086 case Decl::TemplateTemplateParm:
2087 case Decl::ObjCCategoryImpl:
2088 case Decl::ObjCImplementation:
Abramo Bagnara6206d532010-06-05 05:09:32 +00002089 case Decl::AccessSpec:
Douglas Gregorb6998662010-01-19 19:34:47 +00002090 case Decl::LinkageSpec:
2091 case Decl::ObjCPropertyImpl:
2092 case Decl::FileScopeAsm:
2093 case Decl::StaticAssert:
2094 case Decl::Block:
2095 return C;
2096
2097 // Declaration kinds that don't make any sense here, but are
2098 // nonetheless harmless.
2099 case Decl::TranslationUnit:
Douglas Gregorb6998662010-01-19 19:34:47 +00002100 break;
2101
2102 // Declaration kinds for which the definition is not resolvable.
2103 case Decl::UnresolvedUsingTypename:
2104 case Decl::UnresolvedUsingValue:
2105 break;
2106
2107 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002108 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
2109 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002110
2111 case Decl::NamespaceAlias:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002112 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002113
2114 case Decl::Enum:
2115 case Decl::Record:
2116 case Decl::CXXRecord:
2117 case Decl::ClassTemplateSpecialization:
2118 case Decl::ClassTemplatePartialSpecialization:
Douglas Gregor952b0172010-02-11 01:04:33 +00002119 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002120 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002121 return clang_getNullCursor();
2122
2123 case Decl::Function:
2124 case Decl::CXXMethod:
2125 case Decl::CXXConstructor:
2126 case Decl::CXXDestructor:
2127 case Decl::CXXConversion: {
2128 const FunctionDecl *Def = 0;
2129 if (cast<FunctionDecl>(D)->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002130 return MakeCXCursor(const_cast<FunctionDecl *>(Def), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002131 return clang_getNullCursor();
2132 }
2133
2134 case Decl::Var: {
Sebastian Redl31310a22010-02-01 20:16:42 +00002135 // Ask the variable if it has a definition.
2136 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
2137 return MakeCXCursor(Def, CXXUnit);
2138 return clang_getNullCursor();
Douglas Gregorb6998662010-01-19 19:34:47 +00002139 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002140
Douglas Gregorb6998662010-01-19 19:34:47 +00002141 case Decl::FunctionTemplate: {
2142 const FunctionDecl *Def = 0;
2143 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002144 return MakeCXCursor(Def->getDescribedFunctionTemplate(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002145 return clang_getNullCursor();
2146 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002147
Douglas Gregorb6998662010-01-19 19:34:47 +00002148 case Decl::ClassTemplate: {
2149 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
Douglas Gregor952b0172010-02-11 01:04:33 +00002150 ->getDefinition())
Douglas Gregorb6998662010-01-19 19:34:47 +00002151 return MakeCXCursor(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002152 cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002153 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002154 return clang_getNullCursor();
2155 }
2156
2157 case Decl::Using: {
2158 UsingDecl *Using = cast<UsingDecl>(D);
2159 CXCursor Def = clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002160 for (UsingDecl::shadow_iterator S = Using->shadow_begin(),
2161 SEnd = Using->shadow_end();
Douglas Gregorb6998662010-01-19 19:34:47 +00002162 S != SEnd; ++S) {
2163 if (Def != clang_getNullCursor()) {
2164 // FIXME: We have no way to return multiple results.
2165 return clang_getNullCursor();
2166 }
2167
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002168 Def = clang_getCursorDefinition(MakeCXCursor((*S)->getTargetDecl(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002169 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002170 }
2171
2172 return Def;
2173 }
2174
2175 case Decl::UsingShadow:
2176 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002177 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002178 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002179
2180 case Decl::ObjCMethod: {
2181 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
2182 if (Method->isThisDeclarationADefinition())
2183 return C;
2184
2185 // Dig out the method definition in the associated
2186 // @implementation, if we have it.
2187 // FIXME: The ASTs should make finding the definition easier.
2188 if (ObjCInterfaceDecl *Class
2189 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
2190 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
2191 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
2192 Method->isInstanceMethod()))
2193 if (Def->isThisDeclarationADefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002194 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002195
2196 return clang_getNullCursor();
2197 }
2198
2199 case Decl::ObjCCategory:
2200 if (ObjCCategoryImplDecl *Impl
2201 = cast<ObjCCategoryDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002202 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002203 return clang_getNullCursor();
2204
2205 case Decl::ObjCProtocol:
2206 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
2207 return C;
2208 return clang_getNullCursor();
2209
2210 case Decl::ObjCInterface:
2211 // There are two notions of a "definition" for an Objective-C
2212 // class: the interface and its implementation. When we resolved a
2213 // reference to an Objective-C class, produce the @interface as
2214 // the definition; when we were provided with the interface,
2215 // produce the @implementation as the definition.
2216 if (WasReference) {
2217 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
2218 return C;
2219 } else if (ObjCImplementationDecl *Impl
2220 = cast<ObjCInterfaceDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002221 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002222 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002223
Douglas Gregorb6998662010-01-19 19:34:47 +00002224 case Decl::ObjCProperty:
2225 // FIXME: We don't really know where to find the
2226 // ObjCPropertyImplDecls that implement this property.
2227 return clang_getNullCursor();
2228
2229 case Decl::ObjCCompatibleAlias:
2230 if (ObjCInterfaceDecl *Class
2231 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
2232 if (!Class->isForwardDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002233 return MakeCXCursor(Class, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002234
Douglas Gregorb6998662010-01-19 19:34:47 +00002235 return clang_getNullCursor();
2236
2237 case Decl::ObjCForwardProtocol: {
2238 ObjCForwardProtocolDecl *Forward = cast<ObjCForwardProtocolDecl>(D);
2239 if (Forward->protocol_size() == 1)
2240 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002241 MakeCXCursor(*Forward->protocol_begin(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002242 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002243
2244 // FIXME: Cannot return multiple definitions.
2245 return clang_getNullCursor();
2246 }
2247
2248 case Decl::ObjCClass: {
2249 ObjCClassDecl *Class = cast<ObjCClassDecl>(D);
2250 if (Class->size() == 1) {
2251 ObjCInterfaceDecl *IFace = Class->begin()->getInterface();
2252 if (!IFace->isForwardDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002253 return MakeCXCursor(IFace, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002254 return clang_getNullCursor();
2255 }
2256
2257 // FIXME: Cannot return multiple definitions.
2258 return clang_getNullCursor();
2259 }
2260
2261 case Decl::Friend:
2262 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002263 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002264 return clang_getNullCursor();
2265
2266 case Decl::FriendTemplate:
2267 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002268 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002269 return clang_getNullCursor();
2270 }
2271
2272 return clang_getNullCursor();
2273}
2274
2275unsigned clang_isCursorDefinition(CXCursor C) {
2276 if (!clang_isDeclaration(C.kind))
2277 return 0;
2278
2279 return clang_getCursorDefinition(C) == C;
2280}
2281
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002282void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00002283 const char **startBuf,
2284 const char **endBuf,
2285 unsigned *startLine,
2286 unsigned *startColumn,
2287 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002288 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00002289 assert(getCursorDecl(C) && "CXCursor has null decl");
2290 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00002291 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
2292 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002293
Steve Naroff4ade6d62009-09-23 17:52:52 +00002294 SourceManager &SM = FD->getASTContext().getSourceManager();
2295 *startBuf = SM.getCharacterData(Body->getLBracLoc());
2296 *endBuf = SM.getCharacterData(Body->getRBracLoc());
2297 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
2298 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
2299 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
2300 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
2301}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002302
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002303void clang_enableStackTraces(void) {
2304 llvm::sys::PrintStackTraceOnErrorSignal();
2305}
2306
Ted Kremenekfb480492010-01-13 21:46:36 +00002307} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00002308
Ted Kremenekfb480492010-01-13 21:46:36 +00002309//===----------------------------------------------------------------------===//
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002310// Token-based Operations.
2311//===----------------------------------------------------------------------===//
2312
2313/* CXToken layout:
2314 * int_data[0]: a CXTokenKind
2315 * int_data[1]: starting token location
2316 * int_data[2]: token length
2317 * int_data[3]: reserved
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002318 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002319 * otherwise unused.
2320 */
2321extern "C" {
2322
2323CXTokenKind clang_getTokenKind(CXToken CXTok) {
2324 return static_cast<CXTokenKind>(CXTok.int_data[0]);
2325}
2326
2327CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
2328 switch (clang_getTokenKind(CXTok)) {
2329 case CXToken_Identifier:
2330 case CXToken_Keyword:
2331 // We know we have an IdentifierInfo*, so use that.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002332 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
2333 ->getNameStart());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002334
2335 case CXToken_Literal: {
2336 // We have stashed the starting pointer in the ptr_data field. Use it.
2337 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002338 return createCXString(llvm::StringRef(Text, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002339 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002340
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002341 case CXToken_Punctuation:
2342 case CXToken_Comment:
2343 break;
2344 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002345
2346 // We have to find the starting buffer pointer the hard way, by
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002347 // deconstructing the source location.
2348 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2349 if (!CXXUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002350 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002351
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002352 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
2353 std::pair<FileID, unsigned> LocInfo
2354 = CXXUnit->getSourceManager().getDecomposedLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +00002355 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002356 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00002357 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
2358 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00002359 return createCXString("");
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002360
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002361 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002362}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002363
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002364CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
2365 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2366 if (!CXXUnit)
2367 return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002368
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002369 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
2370 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
2371}
2372
2373CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
2374 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregor5352ac02010-01-28 00:27:43 +00002375 if (!CXXUnit)
2376 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002377
2378 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002379 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
2380}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002381
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002382void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
2383 CXToken **Tokens, unsigned *NumTokens) {
2384 if (Tokens)
2385 *Tokens = 0;
2386 if (NumTokens)
2387 *NumTokens = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002388
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002389 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2390 if (!CXXUnit || !Tokens || !NumTokens)
2391 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002392
Douglas Gregorbdf60622010-03-05 21:16:25 +00002393 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
2394
Daniel Dunbar85b988f2010-02-14 08:31:57 +00002395 SourceRange R = cxloc::translateCXSourceRange(Range);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002396 if (R.isInvalid())
2397 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002398
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002399 SourceManager &SourceMgr = CXXUnit->getSourceManager();
2400 std::pair<FileID, unsigned> BeginLocInfo
2401 = SourceMgr.getDecomposedLoc(R.getBegin());
2402 std::pair<FileID, unsigned> EndLocInfo
2403 = SourceMgr.getDecomposedLoc(R.getEnd());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002404
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002405 // Cannot tokenize across files.
2406 if (BeginLocInfo.first != EndLocInfo.first)
2407 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002408
2409 // Create a lexer
Douglas Gregorf715ca12010-03-16 00:06:06 +00002410 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002411 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00002412 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
Douglas Gregor47a3fcd2010-03-16 20:26:15 +00002413 if (Invalid)
2414 return;
Douglas Gregoraea67db2010-03-15 22:54:52 +00002415
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002416 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
2417 CXXUnit->getASTContext().getLangOptions(),
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002418 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002419 Lex.SetCommentRetentionState(true);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002420
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002421 // Lex tokens until we hit the end of the range.
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002422 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002423 llvm::SmallVector<CXToken, 32> CXTokens;
2424 Token Tok;
2425 do {
2426 // Lex the next token
2427 Lex.LexFromRawLexer(Tok);
2428 if (Tok.is(tok::eof))
2429 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002430
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002431 // Initialize the CXToken.
2432 CXToken CXTok;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002433
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002434 // - Common fields
2435 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
2436 CXTok.int_data[2] = Tok.getLength();
2437 CXTok.int_data[3] = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002438
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002439 // - Kind-specific fields
2440 if (Tok.isLiteral()) {
2441 CXTok.int_data[0] = CXToken_Literal;
2442 CXTok.ptr_data = (void *)Tok.getLiteralData();
2443 } else if (Tok.is(tok::identifier)) {
Douglas Gregoraea67db2010-03-15 22:54:52 +00002444 // Lookup the identifier to determine whether we have a keyword.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002445 std::pair<FileID, unsigned> LocInfo
2446 = SourceMgr.getDecomposedLoc(Tok.getLocation());
Douglas Gregorf715ca12010-03-16 00:06:06 +00002447 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002448 llvm::StringRef Buf
Douglas Gregorf715ca12010-03-16 00:06:06 +00002449 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
2450 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00002451 return;
2452
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002453 const char *StartPos = Buf.data() + LocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002454 IdentifierInfo *II
2455 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok, StartPos);
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00002456
2457 if (II->getObjCKeywordID() != tok::objc_not_keyword) {
2458 CXTok.int_data[0] = CXToken_Keyword;
2459 }
2460 else {
2461 CXTok.int_data[0] = II->getTokenID() == tok::identifier?
2462 CXToken_Identifier
2463 : CXToken_Keyword;
2464 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002465 CXTok.ptr_data = II;
2466 } else if (Tok.is(tok::comment)) {
2467 CXTok.int_data[0] = CXToken_Comment;
2468 CXTok.ptr_data = 0;
2469 } else {
2470 CXTok.int_data[0] = CXToken_Punctuation;
2471 CXTok.ptr_data = 0;
2472 }
2473 CXTokens.push_back(CXTok);
2474 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002475
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002476 if (CXTokens.empty())
2477 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002478
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002479 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
2480 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
2481 *NumTokens = CXTokens.size();
2482}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002483
Ted Kremenek6db61092010-05-05 00:55:15 +00002484void clang_disposeTokens(CXTranslationUnit TU,
2485 CXToken *Tokens, unsigned NumTokens) {
2486 free(Tokens);
2487}
2488
2489} // end: extern "C"
2490
2491//===----------------------------------------------------------------------===//
2492// Token annotation APIs.
2493//===----------------------------------------------------------------------===//
2494
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002495typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002496static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
2497 CXCursor parent,
2498 CXClientData client_data);
Ted Kremenek6db61092010-05-05 00:55:15 +00002499namespace {
2500class AnnotateTokensWorker {
2501 AnnotateTokensData &Annotated;
Ted Kremenek11949cb2010-05-05 00:55:17 +00002502 CXToken *Tokens;
2503 CXCursor *Cursors;
2504 unsigned NumTokens;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002505 unsigned TokIdx;
2506 CursorVisitor AnnotateVis;
2507 SourceManager &SrcMgr;
2508
2509 bool MoreTokens() const { return TokIdx < NumTokens; }
2510 unsigned NextToken() const { return TokIdx; }
2511 void AdvanceToken() { ++TokIdx; }
2512 SourceLocation GetTokenLoc(unsigned tokI) {
2513 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
2514 }
2515
Ted Kremenek6db61092010-05-05 00:55:15 +00002516public:
Ted Kremenek11949cb2010-05-05 00:55:17 +00002517 AnnotateTokensWorker(AnnotateTokensData &annotated,
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002518 CXToken *tokens, CXCursor *cursors, unsigned numTokens,
2519 ASTUnit *CXXUnit, SourceRange RegionOfInterest)
Ted Kremenek11949cb2010-05-05 00:55:17 +00002520 : Annotated(annotated), Tokens(tokens), Cursors(cursors),
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002521 NumTokens(numTokens), TokIdx(0),
2522 AnnotateVis(CXXUnit, AnnotateTokensVisitor, this,
2523 Decl::MaxPCHLevel, RegionOfInterest),
2524 SrcMgr(CXXUnit->getSourceManager()) {}
Ted Kremenek11949cb2010-05-05 00:55:17 +00002525
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002526 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
Ted Kremenek6db61092010-05-05 00:55:15 +00002527 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002528 void AnnotateTokens(CXCursor parent);
Ted Kremenek6db61092010-05-05 00:55:15 +00002529};
2530}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002531
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002532void AnnotateTokensWorker::AnnotateTokens(CXCursor parent) {
2533 // Walk the AST within the region of interest, annotating tokens
2534 // along the way.
2535 VisitChildren(parent);
Ted Kremenek11949cb2010-05-05 00:55:17 +00002536
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002537 for (unsigned I = 0 ; I < TokIdx ; ++I) {
2538 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
2539 if (Pos != Annotated.end())
2540 Cursors[I] = Pos->second;
2541 }
2542
2543 // Finish up annotating any tokens left.
2544 if (!MoreTokens())
2545 return;
2546
2547 const CXCursor &C = clang_getNullCursor();
2548 for (unsigned I = TokIdx ; I < NumTokens ; ++I) {
2549 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
2550 Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second;
Ted Kremenek11949cb2010-05-05 00:55:17 +00002551 }
2552}
2553
Ted Kremenek6db61092010-05-05 00:55:15 +00002554enum CXChildVisitResult
2555AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002556 CXSourceLocation Loc = clang_getCursorLocation(cursor);
2557 // We can always annotate a preprocessing directive/macro instantiation.
2558 if (clang_isPreprocessing(cursor.kind)) {
2559 Annotated[Loc.int_data] = cursor;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002560 return CXChildVisit_Recurse;
2561 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002562
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002563 SourceRange cursorRange = getRawCursorExtent(cursor);
Ted Kremeneka333c662010-05-12 05:29:33 +00002564
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002565 if (cursorRange.isInvalid())
2566 return CXChildVisit_Continue;
Ted Kremeneka333c662010-05-12 05:29:33 +00002567
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002568 SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data);
2569
Ted Kremeneka333c662010-05-12 05:29:33 +00002570 // Adjust the annotated range based specific declarations.
2571 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
2572 if (cursorK >= CXCursor_FirstDecl && cursorK <= CXCursor_LastDecl) {
Ted Kremenek23173d72010-05-18 21:09:07 +00002573 Decl *D = cxcursor::getCursorDecl(cursor);
2574 // Don't visit synthesized ObjC methods, since they have no syntatic
2575 // representation in the source.
2576 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
2577 if (MD->isSynthesized())
2578 return CXChildVisit_Continue;
2579 }
2580 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
Ted Kremeneka333c662010-05-12 05:29:33 +00002581 if (TypeSourceInfo *TI = DD->getTypeSourceInfo()) {
2582 TypeLoc TL = TI->getTypeLoc();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00002583 SourceLocation TLoc = TL.getSourceRange().getBegin();
Ted Kremenek6bfd5332010-05-13 15:38:38 +00002584 if (TLoc.isValid() &&
2585 SrcMgr.isBeforeInTranslationUnit(TLoc, L))
Ted Kremeneka333c662010-05-12 05:29:33 +00002586 cursorRange.setBegin(TLoc);
Ted Kremeneka333c662010-05-12 05:29:33 +00002587 }
2588 }
2589 }
2590
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002591 const enum CXCursorKind K = clang_getCursorKind(parent);
2592 const CXCursor updateC =
2593 (clang_isInvalid(K) || K == CXCursor_TranslationUnit ||
2594 L.isMacroID())
2595 ? clang_getNullCursor() : parent;
2596
2597 while (MoreTokens()) {
2598 const unsigned I = NextToken();
2599 SourceLocation TokLoc = GetTokenLoc(I);
2600 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
2601 case RangeBefore:
2602 Cursors[I] = updateC;
2603 AdvanceToken();
2604 continue;
2605 case RangeAfter:
2606 return CXChildVisit_Continue;
2607 case RangeOverlap:
2608 break;
2609 }
2610 break;
2611 }
2612
2613 // Visit children to get their cursor information.
2614 const unsigned BeforeChildren = NextToken();
2615 VisitChildren(cursor);
2616 const unsigned AfterChildren = NextToken();
2617
2618 // Adjust 'Last' to the last token within the extent of the cursor.
2619 while (MoreTokens()) {
2620 const unsigned I = NextToken();
2621 SourceLocation TokLoc = GetTokenLoc(I);
2622 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
2623 case RangeBefore:
2624 assert(0 && "Infeasible");
2625 case RangeAfter:
2626 break;
2627 case RangeOverlap:
2628 Cursors[I] = updateC;
2629 AdvanceToken();
2630 continue;
2631 }
2632 break;
2633 }
2634 const unsigned Last = NextToken();
Ted Kremenek6db61092010-05-05 00:55:15 +00002635
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002636 // Scan the tokens that are at the beginning of the cursor, but are not
2637 // capture by the child cursors.
2638
2639 // For AST elements within macros, rely on a post-annotate pass to
2640 // to correctly annotate the tokens with cursors. Otherwise we can
2641 // get confusing results of having tokens that map to cursors that really
2642 // are expanded by an instantiation.
2643 if (L.isMacroID())
2644 cursor = clang_getNullCursor();
2645
2646 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
2647 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
2648 break;
2649 Cursors[I] = cursor;
2650 }
2651 // Scan the tokens that are at the end of the cursor, but are not captured
2652 // but the child cursors.
2653 for (unsigned I = AfterChildren; I != Last; ++I)
2654 Cursors[I] = cursor;
2655
2656 TokIdx = Last;
2657 return CXChildVisit_Continue;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002658}
2659
Ted Kremenek6db61092010-05-05 00:55:15 +00002660static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
2661 CXCursor parent,
2662 CXClientData client_data) {
2663 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
2664}
2665
2666extern "C" {
2667
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002668void clang_annotateTokens(CXTranslationUnit TU,
2669 CXToken *Tokens, unsigned NumTokens,
2670 CXCursor *Cursors) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002671
2672 if (NumTokens == 0 || !Tokens || !Cursors)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002673 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002674
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002675 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002676 if (!CXXUnit) {
2677 // Any token we don't specifically annotate will have a NULL cursor.
2678 const CXCursor &C = clang_getNullCursor();
2679 for (unsigned I = 0; I != NumTokens; ++I)
2680 Cursors[I] = C;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002681 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002682 }
2683
Douglas Gregorbdf60622010-03-05 21:16:25 +00002684 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002685
Douglas Gregor0396f462010-03-19 05:22:59 +00002686 // Determine the region of interest, which contains all of the tokens.
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002687 SourceRange RegionOfInterest;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002688 RegionOfInterest.setBegin(cxloc::translateSourceLocation(
2689 clang_getTokenLocation(TU, Tokens[0])));
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002690 RegionOfInterest.setEnd(cxloc::translateSourceLocation(
2691 clang_getTokenLocation(TU,
2692 Tokens[NumTokens - 1])));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002693
Douglas Gregor0396f462010-03-19 05:22:59 +00002694 // A mapping from the source locations found when re-lexing or traversing the
2695 // region of interest to the corresponding cursors.
2696 AnnotateTokensData Annotated;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002697
2698 // Relex the tokens within the source range to look for preprocessing
Douglas Gregor0396f462010-03-19 05:22:59 +00002699 // directives.
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002700 SourceManager &SourceMgr = CXXUnit->getSourceManager();
2701 std::pair<FileID, unsigned> BeginLocInfo
2702 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
2703 std::pair<FileID, unsigned> EndLocInfo
2704 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002705
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002706 llvm::StringRef Buffer;
Douglas Gregor0396f462010-03-19 05:22:59 +00002707 bool Invalid = false;
2708 if (BeginLocInfo.first == EndLocInfo.first &&
2709 ((Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid)),true) &&
2710 !Invalid) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002711 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
2712 CXXUnit->getASTContext().getLangOptions(),
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002713 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002714 Buffer.end());
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002715 Lex.SetCommentRetentionState(true);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002716
2717 // Lex tokens in raw mode until we hit the end of the range, to avoid
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002718 // entering #includes or expanding macros.
Douglas Gregor48072312010-03-18 15:23:44 +00002719 while (true) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002720 Token Tok;
2721 Lex.LexFromRawLexer(Tok);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002722
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002723 reprocess:
2724 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
2725 // We have found a preprocessing directive. Gobble it up so that we
2726 // don't see it while preprocessing these tokens later, but keep track of
2727 // all of the token locations inside this preprocessing directive so that
2728 // we can annotate them appropriately.
2729 //
2730 // FIXME: Some simple tests here could identify macro definitions and
2731 // #undefs, to provide specific cursor kinds for those.
2732 std::vector<SourceLocation> Locations;
2733 do {
2734 Locations.push_back(Tok.getLocation());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002735 Lex.LexFromRawLexer(Tok);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002736 } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002737
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002738 using namespace cxcursor;
2739 CXCursor Cursor
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002740 = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
2741 Locations.back()),
Ted Kremenek6db61092010-05-05 00:55:15 +00002742 CXXUnit);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002743 for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
2744 Annotated[Locations[I].getRawEncoding()] = Cursor;
2745 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002746
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002747 if (Tok.isAtStartOfLine())
2748 goto reprocess;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002749
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002750 continue;
2751 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002752
Douglas Gregor48072312010-03-18 15:23:44 +00002753 if (Tok.is(tok::eof))
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002754 break;
2755 }
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002756 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002757
Douglas Gregor0396f462010-03-19 05:22:59 +00002758 // Annotate all of the source locations in the region of interest that map to
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002759 // a specific cursor.
2760 AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens,
2761 CXXUnit, RegionOfInterest);
2762 W.AnnotateTokens(clang_getTranslationUnitCursor(CXXUnit));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002763}
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002764} // end: extern "C"
2765
2766//===----------------------------------------------------------------------===//
Ted Kremenek16b42592010-03-03 06:36:57 +00002767// Operations for querying linkage of a cursor.
2768//===----------------------------------------------------------------------===//
2769
2770extern "C" {
2771CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
Douglas Gregor0396f462010-03-19 05:22:59 +00002772 if (!clang_isDeclaration(cursor.kind))
2773 return CXLinkage_Invalid;
2774
Ted Kremenek16b42592010-03-03 06:36:57 +00002775 Decl *D = cxcursor::getCursorDecl(cursor);
2776 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
2777 switch (ND->getLinkage()) {
2778 case NoLinkage: return CXLinkage_NoLinkage;
2779 case InternalLinkage: return CXLinkage_Internal;
2780 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
2781 case ExternalLinkage: return CXLinkage_External;
2782 };
2783
2784 return CXLinkage_Invalid;
2785}
2786} // end: extern "C"
2787
2788//===----------------------------------------------------------------------===//
Ted Kremenek45e1dae2010-04-12 21:22:16 +00002789// Operations for querying language of a cursor.
2790//===----------------------------------------------------------------------===//
2791
2792static CXLanguageKind getDeclLanguage(const Decl *D) {
2793 switch (D->getKind()) {
2794 default:
2795 break;
2796 case Decl::ImplicitParam:
2797 case Decl::ObjCAtDefsField:
2798 case Decl::ObjCCategory:
2799 case Decl::ObjCCategoryImpl:
2800 case Decl::ObjCClass:
2801 case Decl::ObjCCompatibleAlias:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00002802 case Decl::ObjCForwardProtocol:
2803 case Decl::ObjCImplementation:
2804 case Decl::ObjCInterface:
2805 case Decl::ObjCIvar:
2806 case Decl::ObjCMethod:
2807 case Decl::ObjCProperty:
2808 case Decl::ObjCPropertyImpl:
2809 case Decl::ObjCProtocol:
2810 return CXLanguage_ObjC;
2811 case Decl::CXXConstructor:
2812 case Decl::CXXConversion:
2813 case Decl::CXXDestructor:
2814 case Decl::CXXMethod:
2815 case Decl::CXXRecord:
2816 case Decl::ClassTemplate:
2817 case Decl::ClassTemplatePartialSpecialization:
2818 case Decl::ClassTemplateSpecialization:
2819 case Decl::Friend:
2820 case Decl::FriendTemplate:
2821 case Decl::FunctionTemplate:
2822 case Decl::LinkageSpec:
2823 case Decl::Namespace:
2824 case Decl::NamespaceAlias:
2825 case Decl::NonTypeTemplateParm:
2826 case Decl::StaticAssert:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00002827 case Decl::TemplateTemplateParm:
2828 case Decl::TemplateTypeParm:
2829 case Decl::UnresolvedUsingTypename:
2830 case Decl::UnresolvedUsingValue:
2831 case Decl::Using:
2832 case Decl::UsingDirective:
2833 case Decl::UsingShadow:
2834 return CXLanguage_CPlusPlus;
2835 }
2836
2837 return CXLanguage_C;
2838}
2839
2840extern "C" {
2841CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
2842 if (clang_isDeclaration(cursor.kind))
2843 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
2844
2845 return CXLanguage_Invalid;
2846}
2847} // end: extern "C"
2848
Ted Kremenek9ada39a2010-05-17 20:06:56 +00002849
2850//===----------------------------------------------------------------------===//
2851// C++ AST instrospection.
2852//===----------------------------------------------------------------------===//
2853
2854extern "C" {
2855unsigned clang_CXXMethod_isStatic(CXCursor C) {
2856 if (!clang_isDeclaration(C.kind))
2857 return 0;
2858 CXXMethodDecl *D = dyn_cast<CXXMethodDecl>(cxcursor::getCursorDecl(C));
2859 return (D && D->isStatic()) ? 1 : 0;
Ted Kremenek40b492a2010-05-17 20:12:45 +00002860}
Ted Kremenekb12903e2010-05-18 22:32:15 +00002861
Ted Kremenek9ada39a2010-05-17 20:06:56 +00002862} // end: extern "C"
2863
Ted Kremenek45e1dae2010-04-12 21:22:16 +00002864//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00002865// CXString Operations.
2866//===----------------------------------------------------------------------===//
2867
2868extern "C" {
2869const char *clang_getCString(CXString string) {
2870 return string.Spelling;
2871}
2872
2873void clang_disposeString(CXString string) {
2874 if (string.MustFreeString && string.Spelling)
2875 free((void*)string.Spelling);
2876}
Ted Kremenek04bb7162010-01-22 22:44:15 +00002877
Ted Kremenekfb480492010-01-13 21:46:36 +00002878} // end: extern "C"
Ted Kremenek04bb7162010-01-22 22:44:15 +00002879
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002880namespace clang { namespace cxstring {
2881CXString createCXString(const char *String, bool DupString){
2882 CXString Str;
2883 if (DupString) {
2884 Str.Spelling = strdup(String);
2885 Str.MustFreeString = 1;
2886 } else {
2887 Str.Spelling = String;
2888 Str.MustFreeString = 0;
2889 }
2890 return Str;
2891}
2892
2893CXString createCXString(llvm::StringRef String, bool DupString) {
2894 CXString Result;
2895 if (DupString || (!String.empty() && String.data()[String.size()] != 0)) {
2896 char *Spelling = (char *)malloc(String.size() + 1);
2897 memmove(Spelling, String.data(), String.size());
2898 Spelling[String.size()] = 0;
2899 Result.Spelling = Spelling;
2900 Result.MustFreeString = 1;
2901 } else {
2902 Result.Spelling = String.data();
2903 Result.MustFreeString = 0;
2904 }
2905 return Result;
2906}
2907}}
2908
Ted Kremenek04bb7162010-01-22 22:44:15 +00002909//===----------------------------------------------------------------------===//
2910// Misc. utility functions.
2911//===----------------------------------------------------------------------===//
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002912
Ted Kremenek04bb7162010-01-22 22:44:15 +00002913extern "C" {
2914
Ted Kremeneka2a9d6e2010-02-12 22:54:40 +00002915CXString clang_getClangVersion() {
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002916 return createCXString(getClangFullVersion());
Ted Kremenek04bb7162010-01-22 22:44:15 +00002917}
2918
2919} // end: extern "C"