blob: 0a3d54b6cbbc98166cfff01ea62fce9be97b7a81 [file] [log] [blame]
Ted Kremenekd2fa5662009-08-26 22:36:44 +00001//===- CIndex.cpp - Clang-C Source Indexing Library -----------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00007//
Ted Kremenekd2fa5662009-08-26 22:36:44 +00008//===----------------------------------------------------------------------===//
9//
Ted Kremenekab188932010-01-05 19:32:54 +000010// This file implements the main API hooks in the Clang-C Source Indexing
11// library.
Ted Kremenekd2fa5662009-08-26 22:36:44 +000012//
13//===----------------------------------------------------------------------===//
14
Ted Kremenekab188932010-01-05 19:32:54 +000015#include "CIndexer.h"
Ted Kremenek16c440a2010-01-15 20:35:54 +000016#include "CXCursor.h"
Ted Kremeneka297de22010-01-25 22:34:44 +000017#include "CXSourceLocation.h"
Douglas Gregor5352ac02010-01-28 00:27:43 +000018#include "CIndexDiagnostic.h"
Ted Kremenekab188932010-01-05 19:32:54 +000019
Ted Kremenek04bb7162010-01-22 22:44:15 +000020#include "clang/Basic/Version.h"
Douglas Gregor936ea3b2010-01-28 00:56:43 +000021
Steve Naroff50398192009-08-28 15:28:48 +000022#include "clang/AST/DeclVisitor.h"
Steve Narofffb570422009-09-22 19:25:29 +000023#include "clang/AST/StmtVisitor.h"
Douglas Gregor7d0d40e2010-01-21 16:28:34 +000024#include "clang/AST/TypeLocVisitor.h"
Benjamin Kramerb846deb2010-04-12 19:45:50 +000025#include "clang/Basic/Diagnostic.h"
26#include "clang/Frontend/ASTUnit.h"
27#include "clang/Frontend/CompilerInstance.h"
Douglas Gregor936ea3b2010-01-28 00:56:43 +000028#include "clang/Frontend/FrontendDiagnostic.h"
Ted Kremenekd8210652010-01-06 23:43:31 +000029#include "clang/Lex/Lexer.h"
Benjamin Kramerb846deb2010-04-12 19:45:50 +000030#include "clang/Lex/PreprocessingRecord.h"
Douglas Gregor33e9abd2010-01-22 19:49:59 +000031#include "clang/Lex/Preprocessor.h"
Douglas Gregor02465752009-10-16 21:24:31 +000032#include "llvm/Support/MemoryBuffer.h"
Benjamin Kramer0829a832009-10-18 11:19:36 +000033#include "llvm/System/Program.h"
Douglas Gregor0a812cf2010-02-18 23:07:20 +000034#include "llvm/System/Signals.h"
Ted Kremenekfc062212009-10-19 21:44:57 +000035
Benjamin Kramerc2a98162010-03-13 21:22:49 +000036// Needed to define L_TMPNAM on some systems.
37#include <cstdio>
38
Steve Naroff50398192009-08-28 15:28:48 +000039using namespace clang;
Ted Kremenek16c440a2010-01-15 20:35:54 +000040using namespace clang::cxcursor;
Ted Kremenekee4db4f2010-02-17 00:41:08 +000041using namespace clang::cxstring;
Steve Naroff50398192009-08-28 15:28:48 +000042
Ted Kremenek8a8da7d2010-01-06 03:42:32 +000043//===----------------------------------------------------------------------===//
44// Crash Reporting.
45//===----------------------------------------------------------------------===//
46
Ted Kremenekd7ffd082010-05-22 00:06:46 +000047#ifdef USE_CRASHTRACER
Ted Kremenek8a8da7d2010-01-06 03:42:32 +000048#include "clang/Analysis/Support/SaveAndRestore.h"
49// Integrate with crash reporter.
Daniel Dunbar439794e2010-05-20 23:50:23 +000050static const char *__crashreporter_info__ = 0;
51asm(".desc ___crashreporter_info__, 0x10");
Ted Kremenek6b569992010-02-17 21:12:23 +000052#define NUM_CRASH_STRINGS 32
Ted Kremenek29b72842010-01-07 22:49:05 +000053static unsigned crashtracer_counter = 0;
Ted Kremenek254ba7c2010-01-07 23:13:53 +000054static unsigned crashtracer_counter_id[NUM_CRASH_STRINGS] = { 0 };
Ted Kremenek29b72842010-01-07 22:49:05 +000055static const char *crashtracer_strings[NUM_CRASH_STRINGS] = { 0 };
56static const char *agg_crashtracer_strings[NUM_CRASH_STRINGS] = { 0 };
57
58static unsigned SetCrashTracerInfo(const char *str,
59 llvm::SmallString<1024> &AggStr) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +000060
Ted Kremenek254ba7c2010-01-07 23:13:53 +000061 unsigned slot = 0;
Ted Kremenek29b72842010-01-07 22:49:05 +000062 while (crashtracer_strings[slot]) {
63 if (++slot == NUM_CRASH_STRINGS)
64 slot = 0;
65 }
66 crashtracer_strings[slot] = str;
Ted Kremenek254ba7c2010-01-07 23:13:53 +000067 crashtracer_counter_id[slot] = ++crashtracer_counter;
Ted Kremenek29b72842010-01-07 22:49:05 +000068
69 // We need to create an aggregate string because multiple threads
70 // may be in this method at one time. The crash reporter string
71 // will attempt to overapproximate the set of in-flight invocations
72 // of this function. Race conditions can still cause this goal
73 // to not be achieved.
74 {
Ted Kremenekf0e23e82010-02-17 00:41:40 +000075 llvm::raw_svector_ostream Out(AggStr);
Ted Kremenek29b72842010-01-07 22:49:05 +000076 for (unsigned i = 0; i < NUM_CRASH_STRINGS; ++i)
77 if (crashtracer_strings[i]) Out << crashtracer_strings[i] << '\n';
78 }
79 __crashreporter_info__ = agg_crashtracer_strings[slot] = AggStr.c_str();
80 return slot;
81}
82
83static void ResetCrashTracerInfo(unsigned slot) {
Ted Kremenek254ba7c2010-01-07 23:13:53 +000084 unsigned max_slot = 0;
85 unsigned max_value = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +000086
Ted Kremenek254ba7c2010-01-07 23:13:53 +000087 crashtracer_strings[slot] = agg_crashtracer_strings[slot] = 0;
88
89 for (unsigned i = 0 ; i < NUM_CRASH_STRINGS; ++i)
90 if (agg_crashtracer_strings[i] &&
91 crashtracer_counter_id[i] > max_value) {
92 max_slot = i;
93 max_value = crashtracer_counter_id[i];
Ted Kremenek29b72842010-01-07 22:49:05 +000094 }
Ted Kremenek254ba7c2010-01-07 23:13:53 +000095
96 __crashreporter_info__ = agg_crashtracer_strings[max_slot];
Ted Kremenek29b72842010-01-07 22:49:05 +000097}
98
99namespace {
100class ArgsCrashTracerInfo {
101 llvm::SmallString<1024> CrashString;
102 llvm::SmallString<1024> AggregateString;
103 unsigned crashtracerSlot;
104public:
105 ArgsCrashTracerInfo(llvm::SmallVectorImpl<const char*> &Args)
106 : crashtracerSlot(0)
107 {
108 {
109 llvm::raw_svector_ostream Out(CrashString);
Ted Kremenek0baa9522010-03-05 22:43:25 +0000110 Out << "ClangCIndex [" << getClangFullVersion() << "]"
111 << "[createTranslationUnitFromSourceFile]: clang";
Ted Kremenek29b72842010-01-07 22:49:05 +0000112 for (llvm::SmallVectorImpl<const char*>::iterator I=Args.begin(),
113 E=Args.end(); I!=E; ++I)
114 Out << ' ' << *I;
115 }
116 crashtracerSlot = SetCrashTracerInfo(CrashString.c_str(),
117 AggregateString);
118 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000119
Ted Kremenek29b72842010-01-07 22:49:05 +0000120 ~ArgsCrashTracerInfo() {
121 ResetCrashTracerInfo(crashtracerSlot);
122 }
123};
124}
125#endif
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000126
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000127/// \brief The result of comparing two source ranges.
128enum RangeComparisonResult {
129 /// \brief Either the ranges overlap or one of the ranges is invalid.
130 RangeOverlap,
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000131
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000132 /// \brief The first range ends before the second range starts.
133 RangeBefore,
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000134
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000135 /// \brief The first range starts after the second range ends.
136 RangeAfter
137};
138
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000139/// \brief Compare two source ranges to determine their relative position in
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000140/// the translation unit.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000141static RangeComparisonResult RangeCompare(SourceManager &SM,
142 SourceRange R1,
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000143 SourceRange R2) {
144 assert(R1.isValid() && "First range is invalid?");
145 assert(R2.isValid() && "Second range is invalid?");
Daniel Dunbard52864b2010-02-14 10:02:57 +0000146 if (R1.getEnd() == R2.getBegin() ||
147 SM.isBeforeInTranslationUnit(R1.getEnd(), R2.getBegin()))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000148 return RangeBefore;
Daniel Dunbard52864b2010-02-14 10:02:57 +0000149 if (R2.getEnd() == R1.getBegin() ||
150 SM.isBeforeInTranslationUnit(R2.getEnd(), R1.getBegin()))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000151 return RangeAfter;
152 return RangeOverlap;
153}
154
Ted Kremenekfbd84ca2010-05-05 00:55:23 +0000155/// \brief Determine if a source location falls within, before, or after a
156/// a given source range.
157static RangeComparisonResult LocationCompare(SourceManager &SM,
158 SourceLocation L, SourceRange R) {
159 assert(R.isValid() && "First range is invalid?");
160 assert(L.isValid() && "Second range is invalid?");
161 if (L == R.getBegin())
162 return RangeOverlap;
163 if (L == R.getEnd())
164 return RangeAfter;
165 if (SM.isBeforeInTranslationUnit(L, R.getBegin()))
166 return RangeBefore;
167 if (SM.isBeforeInTranslationUnit(R.getEnd(), L))
168 return RangeAfter;
169 return RangeOverlap;
170}
171
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000172/// \brief Translate a Clang source range into a CIndex source range.
173///
174/// Clang internally represents ranges where the end location points to the
175/// start of the token at the end. However, for external clients it is more
176/// useful to have a CXSourceRange be a proper half-open interval. This routine
177/// does the appropriate translation.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000178CXSourceRange cxloc::translateSourceRange(const SourceManager &SM,
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000179 const LangOptions &LangOpts,
Chris Lattner0a76aae2010-06-18 22:45:06 +0000180 const CharSourceRange &R) {
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000181 // We want the last character in this location, so we will adjust the
Douglas Gregor6a5a23f2010-03-19 21:51:54 +0000182 // location accordingly.
183 // FIXME: How do do this with a macro instantiation location?
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000184 SourceLocation EndLoc = R.getEnd();
Chris Lattner0a76aae2010-06-18 22:45:06 +0000185 if (R.isTokenRange() && !EndLoc.isInvalid() && EndLoc.isFileID()) {
Douglas Gregor6a5a23f2010-03-19 21:51:54 +0000186 unsigned Length = Lexer::MeasureTokenLength(EndLoc, SM, LangOpts);
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000187 EndLoc = EndLoc.getFileLocWithOffset(Length);
188 }
189
190 CXSourceRange Result = { { (void *)&SM, (void *)&LangOpts },
191 R.getBegin().getRawEncoding(),
192 EndLoc.getRawEncoding() };
193 return Result;
194}
Douglas Gregor1db19de2010-01-19 21:36:55 +0000195
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000196//===----------------------------------------------------------------------===//
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000197// Cursor visitor.
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000198//===----------------------------------------------------------------------===//
199
Steve Naroff89922f82009-08-31 00:59:03 +0000200namespace {
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000201
Douglas Gregorb1373d02010-01-20 20:59:29 +0000202// Cursor visitor.
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000203class CursorVisitor : public DeclVisitor<CursorVisitor, bool>,
Douglas Gregora59e3902010-01-21 23:27:09 +0000204 public TypeLocVisitor<CursorVisitor, bool>,
205 public StmtVisitor<CursorVisitor, bool>
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000206{
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000207 /// \brief The translation unit we are traversing.
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000208 ASTUnit *TU;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000209
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000210 /// \brief The parent cursor whose children we are traversing.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000211 CXCursor Parent;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000212
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000213 /// \brief The declaration that serves at the parent of any statement or
214 /// expression nodes.
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000215 Decl *StmtParent;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000216
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000217 /// \brief The visitor function.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000218 CXCursorVisitor Visitor;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000219
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000220 /// \brief The opaque client data, to be passed along to the visitor.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000221 CXClientData ClientData;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000222
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000223 // MaxPCHLevel - the maximum PCH level of declarations that we will pass on
224 // to the visitor. Declarations with a PCH level greater than this value will
225 // be suppressed.
226 unsigned MaxPCHLevel;
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000227
228 /// \brief When valid, a source range to which the cursor should restrict
229 /// its search.
230 SourceRange RegionOfInterest;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000231
Douglas Gregorb1373d02010-01-20 20:59:29 +0000232 using DeclVisitor<CursorVisitor, bool>::Visit;
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000233 using TypeLocVisitor<CursorVisitor, bool>::Visit;
Douglas Gregora59e3902010-01-21 23:27:09 +0000234 using StmtVisitor<CursorVisitor, bool>::Visit;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000235
236 /// \brief Determine whether this particular source range comes before, comes
237 /// after, or overlaps the region of interest.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000238 ///
Daniel Dunbard52864b2010-02-14 10:02:57 +0000239 /// \param R a half-open source range retrieved from the abstract syntax tree.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000240 RangeComparisonResult CompareRegionOfInterest(SourceRange R);
241
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000242 class SetParentRAII {
243 CXCursor &Parent;
244 Decl *&StmtParent;
245 CXCursor OldParent;
246
247 public:
248 SetParentRAII(CXCursor &Parent, Decl *&StmtParent, CXCursor NewParent)
249 : Parent(Parent), StmtParent(StmtParent), OldParent(Parent)
250 {
251 Parent = NewParent;
252 if (clang_isDeclaration(Parent.kind))
253 StmtParent = getCursorDecl(Parent);
254 }
255
256 ~SetParentRAII() {
257 Parent = OldParent;
258 if (clang_isDeclaration(Parent.kind))
259 StmtParent = getCursorDecl(Parent);
260 }
261 };
262
Steve Naroff89922f82009-08-31 00:59:03 +0000263public:
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000264 CursorVisitor(ASTUnit *TU, CXCursorVisitor Visitor, CXClientData ClientData,
265 unsigned MaxPCHLevel,
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000266 SourceRange RegionOfInterest = SourceRange())
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000267 : TU(TU), Visitor(Visitor), ClientData(ClientData),
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000268 MaxPCHLevel(MaxPCHLevel), RegionOfInterest(RegionOfInterest)
Douglas Gregorb1373d02010-01-20 20:59:29 +0000269 {
270 Parent.kind = CXCursor_NoDeclFound;
271 Parent.data[0] = 0;
272 Parent.data[1] = 0;
273 Parent.data[2] = 0;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000274 StmtParent = 0;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000275 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000276
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000277 bool Visit(CXCursor Cursor, bool CheckedRegionOfInterest = false);
Douglas Gregor788f5a12010-03-20 00:41:21 +0000278
279 std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
280 getPreprocessedEntities();
281
Douglas Gregorb1373d02010-01-20 20:59:29 +0000282 bool VisitChildren(CXCursor Parent);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000283
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000284 // Declaration visitors
Ted Kremenek09dfa372010-02-18 05:46:33 +0000285 bool VisitAttributes(Decl *D);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000286 bool VisitBlockDecl(BlockDecl *B);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000287 bool VisitDeclContext(DeclContext *DC);
Ted Kremenek4540c9c2010-02-18 18:47:08 +0000288 bool VisitTranslationUnitDecl(TranslationUnitDecl *D);
289 bool VisitTypedefDecl(TypedefDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000290 bool VisitTagDecl(TagDecl *D);
291 bool VisitEnumConstantDecl(EnumConstantDecl *D);
292 bool VisitDeclaratorDecl(DeclaratorDecl *DD);
293 bool VisitFunctionDecl(FunctionDecl *ND);
294 bool VisitFieldDecl(FieldDecl *D);
Ted Kremenek4540c9c2010-02-18 18:47:08 +0000295 bool VisitVarDecl(VarDecl *);
Ted Kremenek79758f62010-02-18 22:36:18 +0000296 bool VisitObjCMethodDecl(ObjCMethodDecl *ND);
297 bool VisitObjCContainerDecl(ObjCContainerDecl *D);
298 bool VisitObjCCategoryDecl(ObjCCategoryDecl *ND);
299 bool VisitObjCProtocolDecl(ObjCProtocolDecl *PID);
Ted Kremenek23173d72010-05-18 21:09:07 +0000300 bool VisitObjCPropertyDecl(ObjCPropertyDecl *PD);
Ted Kremenek79758f62010-02-18 22:36:18 +0000301 bool VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
302 bool VisitObjCImplDecl(ObjCImplDecl *D);
303 bool VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
304 bool VisitObjCImplementationDecl(ObjCImplementationDecl *D);
305 // FIXME: ObjCPropertyDecl requires TypeSourceInfo, getter/setter locations,
306 // etc.
307 // FIXME: ObjCCompatibleAliasDecl requires aliased-class locations.
308 bool VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D);
309 bool VisitObjCClassDecl(ObjCClassDecl *D);
Ted Kremeneka0536d82010-05-07 01:04:29 +0000310 bool VisitLinkageSpecDecl(LinkageSpecDecl *D);
Ted Kremenek8f06e0e2010-05-06 23:38:21 +0000311 bool VisitNamespaceDecl(NamespaceDecl *D);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000312
313 // Type visitors
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000314 // FIXME: QualifiedTypeLoc doesn't provide any location information
315 bool VisitBuiltinTypeLoc(BuiltinTypeLoc TL);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000316 bool VisitTypedefTypeLoc(TypedefTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000317 bool VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL);
318 bool VisitTagTypeLoc(TagTypeLoc TL);
319 // FIXME: TemplateTypeParmTypeLoc doesn't provide any location information
320 bool VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL);
John McCallc12c5bb2010-05-15 11:32:37 +0000321 bool VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000322 bool VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL);
323 bool VisitPointerTypeLoc(PointerTypeLoc TL);
324 bool VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL);
325 bool VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL);
326 bool VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL);
327 bool VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL);
328 bool VisitFunctionTypeLoc(FunctionTypeLoc TL);
329 bool VisitArrayTypeLoc(ArrayTypeLoc TL);
Douglas Gregor2332c112010-01-21 20:48:56 +0000330 // FIXME: Implement for TemplateSpecializationTypeLoc
331 // FIXME: Implement visitors here when the unimplemented TypeLocs get
332 // implemented
333 bool VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL);
334 bool VisitTypeOfTypeLoc(TypeOfTypeLoc TL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000335
Douglas Gregora59e3902010-01-21 23:27:09 +0000336 // Statement visitors
337 bool VisitStmt(Stmt *S);
338 bool VisitDeclStmt(DeclStmt *S);
Douglas Gregorf5bab412010-01-22 01:00:11 +0000339 // FIXME: LabelStmt label?
340 bool VisitIfStmt(IfStmt *S);
341 bool VisitSwitchStmt(SwitchStmt *S);
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000342 bool VisitCaseStmt(CaseStmt *S);
Douglas Gregor263b47b2010-01-25 16:12:32 +0000343 bool VisitWhileStmt(WhileStmt *S);
344 bool VisitForStmt(ForStmt *S);
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000345// bool VisitSwitchCase(SwitchCase *S);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000346
Douglas Gregor336fd812010-01-23 00:40:08 +0000347 // Expression visitors
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000348 bool VisitBlockExpr(BlockExpr *B);
Douglas Gregor336fd812010-01-23 00:40:08 +0000349 bool VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000350 bool VisitExplicitCastExpr(ExplicitCastExpr *E);
Douglas Gregorc2350e52010-03-08 16:40:19 +0000351 bool VisitObjCMessageExpr(ObjCMessageExpr *E);
Douglas Gregor81d34662010-04-20 15:39:42 +0000352 bool VisitObjCEncodeExpr(ObjCEncodeExpr *E);
Douglas Gregor8ecdb652010-04-28 22:16:22 +0000353 bool VisitOffsetOfExpr(OffsetOfExpr *E);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000354 bool VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E);
Steve Naroff89922f82009-08-31 00:59:03 +0000355};
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000356
Ted Kremenekab188932010-01-05 19:32:54 +0000357} // end anonymous namespace
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000358
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000359RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000360 return RangeCompare(TU->getSourceManager(), R, RegionOfInterest);
361}
362
Douglas Gregorb1373d02010-01-20 20:59:29 +0000363/// \brief Visit the given cursor and, if requested by the visitor,
364/// its children.
365///
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000366/// \param Cursor the cursor to visit.
367///
368/// \param CheckRegionOfInterest if true, then the caller already checked that
369/// this cursor is within the region of interest.
370///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000371/// \returns true if the visitation should be aborted, false if it
372/// should continue.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000373bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
Douglas Gregorb1373d02010-01-20 20:59:29 +0000374 if (clang_isInvalid(Cursor.kind))
375 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000376
Douglas Gregorb1373d02010-01-20 20:59:29 +0000377 if (clang_isDeclaration(Cursor.kind)) {
378 Decl *D = getCursorDecl(Cursor);
379 assert(D && "Invalid declaration cursor");
380 if (D->getPCHLevel() > MaxPCHLevel)
381 return false;
382
383 if (D->isImplicit())
384 return false;
385 }
386
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000387 // If we have a range of interest, and this cursor doesn't intersect with it,
388 // we're done.
389 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
Daniel Dunbarf408f322010-02-14 08:32:05 +0000390 SourceRange Range =
391 cxloc::translateCXSourceRange(clang_getCursorExtent(Cursor));
392 if (Range.isInvalid() || CompareRegionOfInterest(Range))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000393 return false;
394 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000395
Douglas Gregorb1373d02010-01-20 20:59:29 +0000396 switch (Visitor(Cursor, Parent, ClientData)) {
397 case CXChildVisit_Break:
398 return true;
399
400 case CXChildVisit_Continue:
401 return false;
402
403 case CXChildVisit_Recurse:
404 return VisitChildren(Cursor);
405 }
406
Douglas Gregorfd643772010-01-25 16:45:46 +0000407 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000408}
409
Douglas Gregor788f5a12010-03-20 00:41:21 +0000410std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
411CursorVisitor::getPreprocessedEntities() {
412 PreprocessingRecord &PPRec
413 = *TU->getPreprocessor().getPreprocessingRecord();
414
415 bool OnlyLocalDecls
416 = !TU->isMainFileAST() && TU->getOnlyLocalDecls();
417
418 // There is no region of interest; we have to walk everything.
419 if (RegionOfInterest.isInvalid())
420 return std::make_pair(PPRec.begin(OnlyLocalDecls),
421 PPRec.end(OnlyLocalDecls));
422
423 // Find the file in which the region of interest lands.
424 SourceManager &SM = TU->getSourceManager();
425 std::pair<FileID, unsigned> Begin
426 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getBegin());
427 std::pair<FileID, unsigned> End
428 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getEnd());
429
430 // The region of interest spans files; we have to walk everything.
431 if (Begin.first != End.first)
432 return std::make_pair(PPRec.begin(OnlyLocalDecls),
433 PPRec.end(OnlyLocalDecls));
434
435 ASTUnit::PreprocessedEntitiesByFileMap &ByFileMap
436 = TU->getPreprocessedEntitiesByFile();
437 if (ByFileMap.empty()) {
438 // Build the mapping from files to sets of preprocessed entities.
439 for (PreprocessingRecord::iterator E = PPRec.begin(OnlyLocalDecls),
440 EEnd = PPRec.end(OnlyLocalDecls);
441 E != EEnd; ++E) {
442 std::pair<FileID, unsigned> P
443 = SM.getDecomposedInstantiationLoc((*E)->getSourceRange().getBegin());
444 ByFileMap[P.first].push_back(*E);
445 }
446 }
447
448 return std::make_pair(ByFileMap[Begin.first].begin(),
449 ByFileMap[Begin.first].end());
450}
451
Douglas Gregorb1373d02010-01-20 20:59:29 +0000452/// \brief Visit the children of the given cursor.
453///
454/// \returns true if the visitation should be aborted, false if it
455/// should continue.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000456bool CursorVisitor::VisitChildren(CXCursor Cursor) {
Douglas Gregora59e3902010-01-21 23:27:09 +0000457 if (clang_isReference(Cursor.kind)) {
458 // By definition, references have no children.
459 return false;
460 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000461
462 // Set the Parent field to Cursor, then back to its old value once we're
Douglas Gregorb1373d02010-01-20 20:59:29 +0000463 // done.
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000464 SetParentRAII SetParent(Parent, StmtParent, Cursor);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000465
Douglas Gregorb1373d02010-01-20 20:59:29 +0000466 if (clang_isDeclaration(Cursor.kind)) {
467 Decl *D = getCursorDecl(Cursor);
468 assert(D && "Invalid declaration cursor");
Ted Kremenek539311e2010-02-18 18:47:01 +0000469 return VisitAttributes(D) || Visit(D);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000470 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000471
Douglas Gregora59e3902010-01-21 23:27:09 +0000472 if (clang_isStatement(Cursor.kind))
473 return Visit(getCursorStmt(Cursor));
474 if (clang_isExpression(Cursor.kind))
475 return Visit(getCursorExpr(Cursor));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000476
Douglas Gregorb1373d02010-01-20 20:59:29 +0000477 if (clang_isTranslationUnit(Cursor.kind)) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000478 ASTUnit *CXXUnit = getCursorASTUnit(Cursor);
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000479 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
480 RegionOfInterest.isInvalid()) {
Douglas Gregor7b691f332010-01-20 21:13:59 +0000481 const std::vector<Decl*> &TLDs = CXXUnit->getTopLevelDecls();
482 for (std::vector<Decl*>::const_iterator it = TLDs.begin(),
483 ie = TLDs.end(); it != ie; ++it) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000484 if (Visit(MakeCXCursor(*it, CXXUnit), true))
Douglas Gregor7b691f332010-01-20 21:13:59 +0000485 return true;
486 }
Douglas Gregor0396f462010-03-19 05:22:59 +0000487 } else if (VisitDeclContext(
488 CXXUnit->getASTContext().getTranslationUnitDecl()))
489 return true;
Bob Wilson3178cb62010-03-19 03:57:57 +0000490
Douglas Gregor0396f462010-03-19 05:22:59 +0000491 // Walk the preprocessing record.
Daniel Dunbar8de30ff2010-03-20 01:11:56 +0000492 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000493 // FIXME: Once we have the ability to deserialize a preprocessing record,
494 // do so.
Douglas Gregor788f5a12010-03-20 00:41:21 +0000495 PreprocessingRecord::iterator E, EEnd;
496 for (llvm::tie(E, EEnd) = getPreprocessedEntities(); E != EEnd; ++E) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000497 if (MacroInstantiation *MI = dyn_cast<MacroInstantiation>(*E)) {
498 if (Visit(MakeMacroInstantiationCursor(MI, CXXUnit)))
499 return true;
Douglas Gregor788f5a12010-03-20 00:41:21 +0000500
Douglas Gregor0396f462010-03-19 05:22:59 +0000501 continue;
502 }
503
504 if (MacroDefinition *MD = dyn_cast<MacroDefinition>(*E)) {
505 if (Visit(MakeMacroDefinitionCursor(MD, CXXUnit)))
506 return true;
507
508 continue;
509 }
510 }
511 }
Douglas Gregor7b691f332010-01-20 21:13:59 +0000512 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000513 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000514
Douglas Gregorb1373d02010-01-20 20:59:29 +0000515 // Nothing to visit at the moment.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000516 return false;
517}
518
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000519bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
John McCallfc929202010-06-04 22:33:30 +0000520 if (Visit(B->getSignatureAsWritten()->getTypeLoc()))
521 return true;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000522
Ted Kremenek664cffd2010-07-22 11:30:19 +0000523 if (Stmt *Body = B->getBody())
524 return Visit(MakeCXCursor(Body, StmtParent, TU));
525
526 return false;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000527}
528
Douglas Gregorb1373d02010-01-20 20:59:29 +0000529bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000530 for (DeclContext::decl_iterator
Douglas Gregorb1373d02010-01-20 20:59:29 +0000531 I = DC->decls_begin(), E = DC->decls_end(); I != E; ++I) {
Ted Kremenek09dfa372010-02-18 05:46:33 +0000532
Ted Kremenek23173d72010-05-18 21:09:07 +0000533 Decl *D = *I;
534 if (D->getLexicalDeclContext() != DC)
535 continue;
536
537 CXCursor Cursor = MakeCXCursor(D, TU);
Daniel Dunbard52864b2010-02-14 10:02:57 +0000538
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000539 if (RegionOfInterest.isValid()) {
Daniel Dunbard52864b2010-02-14 10:02:57 +0000540 SourceRange Range =
541 cxloc::translateCXSourceRange(clang_getCursorExtent(Cursor));
542 if (Range.isInvalid())
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000543 continue;
Daniel Dunbard52864b2010-02-14 10:02:57 +0000544
545 switch (CompareRegionOfInterest(Range)) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000546 case RangeBefore:
547 // This declaration comes before the region of interest; skip it.
548 continue;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000549
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000550 case RangeAfter:
551 // This declaration comes after the region of interest; we're done.
552 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000553
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000554 case RangeOverlap:
555 // This declaration overlaps the region of interest; visit it.
556 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000557 }
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000558 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000559
Daniel Dunbard52864b2010-02-14 10:02:57 +0000560 if (Visit(Cursor, true))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000561 return true;
562 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000563
Douglas Gregorb1373d02010-01-20 20:59:29 +0000564 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000565}
566
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000567bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
568 llvm_unreachable("Translation units are visited directly by Visit()");
569 return false;
570}
571
572bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
573 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
574 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000575
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000576 return false;
577}
578
579bool CursorVisitor::VisitTagDecl(TagDecl *D) {
580 return VisitDeclContext(D);
581}
582
583bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
584 if (Expr *Init = D->getInitExpr())
585 return Visit(MakeCXCursor(Init, StmtParent, TU));
586 return false;
587}
588
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000589bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
590 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
591 if (Visit(TSInfo->getTypeLoc()))
592 return true;
593
594 return false;
595}
596
Douglas Gregorb1373d02010-01-20 20:59:29 +0000597bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000598 if (VisitDeclaratorDecl(ND))
599 return true;
600
Douglas Gregora59e3902010-01-21 23:27:09 +0000601 if (ND->isThisDeclarationADefinition() &&
602 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
603 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000604
Douglas Gregorb1373d02010-01-20 20:59:29 +0000605 return false;
606}
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000607
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000608bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
609 if (VisitDeclaratorDecl(D))
610 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000611
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000612 if (Expr *BitWidth = D->getBitWidth())
613 return Visit(MakeCXCursor(BitWidth, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000614
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000615 return false;
616}
617
618bool CursorVisitor::VisitVarDecl(VarDecl *D) {
619 if (VisitDeclaratorDecl(D))
620 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000621
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000622 if (Expr *Init = D->getInit())
623 return Visit(MakeCXCursor(Init, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000624
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000625 return false;
626}
627
628bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
Douglas Gregor4bc1cb62010-03-08 14:59:44 +0000629 if (TypeSourceInfo *TSInfo = ND->getResultTypeSourceInfo())
630 if (Visit(TSInfo->getTypeLoc()))
631 return true;
632
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000633 for (ObjCMethodDecl::param_iterator P = ND->param_begin(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000634 PEnd = ND->param_end();
635 P != PEnd; ++P) {
636 if (Visit(MakeCXCursor(*P, TU)))
637 return true;
638 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000639
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000640 if (ND->isThisDeclarationADefinition() &&
641 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
642 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000643
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000644 return false;
645}
646
Douglas Gregora59e3902010-01-21 23:27:09 +0000647bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
648 return VisitDeclContext(D);
649}
650
Douglas Gregorb1373d02010-01-20 20:59:29 +0000651bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000652 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
653 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000654 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000655
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000656 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
657 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
658 E = ND->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000659 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000660 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000661
Douglas Gregora59e3902010-01-21 23:27:09 +0000662 return VisitObjCContainerDecl(ND);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000663}
664
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000665bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
666 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
667 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
668 E = PID->protocol_end(); I != E; ++I, ++PL)
669 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
670 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000671
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000672 return VisitObjCContainerDecl(PID);
673}
674
Ted Kremenek23173d72010-05-18 21:09:07 +0000675bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
John McCallfc929202010-06-04 22:33:30 +0000676 if (Visit(PD->getTypeSourceInfo()->getTypeLoc()))
677 return true;
678
Ted Kremenek23173d72010-05-18 21:09:07 +0000679 // FIXME: This implements a workaround with @property declarations also being
680 // installed in the DeclContext for the @interface. Eventually this code
681 // should be removed.
682 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
683 if (!CDecl || !CDecl->IsClassExtension())
684 return false;
685
686 ObjCInterfaceDecl *ID = CDecl->getClassInterface();
687 if (!ID)
688 return false;
689
690 IdentifierInfo *PropertyId = PD->getIdentifier();
691 ObjCPropertyDecl *prevDecl =
692 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId);
693
694 if (!prevDecl)
695 return false;
696
697 // Visit synthesized methods since they will be skipped when visiting
698 // the @interface.
699 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
700 if (MD->isSynthesized())
701 if (Visit(MakeCXCursor(MD, TU)))
702 return true;
703
704 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
705 if (MD->isSynthesized())
706 if (Visit(MakeCXCursor(MD, TU)))
707 return true;
708
709 return false;
710}
711
Douglas Gregorb1373d02010-01-20 20:59:29 +0000712bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000713 // Issue callbacks for super class.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000714 if (D->getSuperClass() &&
715 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000716 D->getSuperClassLoc(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000717 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000718 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000719
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000720 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
721 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
722 E = D->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000723 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000724 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000725
Douglas Gregora59e3902010-01-21 23:27:09 +0000726 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000727}
728
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000729bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
730 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000731}
732
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000733bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
Ted Kremenekebfa3392010-03-19 20:39:03 +0000734 // 'ID' could be null when dealing with invalid code.
735 if (ObjCInterfaceDecl *ID = D->getClassInterface())
736 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
737 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000738
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000739 return VisitObjCImplDecl(D);
740}
741
742bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
743#if 0
744 // Issue callbacks for super class.
745 // FIXME: No source location information!
746 if (D->getSuperClass() &&
747 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000748 D->getSuperClassLoc(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000749 TU)))
750 return true;
751#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000752
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000753 return VisitObjCImplDecl(D);
754}
755
756bool CursorVisitor::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D) {
757 ObjCForwardProtocolDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
758 for (ObjCForwardProtocolDecl::protocol_iterator I = D->protocol_begin(),
759 E = D->protocol_end();
760 I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000761 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000762 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000763
764 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000765}
766
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000767bool CursorVisitor::VisitObjCClassDecl(ObjCClassDecl *D) {
768 for (ObjCClassDecl::iterator C = D->begin(), CEnd = D->end(); C != CEnd; ++C)
769 if (Visit(MakeCursorObjCClassRef(C->getInterface(), C->getLocation(), TU)))
770 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000771
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000772 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000773}
774
Ted Kremenek8f06e0e2010-05-06 23:38:21 +0000775bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
776 return VisitDeclContext(D);
777}
778
Ted Kremeneka0536d82010-05-07 01:04:29 +0000779bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
780 return VisitDeclContext(D);
781}
782
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000783bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
784 ASTContext &Context = TU->getASTContext();
785
786 // Some builtin types (such as Objective-C's "id", "sel", and
787 // "Class") have associated declarations. Create cursors for those.
788 QualType VisitType;
789 switch (TL.getType()->getAs<BuiltinType>()->getKind()) {
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000790 case BuiltinType::Void:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000791 case BuiltinType::Bool:
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000792 case BuiltinType::Char_U:
793 case BuiltinType::UChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000794 case BuiltinType::Char16:
795 case BuiltinType::Char32:
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000796 case BuiltinType::UShort:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000797 case BuiltinType::UInt:
798 case BuiltinType::ULong:
799 case BuiltinType::ULongLong:
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000800 case BuiltinType::UInt128:
801 case BuiltinType::Char_S:
802 case BuiltinType::SChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000803 case BuiltinType::WChar:
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000804 case BuiltinType::Short:
805 case BuiltinType::Int:
806 case BuiltinType::Long:
807 case BuiltinType::LongLong:
808 case BuiltinType::Int128:
809 case BuiltinType::Float:
810 case BuiltinType::Double:
811 case BuiltinType::LongDouble:
812 case BuiltinType::NullPtr:
813 case BuiltinType::Overload:
814 case BuiltinType::Dependent:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000815 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000816
817 case BuiltinType::UndeducedAuto: // FIXME: Deserves a cursor?
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000818 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000819
Ted Kremenekc4174cc2010-02-18 18:52:18 +0000820 case BuiltinType::ObjCId:
821 VisitType = Context.getObjCIdType();
822 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000823
824 case BuiltinType::ObjCClass:
825 VisitType = Context.getObjCClassType();
826 break;
827
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000828 case BuiltinType::ObjCSel:
829 VisitType = Context.getObjCSelType();
830 break;
831 }
832
833 if (!VisitType.isNull()) {
834 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000835 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000836 TU));
837 }
838
839 return false;
840}
841
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000842bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
843 return Visit(MakeCursorTypeRef(TL.getTypedefDecl(), TL.getNameLoc(), TU));
844}
845
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000846bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
847 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
848}
849
850bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
851 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
852}
853
854bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
855 if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
856 return true;
857
John McCallc12c5bb2010-05-15 11:32:37 +0000858 return false;
859}
860
861bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
862 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
863 return true;
864
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000865 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
866 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
867 TU)))
868 return true;
869 }
870
871 return false;
872}
873
874bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
John McCallc12c5bb2010-05-15 11:32:37 +0000875 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000876}
877
878bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
879 return Visit(TL.getPointeeLoc());
880}
881
882bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
883 return Visit(TL.getPointeeLoc());
884}
885
886bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
887 return Visit(TL.getPointeeLoc());
888}
889
890bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000891 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000892}
893
894bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000895 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000896}
897
898bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
899 if (Visit(TL.getResultLoc()))
900 return true;
901
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000902 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
Ted Kremenek5dbacb42010-04-07 00:27:13 +0000903 if (Decl *D = TL.getArg(I))
904 if (Visit(MakeCXCursor(D, TU)))
905 return true;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000906
907 return false;
908}
909
910bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
911 if (Visit(TL.getElementLoc()))
912 return true;
913
914 if (Expr *Size = TL.getSizeExpr())
915 return Visit(MakeCXCursor(Size, StmtParent, TU));
916
917 return false;
918}
919
Douglas Gregor2332c112010-01-21 20:48:56 +0000920bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
921 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
922}
923
924bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
925 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
926 return Visit(TSInfo->getTypeLoc());
927
928 return false;
929}
930
Douglas Gregora59e3902010-01-21 23:27:09 +0000931bool CursorVisitor::VisitStmt(Stmt *S) {
932 for (Stmt::child_iterator Child = S->child_begin(), ChildEnd = S->child_end();
933 Child != ChildEnd; ++Child) {
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000934 if (Stmt *C = *Child)
935 if (Visit(MakeCXCursor(C, StmtParent, TU)))
936 return true;
Douglas Gregora59e3902010-01-21 23:27:09 +0000937 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000938
Douglas Gregora59e3902010-01-21 23:27:09 +0000939 return false;
940}
941
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000942bool CursorVisitor::VisitCaseStmt(CaseStmt *S) {
943 // Specially handle CaseStmts because they can be nested, e.g.:
944 //
945 // case 1:
946 // case 2:
947 //
948 // In this case the second CaseStmt is the child of the first. Walking
949 // these recursively can blow out the stack.
950 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU);
951 while (true) {
952 // Set the Parent field to Cursor, then back to its old value once we're
953 // done.
954 SetParentRAII SetParent(Parent, StmtParent, Cursor);
955
956 if (Stmt *LHS = S->getLHS())
957 if (Visit(MakeCXCursor(LHS, StmtParent, TU)))
958 return true;
959 if (Stmt *RHS = S->getRHS())
960 if (Visit(MakeCXCursor(RHS, StmtParent, TU)))
961 return true;
962 if (Stmt *SubStmt = S->getSubStmt()) {
963 if (!isa<CaseStmt>(SubStmt))
964 return Visit(MakeCXCursor(SubStmt, StmtParent, TU));
965
966 // Specially handle 'CaseStmt' so that we don't blow out the stack.
967 CaseStmt *CS = cast<CaseStmt>(SubStmt);
968 Cursor = MakeCXCursor(CS, StmtParent, TU);
969 if (RegionOfInterest.isValid()) {
970 SourceRange Range = CS->getSourceRange();
971 if (Range.isInvalid() || CompareRegionOfInterest(Range))
972 return false;
973 }
974
975 switch (Visitor(Cursor, Parent, ClientData)) {
976 case CXChildVisit_Break: return true;
977 case CXChildVisit_Continue: return false;
978 case CXChildVisit_Recurse:
979 // Perform tail-recursion manually.
980 S = CS;
981 continue;
982 }
983 }
984 return false;
985 }
986}
987
Douglas Gregora59e3902010-01-21 23:27:09 +0000988bool CursorVisitor::VisitDeclStmt(DeclStmt *S) {
989 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
990 D != DEnd; ++D) {
Douglas Gregor263b47b2010-01-25 16:12:32 +0000991 if (*D && Visit(MakeCXCursor(*D, TU)))
Douglas Gregora59e3902010-01-21 23:27:09 +0000992 return true;
993 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000994
Douglas Gregora59e3902010-01-21 23:27:09 +0000995 return false;
996}
997
Douglas Gregorf5bab412010-01-22 01:00:11 +0000998bool CursorVisitor::VisitIfStmt(IfStmt *S) {
999 if (VarDecl *Var = S->getConditionVariable()) {
1000 if (Visit(MakeCXCursor(Var, TU)))
1001 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001002 }
1003
Douglas Gregor263b47b2010-01-25 16:12:32 +00001004 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1005 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +00001006 if (S->getThen() && Visit(MakeCXCursor(S->getThen(), StmtParent, TU)))
1007 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +00001008 if (S->getElse() && Visit(MakeCXCursor(S->getElse(), StmtParent, TU)))
1009 return true;
1010
1011 return false;
1012}
1013
1014bool CursorVisitor::VisitSwitchStmt(SwitchStmt *S) {
1015 if (VarDecl *Var = S->getConditionVariable()) {
1016 if (Visit(MakeCXCursor(Var, TU)))
1017 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001018 }
1019
Douglas Gregor263b47b2010-01-25 16:12:32 +00001020 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1021 return true;
1022 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
1023 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001024
Douglas Gregor263b47b2010-01-25 16:12:32 +00001025 return false;
1026}
1027
1028bool CursorVisitor::VisitWhileStmt(WhileStmt *S) {
1029 if (VarDecl *Var = S->getConditionVariable()) {
1030 if (Visit(MakeCXCursor(Var, TU)))
1031 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001032 }
1033
Douglas Gregor263b47b2010-01-25 16:12:32 +00001034 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1035 return true;
1036 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
Douglas Gregorf5bab412010-01-22 01:00:11 +00001037 return true;
1038
Douglas Gregor263b47b2010-01-25 16:12:32 +00001039 return false;
1040}
1041
1042bool CursorVisitor::VisitForStmt(ForStmt *S) {
1043 if (S->getInit() && Visit(MakeCXCursor(S->getInit(), StmtParent, TU)))
1044 return true;
1045 if (VarDecl *Var = S->getConditionVariable()) {
1046 if (Visit(MakeCXCursor(Var, TU)))
1047 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001048 }
1049
Douglas Gregor263b47b2010-01-25 16:12:32 +00001050 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1051 return true;
1052 if (S->getInc() && Visit(MakeCXCursor(S->getInc(), StmtParent, TU)))
1053 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +00001054 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
1055 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001056
Douglas Gregorf5bab412010-01-22 01:00:11 +00001057 return false;
1058}
1059
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00001060bool CursorVisitor::VisitBlockExpr(BlockExpr *B) {
1061 return Visit(B->getBlockDecl());
1062}
1063
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001064bool CursorVisitor::VisitOffsetOfExpr(OffsetOfExpr *E) {
1065 // FIXME: Visit fields as well?
1066 if (Visit(E->getTypeSourceInfo()->getTypeLoc()))
1067 return true;
1068
1069 return VisitExpr(E);
1070}
1071
Douglas Gregor336fd812010-01-23 00:40:08 +00001072bool CursorVisitor::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E) {
1073 if (E->isArgumentType()) {
1074 if (TypeSourceInfo *TSInfo = E->getArgumentTypeInfo())
1075 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001076
Douglas Gregor336fd812010-01-23 00:40:08 +00001077 return false;
1078 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001079
Douglas Gregor336fd812010-01-23 00:40:08 +00001080 return VisitExpr(E);
1081}
1082
1083bool CursorVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
1084 if (TypeSourceInfo *TSInfo = E->getTypeInfoAsWritten())
1085 if (Visit(TSInfo->getTypeLoc()))
1086 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001087
Douglas Gregor336fd812010-01-23 00:40:08 +00001088 return VisitCastExpr(E);
1089}
1090
1091bool CursorVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
1092 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
1093 if (Visit(TSInfo->getTypeLoc()))
1094 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001095
Douglas Gregor336fd812010-01-23 00:40:08 +00001096 return VisitExpr(E);
1097}
1098
Douglas Gregorc2350e52010-03-08 16:40:19 +00001099bool CursorVisitor::VisitObjCMessageExpr(ObjCMessageExpr *E) {
Douglas Gregor04badcf2010-04-21 00:45:42 +00001100 if (TypeSourceInfo *TSInfo = E->getClassReceiverTypeInfo())
1101 if (Visit(TSInfo->getTypeLoc()))
1102 return true;
Douglas Gregorc2350e52010-03-08 16:40:19 +00001103
1104 return VisitExpr(E);
1105}
1106
Douglas Gregor81d34662010-04-20 15:39:42 +00001107bool CursorVisitor::VisitObjCEncodeExpr(ObjCEncodeExpr *E) {
1108 return Visit(E->getEncodedTypeSourceInfo()->getTypeLoc());
1109}
1110
1111
Ted Kremenek09dfa372010-02-18 05:46:33 +00001112bool CursorVisitor::VisitAttributes(Decl *D) {
1113 for (const Attr *A = D->getAttrs(); A; A = A->getNext())
1114 if (Visit(MakeCXCursor(A, D, TU)))
1115 return true;
1116
1117 return false;
1118}
1119
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00001120extern "C" {
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001121CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
1122 int displayDiagnostics) {
Douglas Gregora030b7c2010-01-22 20:35:53 +00001123 CIndexer *CIdxr = new CIndexer();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001124 if (excludeDeclarationsFromPCH)
1125 CIdxr->setOnlyLocalDecls();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001126 if (displayDiagnostics)
1127 CIdxr->setDisplayDiagnostics();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001128 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +00001129}
1130
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001131void clang_disposeIndex(CXIndex CIdx) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001132 if (CIdx)
1133 delete static_cast<CIndexer *>(CIdx);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00001134}
1135
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001136void clang_setUseExternalASTGeneration(CXIndex CIdx, int value) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001137 if (CIdx) {
1138 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
1139 CXXIdx->setUseExternalASTGeneration(value);
1140 }
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001141}
1142
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001143CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
Douglas Gregora88084b2010-02-18 18:08:43 +00001144 const char *ast_filename) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001145 if (!CIdx)
1146 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001147
Douglas Gregor7d1d49d2009-10-16 20:01:17 +00001148 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001149
Douglas Gregor28019772010-04-05 23:52:57 +00001150 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
1151 return ASTUnit::LoadFromPCHFile(ast_filename, Diags,
Douglas Gregora88084b2010-02-18 18:08:43 +00001152 CXXIdx->getOnlyLocalDecls(),
1153 0, 0, true);
Steve Naroff600866c2009-08-27 19:51:58 +00001154}
1155
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001156CXTranslationUnit
1157clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
1158 const char *source_filename,
1159 int num_command_line_args,
Douglas Gregor4db64a42010-01-23 00:14:00 +00001160 const char **command_line_args,
1161 unsigned num_unsaved_files,
Douglas Gregora88084b2010-02-18 18:08:43 +00001162 struct CXUnsavedFile *unsaved_files) {
Douglas Gregor5a430212010-07-21 18:52:53 +00001163 return clang_parseTranslationUnit(CIdx, source_filename,
1164 command_line_args, num_command_line_args,
1165 unsaved_files, num_unsaved_files,
1166 CXTranslationUnit_DetailedPreprocessingRecord);
1167}
1168
1169CXTranslationUnit clang_parseTranslationUnit(CXIndex CIdx,
1170 const char *source_filename,
1171 const char **command_line_args,
1172 int num_command_line_args,
1173 struct CXUnsavedFile *unsaved_files,
1174 unsigned num_unsaved_files,
1175 unsigned options) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001176 if (!CIdx)
1177 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001178
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001179 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
1180
Douglas Gregor5352ac02010-01-28 00:27:43 +00001181 // Configure the diagnostics.
1182 DiagnosticOptions DiagOpts;
Douglas Gregor28019772010-04-05 23:52:57 +00001183 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
1184 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001185
Douglas Gregor4db64a42010-01-23 00:14:00 +00001186 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
1187 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattnera0a270c2010-04-05 22:42:27 +00001188 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001189 const llvm::MemoryBuffer *Buffer
Chris Lattnera0a270c2010-04-05 22:42:27 +00001190 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregor4db64a42010-01-23 00:14:00 +00001191 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
1192 Buffer));
1193 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001194
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001195 if (!CXXIdx->getUseExternalASTGeneration()) {
1196 llvm::SmallVector<const char *, 16> Args;
1197
1198 // The 'source_filename' argument is optional. If the caller does not
1199 // specify it then it is assumed that the source file is specified
1200 // in the actual argument list.
1201 if (source_filename)
1202 Args.push_back(source_filename);
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00001203
1204 // Since the Clang C library is primarily used by batch tools dealing with
1205 // (often very broken) source code, where spell-checking can have a
1206 // significant negative impact on performance (particularly when
1207 // precompiled headers are involved), we disable it by default.
1208 // Note that we place this argument early in the list, so that it can be
1209 // overridden by the caller with "-fspell-checking".
Douglas Gregora0068fc2010-07-09 17:35:33 +00001210 Args.push_back("-fno-spell-checking");
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00001211
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001212 Args.insert(Args.end(), command_line_args,
1213 command_line_args + num_command_line_args);
Douglas Gregor5a430212010-07-21 18:52:53 +00001214
1215 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
1216 Args.push_back("-Xclang");
1217 Args.push_back("-detailed-preprocessing-record");
1218 }
Douglas Gregor5352ac02010-01-28 00:27:43 +00001219 unsigned NumErrors = Diags->getNumErrors();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001220
Ted Kremenek29b72842010-01-07 22:49:05 +00001221#ifdef USE_CRASHTRACER
1222 ArgsCrashTracerInfo ACTI(Args);
Ted Kremenek8a8da7d2010-01-06 03:42:32 +00001223#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001224
Daniel Dunbar94220972009-12-05 02:17:18 +00001225 llvm::OwningPtr<ASTUnit> Unit(
1226 ASTUnit::LoadFromCommandLine(Args.data(), Args.data() + Args.size(),
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001227 Diags,
Daniel Dunbar869824e2009-12-13 03:46:13 +00001228 CXXIdx->getClangResourcesPath(),
Daniel Dunbar94220972009-12-05 02:17:18 +00001229 CXXIdx->getOnlyLocalDecls(),
Douglas Gregor4db64a42010-01-23 00:14:00 +00001230 RemappedFiles.data(),
Douglas Gregora88084b2010-02-18 18:08:43 +00001231 RemappedFiles.size(),
Douglas Gregor94dc8f62010-03-19 16:15:56 +00001232 /*CaptureDiagnostics=*/true));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001233
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001234 if (NumErrors != Diags->getNumErrors()) {
Ted Kremenek34f6a322010-03-05 22:43:29 +00001235 // Make sure to check that 'Unit' is non-NULL.
1236 if (CXXIdx->getDisplayDiagnostics() && Unit.get()) {
Douglas Gregor405634b2010-04-05 18:10:21 +00001237 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
1238 DEnd = Unit->stored_diag_end();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001239 D != DEnd; ++D) {
1240 CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOptions());
Douglas Gregor274f1902010-02-22 23:17:23 +00001241 CXString Msg = clang_formatDiagnostic(&Diag,
1242 clang_defaultDiagnosticDisplayOptions());
1243 fprintf(stderr, "%s\n", clang_getCString(Msg));
1244 clang_disposeString(Msg);
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001245 }
Douglas Gregor274f1902010-02-22 23:17:23 +00001246#ifdef LLVM_ON_WIN32
1247 // On Windows, force a flush, since there may be multiple copies of
1248 // stderr and stdout in the file system, all with different buffers
1249 // but writing to the same device.
1250 fflush(stderr);
Ted Kremenek83c51842010-03-26 01:34:51 +00001251#endif
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001252 }
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001253 }
Daniel Dunbar94220972009-12-05 02:17:18 +00001254
1255 return Unit.take();
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001256 }
1257
Ted Kremenek139ba862009-10-22 00:03:57 +00001258 // Build up the arguments for invoking 'clang'.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001259 std::vector<const char *> argv;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001260
Ted Kremenek139ba862009-10-22 00:03:57 +00001261 // First add the complete path to the 'clang' executable.
1262 llvm::sys::Path ClangPath = static_cast<CIndexer *>(CIdx)->getClangPath();
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00001263 argv.push_back(ClangPath.c_str());
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001264
Ted Kremenek139ba862009-10-22 00:03:57 +00001265 // Add the '-emit-ast' option as our execution mode for 'clang'.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001266 argv.push_back("-emit-ast");
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001267
Ted Kremenek139ba862009-10-22 00:03:57 +00001268 // The 'source_filename' argument is optional. If the caller does not
1269 // specify it then it is assumed that the source file is specified
1270 // in the actual argument list.
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001271 if (source_filename)
1272 argv.push_back(source_filename);
Ted Kremenek139ba862009-10-22 00:03:57 +00001273
Steve Naroff37b5ac22009-10-15 20:50:09 +00001274 // Generate a temporary name for the AST file.
Ted Kremenek139ba862009-10-22 00:03:57 +00001275 argv.push_back("-o");
Benjamin Kramerc2a98162010-03-13 21:22:49 +00001276 char astTmpFile[L_tmpnam];
1277 argv.push_back(tmpnam(astTmpFile));
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00001278
1279 // Since the Clang C library is primarily used by batch tools dealing with
1280 // (often very broken) source code, where spell-checking can have a
1281 // significant negative impact on performance (particularly when
1282 // precompiled headers are involved), we disable it by default.
1283 // Note that we place this argument early in the list, so that it can be
1284 // overridden by the caller with "-fspell-checking".
Douglas Gregora0068fc2010-07-09 17:35:33 +00001285 argv.push_back("-fno-spell-checking");
Ted Kremenek139ba862009-10-22 00:03:57 +00001286
Douglas Gregor4db64a42010-01-23 00:14:00 +00001287 // Remap any unsaved files to temporary files.
1288 std::vector<llvm::sys::Path> TemporaryFiles;
1289 std::vector<std::string> RemapArgs;
1290 if (RemapFiles(num_unsaved_files, unsaved_files, RemapArgs, TemporaryFiles))
1291 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001292
Douglas Gregor4db64a42010-01-23 00:14:00 +00001293 // The pointers into the elements of RemapArgs are stable because we
1294 // won't be adding anything to RemapArgs after this point.
1295 for (unsigned i = 0, e = RemapArgs.size(); i != e; ++i)
1296 argv.push_back(RemapArgs[i].c_str());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001297
Ted Kremenek139ba862009-10-22 00:03:57 +00001298 // Process the compiler options, stripping off '-o', '-c', '-fsyntax-only'.
1299 for (int i = 0; i < num_command_line_args; ++i)
1300 if (const char *arg = command_line_args[i]) {
1301 if (strcmp(arg, "-o") == 0) {
1302 ++i; // Also skip the matching argument.
1303 continue;
1304 }
1305 if (strcmp(arg, "-emit-ast") == 0 ||
1306 strcmp(arg, "-c") == 0 ||
1307 strcmp(arg, "-fsyntax-only") == 0) {
1308 continue;
1309 }
1310
1311 // Keep the argument.
1312 argv.push_back(arg);
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001313 }
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001314
Douglas Gregord93256e2010-01-28 06:00:51 +00001315 // Generate a temporary name for the diagnostics file.
Benjamin Kramerc2a98162010-03-13 21:22:49 +00001316 char tmpFileResults[L_tmpnam];
1317 char *tmpResultsFileName = tmpnam(tmpFileResults);
1318 llvm::sys::Path DiagnosticsFile(tmpResultsFileName);
Douglas Gregord93256e2010-01-28 06:00:51 +00001319 TemporaryFiles.push_back(DiagnosticsFile);
1320 argv.push_back("-fdiagnostics-binary");
1321
Douglas Gregor94dc8f62010-03-19 16:15:56 +00001322 argv.push_back("-Xclang");
1323 argv.push_back("-detailed-preprocessing-record");
1324
Ted Kremenek139ba862009-10-22 00:03:57 +00001325 // Add the null terminator.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001326 argv.push_back(NULL);
1327
Ted Kremenekfeb15e32009-10-26 22:14:08 +00001328 // Invoke 'clang'.
1329 llvm::sys::Path DevNull; // leave empty, causes redirection to /dev/null
1330 // on Unix or NUL (Windows).
Ted Kremenek379afec2009-10-22 03:24:01 +00001331 std::string ErrMsg;
Douglas Gregord93256e2010-01-28 06:00:51 +00001332 const llvm::sys::Path *Redirects[] = { &DevNull, &DevNull, &DiagnosticsFile,
1333 NULL };
Ted Kremenek379afec2009-10-22 03:24:01 +00001334 llvm::sys::Program::ExecuteAndWait(ClangPath, &argv[0], /* env */ NULL,
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001335 /* redirects */ &Redirects[0],
Ted Kremenek379afec2009-10-22 03:24:01 +00001336 /* secondsToWait */ 0, /* memoryLimits */ 0, &ErrMsg);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001337
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001338 if (!ErrMsg.empty()) {
1339 std::string AllArgs;
Ted Kremenek379afec2009-10-22 03:24:01 +00001340 for (std::vector<const char*>::iterator I = argv.begin(), E = argv.end();
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001341 I != E; ++I) {
1342 AllArgs += ' ';
Ted Kremenek779e5f42009-10-26 22:08:39 +00001343 if (*I)
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001344 AllArgs += *I;
Ted Kremenek779e5f42009-10-26 22:08:39 +00001345 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001346
Daniel Dunbar32141c82010-02-23 20:23:45 +00001347 Diags->Report(diag::err_fe_invoking) << AllArgs << ErrMsg;
Ted Kremenek379afec2009-10-22 03:24:01 +00001348 }
Benjamin Kramer0829a832009-10-18 11:19:36 +00001349
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001350 ASTUnit *ATU = ASTUnit::LoadFromPCHFile(astTmpFile, Diags,
Douglas Gregor4db64a42010-01-23 00:14:00 +00001351 CXXIdx->getOnlyLocalDecls(),
Douglas Gregor4db64a42010-01-23 00:14:00 +00001352 RemappedFiles.data(),
Douglas Gregora88084b2010-02-18 18:08:43 +00001353 RemappedFiles.size(),
1354 /*CaptureDiagnostics=*/true);
Douglas Gregora88084b2010-02-18 18:08:43 +00001355 if (ATU) {
1356 LoadSerializedDiagnostics(DiagnosticsFile,
1357 num_unsaved_files, unsaved_files,
1358 ATU->getFileManager(),
1359 ATU->getSourceManager(),
Douglas Gregor405634b2010-04-05 18:10:21 +00001360 ATU->getStoredDiagnostics());
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001361 } else if (CXXIdx->getDisplayDiagnostics()) {
1362 // We failed to load the ASTUnit, but we can still deserialize the
1363 // diagnostics and emit them.
1364 FileManager FileMgr;
Douglas Gregorf715ca12010-03-16 00:06:06 +00001365 Diagnostic Diag;
1366 SourceManager SourceMgr(Diag);
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001367 // FIXME: Faked LangOpts!
1368 LangOptions LangOpts;
1369 llvm::SmallVector<StoredDiagnostic, 4> Diags;
1370 LoadSerializedDiagnostics(DiagnosticsFile,
1371 num_unsaved_files, unsaved_files,
1372 FileMgr, SourceMgr, Diags);
1373 for (llvm::SmallVector<StoredDiagnostic, 4>::iterator D = Diags.begin(),
1374 DEnd = Diags.end();
1375 D != DEnd; ++D) {
1376 CXStoredDiagnostic Diag(*D, LangOpts);
Douglas Gregor274f1902010-02-22 23:17:23 +00001377 CXString Msg = clang_formatDiagnostic(&Diag,
1378 clang_defaultDiagnosticDisplayOptions());
1379 fprintf(stderr, "%s\n", clang_getCString(Msg));
1380 clang_disposeString(Msg);
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001381 }
Douglas Gregor274f1902010-02-22 23:17:23 +00001382
1383#ifdef LLVM_ON_WIN32
1384 // On Windows, force a flush, since there may be multiple copies of
1385 // stderr and stdout in the file system, all with different buffers
1386 // but writing to the same device.
1387 fflush(stderr);
1388#endif
Douglas Gregora88084b2010-02-18 18:08:43 +00001389 }
Douglas Gregord93256e2010-01-28 06:00:51 +00001390
Douglas Gregor313e26c2010-02-18 23:35:40 +00001391 if (ATU) {
1392 // Make the translation unit responsible for destroying all temporary files.
1393 for (unsigned i = 0, e = TemporaryFiles.size(); i != e; ++i)
1394 ATU->addTemporaryFile(TemporaryFiles[i]);
1395 ATU->addTemporaryFile(llvm::sys::Path(ATU->getPCHFileName()));
1396 } else {
1397 // Destroy all of the temporary files now; they can't be referenced any
1398 // longer.
1399 llvm::sys::Path(astTmpFile).eraseFromDisk();
1400 for (unsigned i = 0, e = TemporaryFiles.size(); i != e; ++i)
1401 TemporaryFiles[i].eraseFromDisk();
1402 }
1403
Steve Naroffe19944c2009-10-15 22:23:48 +00001404 return ATU;
Steve Naroff5b7d8e22009-10-15 20:04:39 +00001405}
1406
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001407void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001408 if (CTUnit)
1409 delete static_cast<ASTUnit *>(CTUnit);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00001410}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001411
Douglas Gregorabc563f2010-07-19 21:46:24 +00001412int clang_reparseTranslationUnit(CXTranslationUnit TU,
1413 unsigned num_unsaved_files,
1414 struct CXUnsavedFile *unsaved_files) {
1415 if (!TU)
1416 return 1;
1417
1418 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
1419 for (unsigned I = 0; I != num_unsaved_files; ++I) {
1420 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
1421 const llvm::MemoryBuffer *Buffer
1422 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
1423 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
1424 Buffer));
1425 }
1426
1427 return static_cast<ASTUnit *>(TU)->Reparse(RemappedFiles.data(),
1428 RemappedFiles.size())? 1 : 0;
1429}
1430
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001431CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001432 if (!CTUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001433 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001434
Steve Naroff77accc12009-09-03 18:19:54 +00001435 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001436 return createCXString(CXXUnit->getOriginalSourceFileName(), true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +00001437}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +00001438
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001439CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001440 CXCursor Result = { CXCursor_TranslationUnit, { 0, 0, TU } };
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001441 return Result;
1442}
1443
Ted Kremenekfb480492010-01-13 21:46:36 +00001444} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +00001445
Ted Kremenekfb480492010-01-13 21:46:36 +00001446//===----------------------------------------------------------------------===//
Douglas Gregor1db19de2010-01-19 21:36:55 +00001447// CXSourceLocation and CXSourceRange Operations.
1448//===----------------------------------------------------------------------===//
1449
Douglas Gregorb9790342010-01-22 21:44:22 +00001450extern "C" {
1451CXSourceLocation clang_getNullLocation() {
Douglas Gregor5352ac02010-01-28 00:27:43 +00001452 CXSourceLocation Result = { { 0, 0 }, 0 };
Douglas Gregorb9790342010-01-22 21:44:22 +00001453 return Result;
1454}
1455
1456unsigned clang_equalLocations(CXSourceLocation loc1, CXSourceLocation loc2) {
Daniel Dunbar90a6b9e2010-01-30 23:58:27 +00001457 return (loc1.ptr_data[0] == loc2.ptr_data[0] &&
1458 loc1.ptr_data[1] == loc2.ptr_data[1] &&
1459 loc1.int_data == loc2.int_data);
Douglas Gregorb9790342010-01-22 21:44:22 +00001460}
1461
1462CXSourceLocation clang_getLocation(CXTranslationUnit tu,
1463 CXFile file,
1464 unsigned line,
1465 unsigned column) {
Douglas Gregor42748ec2010-04-30 19:45:53 +00001466 if (!tu || !file)
Douglas Gregorb9790342010-01-22 21:44:22 +00001467 return clang_getNullLocation();
Douglas Gregor42748ec2010-04-30 19:45:53 +00001468
Douglas Gregorb9790342010-01-22 21:44:22 +00001469 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
1470 SourceLocation SLoc
1471 = CXXUnit->getSourceManager().getLocation(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001472 static_cast<const FileEntry *>(file),
Douglas Gregorb9790342010-01-22 21:44:22 +00001473 line, column);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001474
Ted Kremenek1a9a0bc2010-06-28 23:54:17 +00001475 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
Douglas Gregorb9790342010-01-22 21:44:22 +00001476}
1477
Douglas Gregor5352ac02010-01-28 00:27:43 +00001478CXSourceRange clang_getNullRange() {
1479 CXSourceRange Result = { { 0, 0 }, 0, 0 };
1480 return Result;
1481}
Daniel Dunbard52864b2010-02-14 10:02:57 +00001482
Douglas Gregor5352ac02010-01-28 00:27:43 +00001483CXSourceRange clang_getRange(CXSourceLocation begin, CXSourceLocation end) {
1484 if (begin.ptr_data[0] != end.ptr_data[0] ||
1485 begin.ptr_data[1] != end.ptr_data[1])
1486 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001487
1488 CXSourceRange Result = { { begin.ptr_data[0], begin.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00001489 begin.int_data, end.int_data };
Douglas Gregorb9790342010-01-22 21:44:22 +00001490 return Result;
1491}
1492
Douglas Gregor46766dc2010-01-26 19:19:08 +00001493void clang_getInstantiationLocation(CXSourceLocation location,
1494 CXFile *file,
1495 unsigned *line,
1496 unsigned *column,
1497 unsigned *offset) {
Douglas Gregor1db19de2010-01-19 21:36:55 +00001498 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
1499
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00001500 if (!location.ptr_data[0] || Loc.isInvalid()) {
Douglas Gregor46766dc2010-01-26 19:19:08 +00001501 if (file)
1502 *file = 0;
1503 if (line)
1504 *line = 0;
1505 if (column)
1506 *column = 0;
1507 if (offset)
1508 *offset = 0;
1509 return;
1510 }
1511
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00001512 const SourceManager &SM =
1513 *static_cast<const SourceManager*>(location.ptr_data[0]);
Douglas Gregor1db19de2010-01-19 21:36:55 +00001514 SourceLocation InstLoc = SM.getInstantiationLoc(Loc);
Douglas Gregor1db19de2010-01-19 21:36:55 +00001515
1516 if (file)
1517 *file = (void *)SM.getFileEntryForID(SM.getFileID(InstLoc));
1518 if (line)
1519 *line = SM.getInstantiationLineNumber(InstLoc);
1520 if (column)
1521 *column = SM.getInstantiationColumnNumber(InstLoc);
Douglas Gregore69517c2010-01-26 03:07:15 +00001522 if (offset)
Douglas Gregor46766dc2010-01-26 19:19:08 +00001523 *offset = SM.getDecomposedLoc(InstLoc).second;
Douglas Gregore69517c2010-01-26 03:07:15 +00001524}
1525
Douglas Gregor1db19de2010-01-19 21:36:55 +00001526CXSourceLocation clang_getRangeStart(CXSourceRange range) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001527 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00001528 range.begin_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00001529 return Result;
1530}
1531
1532CXSourceLocation clang_getRangeEnd(CXSourceRange range) {
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00001533 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00001534 range.end_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00001535 return Result;
1536}
1537
Douglas Gregorb9790342010-01-22 21:44:22 +00001538} // end: extern "C"
1539
Douglas Gregor1db19de2010-01-19 21:36:55 +00001540//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00001541// CXFile Operations.
1542//===----------------------------------------------------------------------===//
1543
1544extern "C" {
Ted Kremenek74844072010-02-17 00:41:20 +00001545CXString clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00001546 if (!SFile)
Ted Kremenek74844072010-02-17 00:41:20 +00001547 return createCXString(NULL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001548
Steve Naroff88145032009-10-27 14:35:18 +00001549 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Ted Kremenek74844072010-02-17 00:41:20 +00001550 return createCXString(FEnt->getName());
Steve Naroff88145032009-10-27 14:35:18 +00001551}
1552
1553time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00001554 if (!SFile)
1555 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001556
Steve Naroff88145032009-10-27 14:35:18 +00001557 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
1558 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +00001559}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001560
Douglas Gregorb9790342010-01-22 21:44:22 +00001561CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
1562 if (!tu)
1563 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001564
Douglas Gregorb9790342010-01-22 21:44:22 +00001565 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001566
Douglas Gregorb9790342010-01-22 21:44:22 +00001567 FileManager &FMgr = CXXUnit->getFileManager();
1568 const FileEntry *File = FMgr.getFile(file_name, file_name+strlen(file_name));
1569 return const_cast<FileEntry *>(File);
1570}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001571
Ted Kremenekfb480492010-01-13 21:46:36 +00001572} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +00001573
Ted Kremenekfb480492010-01-13 21:46:36 +00001574//===----------------------------------------------------------------------===//
1575// CXCursor Operations.
1576//===----------------------------------------------------------------------===//
1577
Ted Kremenekfb480492010-01-13 21:46:36 +00001578static Decl *getDeclFromExpr(Stmt *E) {
1579 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
1580 return RefExpr->getDecl();
1581 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
1582 return ME->getMemberDecl();
1583 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
1584 return RE->getDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001585
Ted Kremenekfb480492010-01-13 21:46:36 +00001586 if (CallExpr *CE = dyn_cast<CallExpr>(E))
1587 return getDeclFromExpr(CE->getCallee());
1588 if (CastExpr *CE = dyn_cast<CastExpr>(E))
1589 return getDeclFromExpr(CE->getSubExpr());
1590 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
1591 return OME->getMethodDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001592
Ted Kremenekfb480492010-01-13 21:46:36 +00001593 return 0;
1594}
1595
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00001596static SourceLocation getLocationFromExpr(Expr *E) {
1597 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
1598 return /*FIXME:*/Msg->getLeftLoc();
1599 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
1600 return DRE->getLocation();
1601 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
1602 return Member->getMemberLoc();
1603 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
1604 return Ivar->getLocation();
1605 return E->getLocStart();
1606}
1607
Ted Kremenekfb480492010-01-13 21:46:36 +00001608extern "C" {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001609
1610unsigned clang_visitChildren(CXCursor parent,
Douglas Gregorb1373d02010-01-20 20:59:29 +00001611 CXCursorVisitor visitor,
1612 CXClientData client_data) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001613 ASTUnit *CXXUnit = getCursorASTUnit(parent);
Douglas Gregorb1373d02010-01-20 20:59:29 +00001614
1615 unsigned PCHLevel = Decl::MaxPCHLevel;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001616
Douglas Gregorb1373d02010-01-20 20:59:29 +00001617 // Set the PCHLevel to filter out unwanted decls if requested.
1618 if (CXXUnit->getOnlyLocalDecls()) {
1619 PCHLevel = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001620
Douglas Gregorb1373d02010-01-20 20:59:29 +00001621 // If the main input was an AST, bump the level.
1622 if (CXXUnit->isMainFileAST())
1623 ++PCHLevel;
1624 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001625
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001626 CursorVisitor CursorVis(CXXUnit, visitor, client_data, PCHLevel);
Douglas Gregorb1373d02010-01-20 20:59:29 +00001627 return CursorVis.VisitChildren(parent);
1628}
1629
Douglas Gregor78205d42010-01-20 21:45:58 +00001630static CXString getDeclSpelling(Decl *D) {
1631 NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
1632 if (!ND)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001633 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001634
Douglas Gregor78205d42010-01-20 21:45:58 +00001635 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001636 return createCXString(OMD->getSelector().getAsString());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001637
Douglas Gregor78205d42010-01-20 21:45:58 +00001638 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
1639 // No, this isn't the same as the code below. getIdentifier() is non-virtual
1640 // and returns different names. NamedDecl returns the class name and
1641 // ObjCCategoryImplDecl returns the category name.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001642 return createCXString(CIMP->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001643
Ted Kremenek50aa6ac2010-05-19 21:51:10 +00001644 llvm::SmallString<1024> S;
1645 llvm::raw_svector_ostream os(S);
1646 ND->printName(os);
1647
1648 return createCXString(os.str());
Douglas Gregor78205d42010-01-20 21:45:58 +00001649}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001650
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001651CXString clang_getCursorSpelling(CXCursor C) {
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001652 if (clang_isTranslationUnit(C.kind))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001653 return clang_getTranslationUnitSpelling(C.data[2]);
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001654
Steve Narofff334b4e2009-09-02 18:26:48 +00001655 if (clang_isReference(C.kind)) {
1656 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00001657 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +00001658 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001659 return createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00001660 }
1661 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +00001662 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001663 return createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00001664 }
1665 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +00001666 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +00001667 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001668 return createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00001669 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001670 case CXCursor_TypeRef: {
1671 TypeDecl *Type = getCursorTypeRef(C).first;
1672 assert(Type && "Missing type decl");
1673
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001674 return createCXString(getCursorContext(C).getTypeDeclType(Type).
1675 getAsString());
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001676 }
1677
Daniel Dunbaracca7252009-11-30 20:42:49 +00001678 default:
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001679 return createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +00001680 }
1681 }
Douglas Gregor97b98722010-01-19 23:20:36 +00001682
1683 if (clang_isExpression(C.kind)) {
1684 Decl *D = getDeclFromExpr(getCursorExpr(C));
1685 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +00001686 return getDeclSpelling(D);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001687 return createCXString("");
Douglas Gregor97b98722010-01-19 23:20:36 +00001688 }
1689
Douglas Gregor4ae8f292010-03-18 17:52:52 +00001690 if (C.kind == CXCursor_MacroInstantiation)
1691 return createCXString(getCursorMacroInstantiation(C)->getName()
1692 ->getNameStart());
1693
Douglas Gregor572feb22010-03-18 18:04:21 +00001694 if (C.kind == CXCursor_MacroDefinition)
1695 return createCXString(getCursorMacroDefinition(C)->getName()
1696 ->getNameStart());
1697
Douglas Gregor60cbfac2010-01-25 16:56:17 +00001698 if (clang_isDeclaration(C.kind))
1699 return getDeclSpelling(getCursorDecl(C));
Ted Kremeneke68fff62010-02-17 00:41:32 +00001700
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001701 return createCXString("");
Steve Narofff334b4e2009-09-02 18:26:48 +00001702}
1703
Ted Kremeneke68fff62010-02-17 00:41:32 +00001704CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00001705 switch (Kind) {
Ted Kremeneke68fff62010-02-17 00:41:32 +00001706 case CXCursor_FunctionDecl:
1707 return createCXString("FunctionDecl");
1708 case CXCursor_TypedefDecl:
1709 return createCXString("TypedefDecl");
1710 case CXCursor_EnumDecl:
1711 return createCXString("EnumDecl");
1712 case CXCursor_EnumConstantDecl:
1713 return createCXString("EnumConstantDecl");
1714 case CXCursor_StructDecl:
1715 return createCXString("StructDecl");
1716 case CXCursor_UnionDecl:
1717 return createCXString("UnionDecl");
1718 case CXCursor_ClassDecl:
1719 return createCXString("ClassDecl");
1720 case CXCursor_FieldDecl:
1721 return createCXString("FieldDecl");
1722 case CXCursor_VarDecl:
1723 return createCXString("VarDecl");
1724 case CXCursor_ParmDecl:
1725 return createCXString("ParmDecl");
1726 case CXCursor_ObjCInterfaceDecl:
1727 return createCXString("ObjCInterfaceDecl");
1728 case CXCursor_ObjCCategoryDecl:
1729 return createCXString("ObjCCategoryDecl");
1730 case CXCursor_ObjCProtocolDecl:
1731 return createCXString("ObjCProtocolDecl");
1732 case CXCursor_ObjCPropertyDecl:
1733 return createCXString("ObjCPropertyDecl");
1734 case CXCursor_ObjCIvarDecl:
1735 return createCXString("ObjCIvarDecl");
1736 case CXCursor_ObjCInstanceMethodDecl:
1737 return createCXString("ObjCInstanceMethodDecl");
1738 case CXCursor_ObjCClassMethodDecl:
1739 return createCXString("ObjCClassMethodDecl");
1740 case CXCursor_ObjCImplementationDecl:
1741 return createCXString("ObjCImplementationDecl");
1742 case CXCursor_ObjCCategoryImplDecl:
1743 return createCXString("ObjCCategoryImplDecl");
Ted Kremenek8bd5a692010-04-13 23:39:06 +00001744 case CXCursor_CXXMethod:
1745 return createCXString("CXXMethod");
Ted Kremeneke68fff62010-02-17 00:41:32 +00001746 case CXCursor_UnexposedDecl:
1747 return createCXString("UnexposedDecl");
1748 case CXCursor_ObjCSuperClassRef:
1749 return createCXString("ObjCSuperClassRef");
1750 case CXCursor_ObjCProtocolRef:
1751 return createCXString("ObjCProtocolRef");
1752 case CXCursor_ObjCClassRef:
1753 return createCXString("ObjCClassRef");
1754 case CXCursor_TypeRef:
1755 return createCXString("TypeRef");
1756 case CXCursor_UnexposedExpr:
1757 return createCXString("UnexposedExpr");
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00001758 case CXCursor_BlockExpr:
1759 return createCXString("BlockExpr");
Ted Kremeneke68fff62010-02-17 00:41:32 +00001760 case CXCursor_DeclRefExpr:
1761 return createCXString("DeclRefExpr");
1762 case CXCursor_MemberRefExpr:
1763 return createCXString("MemberRefExpr");
1764 case CXCursor_CallExpr:
1765 return createCXString("CallExpr");
1766 case CXCursor_ObjCMessageExpr:
1767 return createCXString("ObjCMessageExpr");
1768 case CXCursor_UnexposedStmt:
1769 return createCXString("UnexposedStmt");
1770 case CXCursor_InvalidFile:
1771 return createCXString("InvalidFile");
Ted Kremenek292db642010-03-19 20:39:05 +00001772 case CXCursor_InvalidCode:
1773 return createCXString("InvalidCode");
Ted Kremeneke68fff62010-02-17 00:41:32 +00001774 case CXCursor_NoDeclFound:
1775 return createCXString("NoDeclFound");
1776 case CXCursor_NotImplemented:
1777 return createCXString("NotImplemented");
1778 case CXCursor_TranslationUnit:
1779 return createCXString("TranslationUnit");
Ted Kremeneke77f4432010-02-18 03:09:07 +00001780 case CXCursor_UnexposedAttr:
1781 return createCXString("UnexposedAttr");
1782 case CXCursor_IBActionAttr:
1783 return createCXString("attribute(ibaction)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00001784 case CXCursor_IBOutletAttr:
1785 return createCXString("attribute(iboutlet)");
Ted Kremenek857e9182010-05-19 17:38:06 +00001786 case CXCursor_IBOutletCollectionAttr:
1787 return createCXString("attribute(iboutletcollection)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00001788 case CXCursor_PreprocessingDirective:
1789 return createCXString("preprocessing directive");
Douglas Gregor572feb22010-03-18 18:04:21 +00001790 case CXCursor_MacroDefinition:
1791 return createCXString("macro definition");
Douglas Gregor48072312010-03-18 15:23:44 +00001792 case CXCursor_MacroInstantiation:
1793 return createCXString("macro instantiation");
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00001794 case CXCursor_Namespace:
1795 return createCXString("Namespace");
Ted Kremeneka0536d82010-05-07 01:04:29 +00001796 case CXCursor_LinkageSpec:
1797 return createCXString("LinkageSpec");
Steve Naroff89922f82009-08-31 00:59:03 +00001798 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00001799
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00001800 llvm_unreachable("Unhandled CXCursorKind");
Ted Kremeneke68fff62010-02-17 00:41:32 +00001801 return createCXString(NULL);
Steve Naroff600866c2009-08-27 19:51:58 +00001802}
Steve Naroff89922f82009-08-31 00:59:03 +00001803
Ted Kremeneke68fff62010-02-17 00:41:32 +00001804enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
1805 CXCursor parent,
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001806 CXClientData client_data) {
1807 CXCursor *BestCursor = static_cast<CXCursor *>(client_data);
1808 *BestCursor = cursor;
1809 return CXChildVisit_Recurse;
1810}
Ted Kremeneke68fff62010-02-17 00:41:32 +00001811
Douglas Gregorb9790342010-01-22 21:44:22 +00001812CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
1813 if (!TU)
Ted Kremenekf4629892010-01-14 01:51:23 +00001814 return clang_getNullCursor();
Ted Kremeneke68fff62010-02-17 00:41:32 +00001815
Douglas Gregorb9790342010-01-22 21:44:22 +00001816 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
1817
Douglas Gregorbdf60622010-03-05 21:16:25 +00001818 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
1819
Ted Kremeneka297de22010-01-25 22:34:44 +00001820 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001821 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
1822 if (SLoc.isValid()) {
Daniel Dunbard52864b2010-02-14 10:02:57 +00001823 SourceRange RegionOfInterest(SLoc, SLoc.getFileLocWithOffset(1));
Ted Kremeneke68fff62010-02-17 00:41:32 +00001824
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001825 // FIXME: Would be great to have a "hint" cursor, then walk from that
1826 // hint cursor upward until we find a cursor whose source range encloses
1827 // the region of interest, rather than starting from the translation unit.
1828 CXCursor Parent = clang_getTranslationUnitCursor(CXXUnit);
Ted Kremeneke68fff62010-02-17 00:41:32 +00001829 CursorVisitor CursorVis(CXXUnit, GetCursorVisitor, &Result,
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001830 Decl::MaxPCHLevel, RegionOfInterest);
1831 CursorVis.VisitChildren(Parent);
Steve Naroff77128dd2009-09-15 20:25:34 +00001832 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00001833 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00001834}
1835
Ted Kremenek73885552009-11-17 19:28:59 +00001836CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00001837 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00001838}
1839
1840unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00001841 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00001842}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001843
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001844unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00001845 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
1846}
1847
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001848unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +00001849 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
1850}
Steve Naroff2d4d6292009-08-31 14:26:51 +00001851
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001852unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00001853 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
1854}
1855
Douglas Gregor97b98722010-01-19 23:20:36 +00001856unsigned clang_isExpression(enum CXCursorKind K) {
1857 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
1858}
1859
1860unsigned clang_isStatement(enum CXCursorKind K) {
1861 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
1862}
1863
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001864unsigned clang_isTranslationUnit(enum CXCursorKind K) {
1865 return K == CXCursor_TranslationUnit;
1866}
1867
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00001868unsigned clang_isPreprocessing(enum CXCursorKind K) {
1869 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
1870}
1871
Ted Kremenekad6eff62010-03-08 21:17:29 +00001872unsigned clang_isUnexposed(enum CXCursorKind K) {
1873 switch (K) {
1874 case CXCursor_UnexposedDecl:
1875 case CXCursor_UnexposedExpr:
1876 case CXCursor_UnexposedStmt:
1877 case CXCursor_UnexposedAttr:
1878 return true;
1879 default:
1880 return false;
1881 }
1882}
1883
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001884CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00001885 return C.kind;
1886}
1887
Douglas Gregor98258af2010-01-18 22:46:11 +00001888CXSourceLocation clang_getCursorLocation(CXCursor C) {
1889 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00001890 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001891 case CXCursor_ObjCSuperClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00001892 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1893 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001894 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001895 }
1896
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001897 case CXCursor_ObjCProtocolRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00001898 std::pair<ObjCProtocolDecl *, SourceLocation> P
1899 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001900 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001901 }
1902
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001903 case CXCursor_ObjCClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00001904 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1905 = getCursorObjCClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001906 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001907 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001908
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001909 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001910 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001911 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001912 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001913
Douglas Gregorf46034a2010-01-18 23:41:10 +00001914 default:
1915 // FIXME: Need a way to enumerate all non-reference cases.
1916 llvm_unreachable("Missed a reference kind");
1917 }
Douglas Gregor98258af2010-01-18 22:46:11 +00001918 }
Douglas Gregor97b98722010-01-19 23:20:36 +00001919
1920 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001921 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00001922 getLocationFromExpr(getCursorExpr(C)));
1923
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00001924 if (C.kind == CXCursor_PreprocessingDirective) {
1925 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
1926 return cxloc::translateSourceLocation(getCursorContext(C), L);
1927 }
Douglas Gregor48072312010-03-18 15:23:44 +00001928
1929 if (C.kind == CXCursor_MacroInstantiation) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00001930 SourceLocation L
1931 = cxcursor::getCursorMacroInstantiation(C)->getSourceRange().getBegin();
Douglas Gregor48072312010-03-18 15:23:44 +00001932 return cxloc::translateSourceLocation(getCursorContext(C), L);
1933 }
Douglas Gregor572feb22010-03-18 18:04:21 +00001934
1935 if (C.kind == CXCursor_MacroDefinition) {
1936 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
1937 return cxloc::translateSourceLocation(getCursorContext(C), L);
1938 }
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00001939
Ted Kremenek9a700d22010-05-12 06:16:13 +00001940 if (C.kind < CXCursor_FirstDecl || C.kind > CXCursor_LastDecl)
Douglas Gregor5352ac02010-01-28 00:27:43 +00001941 return clang_getNullLocation();
Douglas Gregor98258af2010-01-18 22:46:11 +00001942
Douglas Gregorf46034a2010-01-18 23:41:10 +00001943 Decl *D = getCursorDecl(C);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001944 SourceLocation Loc = D->getLocation();
1945 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
1946 Loc = Class->getClassLoc();
Douglas Gregor2ca54fe2010-03-22 15:53:50 +00001947 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00001948}
Douglas Gregora7bde202010-01-19 00:34:46 +00001949
1950CXSourceRange clang_getCursorExtent(CXCursor C) {
1951 if (clang_isReference(C.kind)) {
1952 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001953 case CXCursor_ObjCSuperClassRef: {
Douglas Gregora7bde202010-01-19 00:34:46 +00001954 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1955 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001956 return cxloc::translateSourceRange(P.first->getASTContext(), P.second);
Douglas Gregora7bde202010-01-19 00:34:46 +00001957 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001958
1959 case CXCursor_ObjCProtocolRef: {
Douglas Gregora7bde202010-01-19 00:34:46 +00001960 std::pair<ObjCProtocolDecl *, SourceLocation> P
1961 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001962 return cxloc::translateSourceRange(P.first->getASTContext(), P.second);
Douglas Gregora7bde202010-01-19 00:34:46 +00001963 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001964
1965 case CXCursor_ObjCClassRef: {
Douglas Gregora7bde202010-01-19 00:34:46 +00001966 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1967 = getCursorObjCClassRef(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001968
Ted Kremeneka297de22010-01-25 22:34:44 +00001969 return cxloc::translateSourceRange(P.first->getASTContext(), P.second);
Douglas Gregora7bde202010-01-19 00:34:46 +00001970 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001971
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001972 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001973 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001974 return cxloc::translateSourceRange(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001975 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001976
Douglas Gregora7bde202010-01-19 00:34:46 +00001977 default:
1978 // FIXME: Need a way to enumerate all non-reference cases.
1979 llvm_unreachable("Missed a reference kind");
1980 }
1981 }
Douglas Gregor97b98722010-01-19 23:20:36 +00001982
1983 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001984 return cxloc::translateSourceRange(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00001985 getCursorExpr(C)->getSourceRange());
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001986
1987 if (clang_isStatement(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001988 return cxloc::translateSourceRange(getCursorContext(C),
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001989 getCursorStmt(C)->getSourceRange());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001990
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00001991 if (C.kind == CXCursor_PreprocessingDirective) {
1992 SourceRange R = cxcursor::getCursorPreprocessingDirective(C);
1993 return cxloc::translateSourceRange(getCursorContext(C), R);
1994 }
Douglas Gregor48072312010-03-18 15:23:44 +00001995
1996 if (C.kind == CXCursor_MacroInstantiation) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00001997 SourceRange R = cxcursor::getCursorMacroInstantiation(C)->getSourceRange();
Douglas Gregor48072312010-03-18 15:23:44 +00001998 return cxloc::translateSourceRange(getCursorContext(C), R);
1999 }
Douglas Gregor572feb22010-03-18 18:04:21 +00002000
2001 if (C.kind == CXCursor_MacroDefinition) {
2002 SourceRange R = cxcursor::getCursorMacroDefinition(C)->getSourceRange();
2003 return cxloc::translateSourceRange(getCursorContext(C), R);
2004 }
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002005
Ted Kremenek9a700d22010-05-12 06:16:13 +00002006 if (C.kind < CXCursor_FirstDecl || C.kind > CXCursor_LastDecl)
Douglas Gregor5352ac02010-01-28 00:27:43 +00002007 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002008
Douglas Gregora7bde202010-01-19 00:34:46 +00002009 Decl *D = getCursorDecl(C);
Douglas Gregor2ca54fe2010-03-22 15:53:50 +00002010 return cxloc::translateSourceRange(getCursorContext(C), D->getSourceRange());
Douglas Gregora7bde202010-01-19 00:34:46 +00002011}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002012
2013CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002014 if (clang_isInvalid(C.kind))
2015 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002016
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002017 ASTUnit *CXXUnit = getCursorASTUnit(C);
Douglas Gregorb6998662010-01-19 19:34:47 +00002018 if (clang_isDeclaration(C.kind))
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002019 return C;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002020
Douglas Gregor97b98722010-01-19 23:20:36 +00002021 if (clang_isExpression(C.kind)) {
2022 Decl *D = getDeclFromExpr(getCursorExpr(C));
2023 if (D)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002024 return MakeCXCursor(D, CXXUnit);
Douglas Gregor97b98722010-01-19 23:20:36 +00002025 return clang_getNullCursor();
2026 }
2027
Douglas Gregorbf7efa22010-03-18 18:23:03 +00002028 if (C.kind == CXCursor_MacroInstantiation) {
2029 if (MacroDefinition *Def = getCursorMacroInstantiation(C)->getDefinition())
2030 return MakeMacroDefinitionCursor(Def, CXXUnit);
2031 }
2032
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002033 if (!clang_isReference(C.kind))
2034 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002035
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002036 switch (C.kind) {
2037 case CXCursor_ObjCSuperClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002038 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002039
2040 case CXCursor_ObjCProtocolRef: {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002041 return MakeCXCursor(getCursorObjCProtocolRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002042
2043 case CXCursor_ObjCClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002044 return MakeCXCursor(getCursorObjCClassRef(C).first, CXXUnit);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002045
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002046 case CXCursor_TypeRef:
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002047 return MakeCXCursor(getCursorTypeRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002048
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002049 default:
2050 // We would prefer to enumerate all non-reference cursor kinds here.
2051 llvm_unreachable("Unhandled reference cursor kind");
2052 break;
2053 }
2054 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002055
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002056 return clang_getNullCursor();
2057}
2058
Douglas Gregorb6998662010-01-19 19:34:47 +00002059CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002060 if (clang_isInvalid(C.kind))
2061 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002062
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002063 ASTUnit *CXXUnit = getCursorASTUnit(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002064
Douglas Gregorb6998662010-01-19 19:34:47 +00002065 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00002066 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00002067 C = clang_getCursorReferenced(C);
2068 WasReference = true;
2069 }
2070
Douglas Gregorbf7efa22010-03-18 18:23:03 +00002071 if (C.kind == CXCursor_MacroInstantiation)
2072 return clang_getCursorReferenced(C);
2073
Douglas Gregorb6998662010-01-19 19:34:47 +00002074 if (!clang_isDeclaration(C.kind))
2075 return clang_getNullCursor();
2076
2077 Decl *D = getCursorDecl(C);
2078 if (!D)
2079 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002080
Douglas Gregorb6998662010-01-19 19:34:47 +00002081 switch (D->getKind()) {
2082 // Declaration kinds that don't really separate the notions of
2083 // declaration and definition.
2084 case Decl::Namespace:
2085 case Decl::Typedef:
2086 case Decl::TemplateTypeParm:
2087 case Decl::EnumConstant:
2088 case Decl::Field:
2089 case Decl::ObjCIvar:
2090 case Decl::ObjCAtDefsField:
2091 case Decl::ImplicitParam:
2092 case Decl::ParmVar:
2093 case Decl::NonTypeTemplateParm:
2094 case Decl::TemplateTemplateParm:
2095 case Decl::ObjCCategoryImpl:
2096 case Decl::ObjCImplementation:
Abramo Bagnara6206d532010-06-05 05:09:32 +00002097 case Decl::AccessSpec:
Douglas Gregorb6998662010-01-19 19:34:47 +00002098 case Decl::LinkageSpec:
2099 case Decl::ObjCPropertyImpl:
2100 case Decl::FileScopeAsm:
2101 case Decl::StaticAssert:
2102 case Decl::Block:
2103 return C;
2104
2105 // Declaration kinds that don't make any sense here, but are
2106 // nonetheless harmless.
2107 case Decl::TranslationUnit:
Douglas Gregorb6998662010-01-19 19:34:47 +00002108 break;
2109
2110 // Declaration kinds for which the definition is not resolvable.
2111 case Decl::UnresolvedUsingTypename:
2112 case Decl::UnresolvedUsingValue:
2113 break;
2114
2115 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002116 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
2117 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002118
2119 case Decl::NamespaceAlias:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002120 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002121
2122 case Decl::Enum:
2123 case Decl::Record:
2124 case Decl::CXXRecord:
2125 case Decl::ClassTemplateSpecialization:
2126 case Decl::ClassTemplatePartialSpecialization:
Douglas Gregor952b0172010-02-11 01:04:33 +00002127 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002128 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002129 return clang_getNullCursor();
2130
2131 case Decl::Function:
2132 case Decl::CXXMethod:
2133 case Decl::CXXConstructor:
2134 case Decl::CXXDestructor:
2135 case Decl::CXXConversion: {
2136 const FunctionDecl *Def = 0;
2137 if (cast<FunctionDecl>(D)->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002138 return MakeCXCursor(const_cast<FunctionDecl *>(Def), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002139 return clang_getNullCursor();
2140 }
2141
2142 case Decl::Var: {
Sebastian Redl31310a22010-02-01 20:16:42 +00002143 // Ask the variable if it has a definition.
2144 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
2145 return MakeCXCursor(Def, CXXUnit);
2146 return clang_getNullCursor();
Douglas Gregorb6998662010-01-19 19:34:47 +00002147 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002148
Douglas Gregorb6998662010-01-19 19:34:47 +00002149 case Decl::FunctionTemplate: {
2150 const FunctionDecl *Def = 0;
2151 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002152 return MakeCXCursor(Def->getDescribedFunctionTemplate(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002153 return clang_getNullCursor();
2154 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002155
Douglas Gregorb6998662010-01-19 19:34:47 +00002156 case Decl::ClassTemplate: {
2157 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
Douglas Gregor952b0172010-02-11 01:04:33 +00002158 ->getDefinition())
Douglas Gregorb6998662010-01-19 19:34:47 +00002159 return MakeCXCursor(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002160 cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002161 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002162 return clang_getNullCursor();
2163 }
2164
2165 case Decl::Using: {
2166 UsingDecl *Using = cast<UsingDecl>(D);
2167 CXCursor Def = clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002168 for (UsingDecl::shadow_iterator S = Using->shadow_begin(),
2169 SEnd = Using->shadow_end();
Douglas Gregorb6998662010-01-19 19:34:47 +00002170 S != SEnd; ++S) {
2171 if (Def != clang_getNullCursor()) {
2172 // FIXME: We have no way to return multiple results.
2173 return clang_getNullCursor();
2174 }
2175
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002176 Def = clang_getCursorDefinition(MakeCXCursor((*S)->getTargetDecl(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002177 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002178 }
2179
2180 return Def;
2181 }
2182
2183 case Decl::UsingShadow:
2184 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002185 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002186 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002187
2188 case Decl::ObjCMethod: {
2189 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
2190 if (Method->isThisDeclarationADefinition())
2191 return C;
2192
2193 // Dig out the method definition in the associated
2194 // @implementation, if we have it.
2195 // FIXME: The ASTs should make finding the definition easier.
2196 if (ObjCInterfaceDecl *Class
2197 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
2198 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
2199 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
2200 Method->isInstanceMethod()))
2201 if (Def->isThisDeclarationADefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002202 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002203
2204 return clang_getNullCursor();
2205 }
2206
2207 case Decl::ObjCCategory:
2208 if (ObjCCategoryImplDecl *Impl
2209 = cast<ObjCCategoryDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002210 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002211 return clang_getNullCursor();
2212
2213 case Decl::ObjCProtocol:
2214 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
2215 return C;
2216 return clang_getNullCursor();
2217
2218 case Decl::ObjCInterface:
2219 // There are two notions of a "definition" for an Objective-C
2220 // class: the interface and its implementation. When we resolved a
2221 // reference to an Objective-C class, produce the @interface as
2222 // the definition; when we were provided with the interface,
2223 // produce the @implementation as the definition.
2224 if (WasReference) {
2225 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
2226 return C;
2227 } else if (ObjCImplementationDecl *Impl
2228 = cast<ObjCInterfaceDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002229 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002230 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002231
Douglas Gregorb6998662010-01-19 19:34:47 +00002232 case Decl::ObjCProperty:
2233 // FIXME: We don't really know where to find the
2234 // ObjCPropertyImplDecls that implement this property.
2235 return clang_getNullCursor();
2236
2237 case Decl::ObjCCompatibleAlias:
2238 if (ObjCInterfaceDecl *Class
2239 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
2240 if (!Class->isForwardDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002241 return MakeCXCursor(Class, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002242
Douglas Gregorb6998662010-01-19 19:34:47 +00002243 return clang_getNullCursor();
2244
2245 case Decl::ObjCForwardProtocol: {
2246 ObjCForwardProtocolDecl *Forward = cast<ObjCForwardProtocolDecl>(D);
2247 if (Forward->protocol_size() == 1)
2248 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002249 MakeCXCursor(*Forward->protocol_begin(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002250 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002251
2252 // FIXME: Cannot return multiple definitions.
2253 return clang_getNullCursor();
2254 }
2255
2256 case Decl::ObjCClass: {
2257 ObjCClassDecl *Class = cast<ObjCClassDecl>(D);
2258 if (Class->size() == 1) {
2259 ObjCInterfaceDecl *IFace = Class->begin()->getInterface();
2260 if (!IFace->isForwardDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002261 return MakeCXCursor(IFace, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002262 return clang_getNullCursor();
2263 }
2264
2265 // FIXME: Cannot return multiple definitions.
2266 return clang_getNullCursor();
2267 }
2268
2269 case Decl::Friend:
2270 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002271 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002272 return clang_getNullCursor();
2273
2274 case Decl::FriendTemplate:
2275 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002276 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002277 return clang_getNullCursor();
2278 }
2279
2280 return clang_getNullCursor();
2281}
2282
2283unsigned clang_isCursorDefinition(CXCursor C) {
2284 if (!clang_isDeclaration(C.kind))
2285 return 0;
2286
2287 return clang_getCursorDefinition(C) == C;
2288}
2289
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002290void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00002291 const char **startBuf,
2292 const char **endBuf,
2293 unsigned *startLine,
2294 unsigned *startColumn,
2295 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002296 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00002297 assert(getCursorDecl(C) && "CXCursor has null decl");
2298 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00002299 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
2300 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002301
Steve Naroff4ade6d62009-09-23 17:52:52 +00002302 SourceManager &SM = FD->getASTContext().getSourceManager();
2303 *startBuf = SM.getCharacterData(Body->getLBracLoc());
2304 *endBuf = SM.getCharacterData(Body->getRBracLoc());
2305 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
2306 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
2307 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
2308 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
2309}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002310
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002311void clang_enableStackTraces(void) {
2312 llvm::sys::PrintStackTraceOnErrorSignal();
2313}
2314
Ted Kremenekfb480492010-01-13 21:46:36 +00002315} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00002316
Ted Kremenekfb480492010-01-13 21:46:36 +00002317//===----------------------------------------------------------------------===//
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002318// Token-based Operations.
2319//===----------------------------------------------------------------------===//
2320
2321/* CXToken layout:
2322 * int_data[0]: a CXTokenKind
2323 * int_data[1]: starting token location
2324 * int_data[2]: token length
2325 * int_data[3]: reserved
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002326 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002327 * otherwise unused.
2328 */
2329extern "C" {
2330
2331CXTokenKind clang_getTokenKind(CXToken CXTok) {
2332 return static_cast<CXTokenKind>(CXTok.int_data[0]);
2333}
2334
2335CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
2336 switch (clang_getTokenKind(CXTok)) {
2337 case CXToken_Identifier:
2338 case CXToken_Keyword:
2339 // We know we have an IdentifierInfo*, so use that.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002340 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
2341 ->getNameStart());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002342
2343 case CXToken_Literal: {
2344 // We have stashed the starting pointer in the ptr_data field. Use it.
2345 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002346 return createCXString(llvm::StringRef(Text, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002347 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002348
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002349 case CXToken_Punctuation:
2350 case CXToken_Comment:
2351 break;
2352 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002353
2354 // We have to find the starting buffer pointer the hard way, by
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002355 // deconstructing the source location.
2356 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2357 if (!CXXUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002358 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002359
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002360 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
2361 std::pair<FileID, unsigned> LocInfo
2362 = CXXUnit->getSourceManager().getDecomposedLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +00002363 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002364 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00002365 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
2366 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00002367 return createCXString("");
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002368
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002369 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002370}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002371
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002372CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
2373 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2374 if (!CXXUnit)
2375 return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002376
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002377 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
2378 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
2379}
2380
2381CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
2382 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregor5352ac02010-01-28 00:27:43 +00002383 if (!CXXUnit)
2384 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002385
2386 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002387 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
2388}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002389
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002390void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
2391 CXToken **Tokens, unsigned *NumTokens) {
2392 if (Tokens)
2393 *Tokens = 0;
2394 if (NumTokens)
2395 *NumTokens = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002396
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002397 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2398 if (!CXXUnit || !Tokens || !NumTokens)
2399 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002400
Douglas Gregorbdf60622010-03-05 21:16:25 +00002401 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
2402
Daniel Dunbar85b988f2010-02-14 08:31:57 +00002403 SourceRange R = cxloc::translateCXSourceRange(Range);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002404 if (R.isInvalid())
2405 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002406
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002407 SourceManager &SourceMgr = CXXUnit->getSourceManager();
2408 std::pair<FileID, unsigned> BeginLocInfo
2409 = SourceMgr.getDecomposedLoc(R.getBegin());
2410 std::pair<FileID, unsigned> EndLocInfo
2411 = SourceMgr.getDecomposedLoc(R.getEnd());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002412
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002413 // Cannot tokenize across files.
2414 if (BeginLocInfo.first != EndLocInfo.first)
2415 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002416
2417 // Create a lexer
Douglas Gregorf715ca12010-03-16 00:06:06 +00002418 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002419 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00002420 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
Douglas Gregor47a3fcd2010-03-16 20:26:15 +00002421 if (Invalid)
2422 return;
Douglas Gregoraea67db2010-03-15 22:54:52 +00002423
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002424 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
2425 CXXUnit->getASTContext().getLangOptions(),
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002426 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002427 Lex.SetCommentRetentionState(true);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002428
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002429 // Lex tokens until we hit the end of the range.
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002430 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002431 llvm::SmallVector<CXToken, 32> CXTokens;
2432 Token Tok;
2433 do {
2434 // Lex the next token
2435 Lex.LexFromRawLexer(Tok);
2436 if (Tok.is(tok::eof))
2437 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002438
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002439 // Initialize the CXToken.
2440 CXToken CXTok;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002441
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002442 // - Common fields
2443 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
2444 CXTok.int_data[2] = Tok.getLength();
2445 CXTok.int_data[3] = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002446
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002447 // - Kind-specific fields
2448 if (Tok.isLiteral()) {
2449 CXTok.int_data[0] = CXToken_Literal;
2450 CXTok.ptr_data = (void *)Tok.getLiteralData();
2451 } else if (Tok.is(tok::identifier)) {
Douglas Gregoraea67db2010-03-15 22:54:52 +00002452 // Lookup the identifier to determine whether we have a keyword.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002453 std::pair<FileID, unsigned> LocInfo
2454 = SourceMgr.getDecomposedLoc(Tok.getLocation());
Douglas Gregorf715ca12010-03-16 00:06:06 +00002455 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002456 llvm::StringRef Buf
Douglas Gregorf715ca12010-03-16 00:06:06 +00002457 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
2458 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00002459 return;
2460
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002461 const char *StartPos = Buf.data() + LocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002462 IdentifierInfo *II
2463 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok, StartPos);
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00002464
2465 if (II->getObjCKeywordID() != tok::objc_not_keyword) {
2466 CXTok.int_data[0] = CXToken_Keyword;
2467 }
2468 else {
2469 CXTok.int_data[0] = II->getTokenID() == tok::identifier?
2470 CXToken_Identifier
2471 : CXToken_Keyword;
2472 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002473 CXTok.ptr_data = II;
2474 } else if (Tok.is(tok::comment)) {
2475 CXTok.int_data[0] = CXToken_Comment;
2476 CXTok.ptr_data = 0;
2477 } else {
2478 CXTok.int_data[0] = CXToken_Punctuation;
2479 CXTok.ptr_data = 0;
2480 }
2481 CXTokens.push_back(CXTok);
2482 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002483
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002484 if (CXTokens.empty())
2485 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002486
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002487 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
2488 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
2489 *NumTokens = CXTokens.size();
2490}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002491
Ted Kremenek6db61092010-05-05 00:55:15 +00002492void clang_disposeTokens(CXTranslationUnit TU,
2493 CXToken *Tokens, unsigned NumTokens) {
2494 free(Tokens);
2495}
2496
2497} // end: extern "C"
2498
2499//===----------------------------------------------------------------------===//
2500// Token annotation APIs.
2501//===----------------------------------------------------------------------===//
2502
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002503typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002504static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
2505 CXCursor parent,
2506 CXClientData client_data);
Ted Kremenek6db61092010-05-05 00:55:15 +00002507namespace {
2508class AnnotateTokensWorker {
2509 AnnotateTokensData &Annotated;
Ted Kremenek11949cb2010-05-05 00:55:17 +00002510 CXToken *Tokens;
2511 CXCursor *Cursors;
2512 unsigned NumTokens;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002513 unsigned TokIdx;
2514 CursorVisitor AnnotateVis;
2515 SourceManager &SrcMgr;
2516
2517 bool MoreTokens() const { return TokIdx < NumTokens; }
2518 unsigned NextToken() const { return TokIdx; }
2519 void AdvanceToken() { ++TokIdx; }
2520 SourceLocation GetTokenLoc(unsigned tokI) {
2521 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
2522 }
2523
Ted Kremenek6db61092010-05-05 00:55:15 +00002524public:
Ted Kremenek11949cb2010-05-05 00:55:17 +00002525 AnnotateTokensWorker(AnnotateTokensData &annotated,
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002526 CXToken *tokens, CXCursor *cursors, unsigned numTokens,
2527 ASTUnit *CXXUnit, SourceRange RegionOfInterest)
Ted Kremenek11949cb2010-05-05 00:55:17 +00002528 : Annotated(annotated), Tokens(tokens), Cursors(cursors),
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002529 NumTokens(numTokens), TokIdx(0),
2530 AnnotateVis(CXXUnit, AnnotateTokensVisitor, this,
2531 Decl::MaxPCHLevel, RegionOfInterest),
2532 SrcMgr(CXXUnit->getSourceManager()) {}
Ted Kremenek11949cb2010-05-05 00:55:17 +00002533
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002534 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
Ted Kremenek6db61092010-05-05 00:55:15 +00002535 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002536 void AnnotateTokens(CXCursor parent);
Ted Kremenek6db61092010-05-05 00:55:15 +00002537};
2538}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002539
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002540void AnnotateTokensWorker::AnnotateTokens(CXCursor parent) {
2541 // Walk the AST within the region of interest, annotating tokens
2542 // along the way.
2543 VisitChildren(parent);
Ted Kremenek11949cb2010-05-05 00:55:17 +00002544
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002545 for (unsigned I = 0 ; I < TokIdx ; ++I) {
2546 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
2547 if (Pos != Annotated.end())
2548 Cursors[I] = Pos->second;
2549 }
2550
2551 // Finish up annotating any tokens left.
2552 if (!MoreTokens())
2553 return;
2554
2555 const CXCursor &C = clang_getNullCursor();
2556 for (unsigned I = TokIdx ; I < NumTokens ; ++I) {
2557 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
2558 Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second;
Ted Kremenek11949cb2010-05-05 00:55:17 +00002559 }
2560}
2561
Ted Kremenek6db61092010-05-05 00:55:15 +00002562enum CXChildVisitResult
2563AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002564 CXSourceLocation Loc = clang_getCursorLocation(cursor);
2565 // We can always annotate a preprocessing directive/macro instantiation.
2566 if (clang_isPreprocessing(cursor.kind)) {
2567 Annotated[Loc.int_data] = cursor;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002568 return CXChildVisit_Recurse;
2569 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002570
2571 CXSourceRange cursorExtent = clang_getCursorExtent(cursor);
2572 SourceRange cursorRange = cxloc::translateCXSourceRange(cursorExtent);
Ted Kremeneka333c662010-05-12 05:29:33 +00002573
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002574 if (cursorRange.isInvalid())
2575 return CXChildVisit_Continue;
Ted Kremeneka333c662010-05-12 05:29:33 +00002576
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002577 SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data);
2578
Ted Kremeneka333c662010-05-12 05:29:33 +00002579 // Adjust the annotated range based specific declarations.
2580 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
2581 if (cursorK >= CXCursor_FirstDecl && cursorK <= CXCursor_LastDecl) {
Ted Kremenek23173d72010-05-18 21:09:07 +00002582 Decl *D = cxcursor::getCursorDecl(cursor);
2583 // Don't visit synthesized ObjC methods, since they have no syntatic
2584 // representation in the source.
2585 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
2586 if (MD->isSynthesized())
2587 return CXChildVisit_Continue;
2588 }
2589 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
Ted Kremeneka333c662010-05-12 05:29:33 +00002590 if (TypeSourceInfo *TI = DD->getTypeSourceInfo()) {
2591 TypeLoc TL = TI->getTypeLoc();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00002592 SourceLocation TLoc = TL.getSourceRange().getBegin();
Ted Kremenek6bfd5332010-05-13 15:38:38 +00002593 if (TLoc.isValid() &&
2594 SrcMgr.isBeforeInTranslationUnit(TLoc, L))
Ted Kremeneka333c662010-05-12 05:29:33 +00002595 cursorRange.setBegin(TLoc);
Ted Kremeneka333c662010-05-12 05:29:33 +00002596 }
2597 }
2598 }
2599
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002600 const enum CXCursorKind K = clang_getCursorKind(parent);
2601 const CXCursor updateC =
2602 (clang_isInvalid(K) || K == CXCursor_TranslationUnit ||
2603 L.isMacroID())
2604 ? clang_getNullCursor() : parent;
2605
2606 while (MoreTokens()) {
2607 const unsigned I = NextToken();
2608 SourceLocation TokLoc = GetTokenLoc(I);
2609 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
2610 case RangeBefore:
2611 Cursors[I] = updateC;
2612 AdvanceToken();
2613 continue;
2614 case RangeAfter:
2615 return CXChildVisit_Continue;
2616 case RangeOverlap:
2617 break;
2618 }
2619 break;
2620 }
2621
2622 // Visit children to get their cursor information.
2623 const unsigned BeforeChildren = NextToken();
2624 VisitChildren(cursor);
2625 const unsigned AfterChildren = NextToken();
2626
2627 // Adjust 'Last' to the last token within the extent of the cursor.
2628 while (MoreTokens()) {
2629 const unsigned I = NextToken();
2630 SourceLocation TokLoc = GetTokenLoc(I);
2631 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
2632 case RangeBefore:
2633 assert(0 && "Infeasible");
2634 case RangeAfter:
2635 break;
2636 case RangeOverlap:
2637 Cursors[I] = updateC;
2638 AdvanceToken();
2639 continue;
2640 }
2641 break;
2642 }
2643 const unsigned Last = NextToken();
Ted Kremenek6db61092010-05-05 00:55:15 +00002644
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002645 // Scan the tokens that are at the beginning of the cursor, but are not
2646 // capture by the child cursors.
2647
2648 // For AST elements within macros, rely on a post-annotate pass to
2649 // to correctly annotate the tokens with cursors. Otherwise we can
2650 // get confusing results of having tokens that map to cursors that really
2651 // are expanded by an instantiation.
2652 if (L.isMacroID())
2653 cursor = clang_getNullCursor();
2654
2655 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
2656 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
2657 break;
2658 Cursors[I] = cursor;
2659 }
2660 // Scan the tokens that are at the end of the cursor, but are not captured
2661 // but the child cursors.
2662 for (unsigned I = AfterChildren; I != Last; ++I)
2663 Cursors[I] = cursor;
2664
2665 TokIdx = Last;
2666 return CXChildVisit_Continue;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002667}
2668
Ted Kremenek6db61092010-05-05 00:55:15 +00002669static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
2670 CXCursor parent,
2671 CXClientData client_data) {
2672 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
2673}
2674
2675extern "C" {
2676
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002677void clang_annotateTokens(CXTranslationUnit TU,
2678 CXToken *Tokens, unsigned NumTokens,
2679 CXCursor *Cursors) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002680
2681 if (NumTokens == 0 || !Tokens || !Cursors)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002682 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002683
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002684 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002685 if (!CXXUnit) {
2686 // Any token we don't specifically annotate will have a NULL cursor.
2687 const CXCursor &C = clang_getNullCursor();
2688 for (unsigned I = 0; I != NumTokens; ++I)
2689 Cursors[I] = C;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002690 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002691 }
2692
Douglas Gregorbdf60622010-03-05 21:16:25 +00002693 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002694
Douglas Gregor0396f462010-03-19 05:22:59 +00002695 // Determine the region of interest, which contains all of the tokens.
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002696 SourceRange RegionOfInterest;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002697 RegionOfInterest.setBegin(cxloc::translateSourceLocation(
2698 clang_getTokenLocation(TU, Tokens[0])));
2699
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002700 SourceLocation End
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002701 = cxloc::translateSourceLocation(clang_getTokenLocation(TU,
2702 Tokens[NumTokens - 1]));
Daniel Dunbard52864b2010-02-14 10:02:57 +00002703 RegionOfInterest.setEnd(CXXUnit->getPreprocessor().getLocForEndOfToken(End));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002704
Douglas Gregor0396f462010-03-19 05:22:59 +00002705 // A mapping from the source locations found when re-lexing or traversing the
2706 // region of interest to the corresponding cursors.
2707 AnnotateTokensData Annotated;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002708
2709 // Relex the tokens within the source range to look for preprocessing
Douglas Gregor0396f462010-03-19 05:22:59 +00002710 // directives.
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002711 SourceManager &SourceMgr = CXXUnit->getSourceManager();
2712 std::pair<FileID, unsigned> BeginLocInfo
2713 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
2714 std::pair<FileID, unsigned> EndLocInfo
2715 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002716
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002717 llvm::StringRef Buffer;
Douglas Gregor0396f462010-03-19 05:22:59 +00002718 bool Invalid = false;
2719 if (BeginLocInfo.first == EndLocInfo.first &&
2720 ((Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid)),true) &&
2721 !Invalid) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002722 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
2723 CXXUnit->getASTContext().getLangOptions(),
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002724 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002725 Buffer.end());
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002726 Lex.SetCommentRetentionState(true);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002727
2728 // Lex tokens in raw mode until we hit the end of the range, to avoid
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002729 // entering #includes or expanding macros.
Douglas Gregor48072312010-03-18 15:23:44 +00002730 while (true) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002731 Token Tok;
2732 Lex.LexFromRawLexer(Tok);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002733
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002734 reprocess:
2735 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
2736 // We have found a preprocessing directive. Gobble it up so that we
2737 // don't see it while preprocessing these tokens later, but keep track of
2738 // all of the token locations inside this preprocessing directive so that
2739 // we can annotate them appropriately.
2740 //
2741 // FIXME: Some simple tests here could identify macro definitions and
2742 // #undefs, to provide specific cursor kinds for those.
2743 std::vector<SourceLocation> Locations;
2744 do {
2745 Locations.push_back(Tok.getLocation());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002746 Lex.LexFromRawLexer(Tok);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002747 } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002748
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002749 using namespace cxcursor;
2750 CXCursor Cursor
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002751 = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
2752 Locations.back()),
Ted Kremenek6db61092010-05-05 00:55:15 +00002753 CXXUnit);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002754 for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
2755 Annotated[Locations[I].getRawEncoding()] = Cursor;
2756 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002757
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002758 if (Tok.isAtStartOfLine())
2759 goto reprocess;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002760
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002761 continue;
2762 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002763
Douglas Gregor48072312010-03-18 15:23:44 +00002764 if (Tok.is(tok::eof))
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002765 break;
2766 }
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002767 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002768
Douglas Gregor0396f462010-03-19 05:22:59 +00002769 // Annotate all of the source locations in the region of interest that map to
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002770 // a specific cursor.
2771 AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens,
2772 CXXUnit, RegionOfInterest);
2773 W.AnnotateTokens(clang_getTranslationUnitCursor(CXXUnit));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002774}
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002775} // end: extern "C"
2776
2777//===----------------------------------------------------------------------===//
Ted Kremenek16b42592010-03-03 06:36:57 +00002778// Operations for querying linkage of a cursor.
2779//===----------------------------------------------------------------------===//
2780
2781extern "C" {
2782CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
Douglas Gregor0396f462010-03-19 05:22:59 +00002783 if (!clang_isDeclaration(cursor.kind))
2784 return CXLinkage_Invalid;
2785
Ted Kremenek16b42592010-03-03 06:36:57 +00002786 Decl *D = cxcursor::getCursorDecl(cursor);
2787 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
2788 switch (ND->getLinkage()) {
2789 case NoLinkage: return CXLinkage_NoLinkage;
2790 case InternalLinkage: return CXLinkage_Internal;
2791 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
2792 case ExternalLinkage: return CXLinkage_External;
2793 };
2794
2795 return CXLinkage_Invalid;
2796}
2797} // end: extern "C"
2798
2799//===----------------------------------------------------------------------===//
Ted Kremenek45e1dae2010-04-12 21:22:16 +00002800// Operations for querying language of a cursor.
2801//===----------------------------------------------------------------------===//
2802
2803static CXLanguageKind getDeclLanguage(const Decl *D) {
2804 switch (D->getKind()) {
2805 default:
2806 break;
2807 case Decl::ImplicitParam:
2808 case Decl::ObjCAtDefsField:
2809 case Decl::ObjCCategory:
2810 case Decl::ObjCCategoryImpl:
2811 case Decl::ObjCClass:
2812 case Decl::ObjCCompatibleAlias:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00002813 case Decl::ObjCForwardProtocol:
2814 case Decl::ObjCImplementation:
2815 case Decl::ObjCInterface:
2816 case Decl::ObjCIvar:
2817 case Decl::ObjCMethod:
2818 case Decl::ObjCProperty:
2819 case Decl::ObjCPropertyImpl:
2820 case Decl::ObjCProtocol:
2821 return CXLanguage_ObjC;
2822 case Decl::CXXConstructor:
2823 case Decl::CXXConversion:
2824 case Decl::CXXDestructor:
2825 case Decl::CXXMethod:
2826 case Decl::CXXRecord:
2827 case Decl::ClassTemplate:
2828 case Decl::ClassTemplatePartialSpecialization:
2829 case Decl::ClassTemplateSpecialization:
2830 case Decl::Friend:
2831 case Decl::FriendTemplate:
2832 case Decl::FunctionTemplate:
2833 case Decl::LinkageSpec:
2834 case Decl::Namespace:
2835 case Decl::NamespaceAlias:
2836 case Decl::NonTypeTemplateParm:
2837 case Decl::StaticAssert:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00002838 case Decl::TemplateTemplateParm:
2839 case Decl::TemplateTypeParm:
2840 case Decl::UnresolvedUsingTypename:
2841 case Decl::UnresolvedUsingValue:
2842 case Decl::Using:
2843 case Decl::UsingDirective:
2844 case Decl::UsingShadow:
2845 return CXLanguage_CPlusPlus;
2846 }
2847
2848 return CXLanguage_C;
2849}
2850
2851extern "C" {
2852CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
2853 if (clang_isDeclaration(cursor.kind))
2854 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
2855
2856 return CXLanguage_Invalid;
2857}
2858} // end: extern "C"
2859
Ted Kremenek9ada39a2010-05-17 20:06:56 +00002860
2861//===----------------------------------------------------------------------===//
2862// C++ AST instrospection.
2863//===----------------------------------------------------------------------===//
2864
2865extern "C" {
2866unsigned clang_CXXMethod_isStatic(CXCursor C) {
2867 if (!clang_isDeclaration(C.kind))
2868 return 0;
2869 CXXMethodDecl *D = dyn_cast<CXXMethodDecl>(cxcursor::getCursorDecl(C));
2870 return (D && D->isStatic()) ? 1 : 0;
Ted Kremenek40b492a2010-05-17 20:12:45 +00002871}
Ted Kremenekb12903e2010-05-18 22:32:15 +00002872
Ted Kremenek9ada39a2010-05-17 20:06:56 +00002873} // end: extern "C"
2874
Ted Kremenek45e1dae2010-04-12 21:22:16 +00002875//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00002876// CXString Operations.
2877//===----------------------------------------------------------------------===//
2878
2879extern "C" {
2880const char *clang_getCString(CXString string) {
2881 return string.Spelling;
2882}
2883
2884void clang_disposeString(CXString string) {
2885 if (string.MustFreeString && string.Spelling)
2886 free((void*)string.Spelling);
2887}
Ted Kremenek04bb7162010-01-22 22:44:15 +00002888
Ted Kremenekfb480492010-01-13 21:46:36 +00002889} // end: extern "C"
Ted Kremenek04bb7162010-01-22 22:44:15 +00002890
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002891namespace clang { namespace cxstring {
2892CXString createCXString(const char *String, bool DupString){
2893 CXString Str;
2894 if (DupString) {
2895 Str.Spelling = strdup(String);
2896 Str.MustFreeString = 1;
2897 } else {
2898 Str.Spelling = String;
2899 Str.MustFreeString = 0;
2900 }
2901 return Str;
2902}
2903
2904CXString createCXString(llvm::StringRef String, bool DupString) {
2905 CXString Result;
2906 if (DupString || (!String.empty() && String.data()[String.size()] != 0)) {
2907 char *Spelling = (char *)malloc(String.size() + 1);
2908 memmove(Spelling, String.data(), String.size());
2909 Spelling[String.size()] = 0;
2910 Result.Spelling = Spelling;
2911 Result.MustFreeString = 1;
2912 } else {
2913 Result.Spelling = String.data();
2914 Result.MustFreeString = 0;
2915 }
2916 return Result;
2917}
2918}}
2919
Ted Kremenek04bb7162010-01-22 22:44:15 +00002920//===----------------------------------------------------------------------===//
2921// Misc. utility functions.
2922//===----------------------------------------------------------------------===//
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002923
Ted Kremenek04bb7162010-01-22 22:44:15 +00002924extern "C" {
2925
Ted Kremeneka2a9d6e2010-02-12 22:54:40 +00002926CXString clang_getClangVersion() {
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002927 return createCXString(getClangFullVersion());
Ted Kremenek04bb7162010-01-22 22:44:15 +00002928}
2929
2930} // end: extern "C"