blob: 1b3c6a2c73bcc3581efdd7e5a78dfe4cea989e64 [file] [log] [blame]
Ted Kremenekd2fa5662009-08-26 22:36:44 +00001//===- CIndex.cpp - Clang-C Source Indexing Library -----------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00007//
Ted Kremenekd2fa5662009-08-26 22:36:44 +00008//===----------------------------------------------------------------------===//
9//
Ted Kremenekab188932010-01-05 19:32:54 +000010// This file implements the main API hooks in the Clang-C Source Indexing
11// library.
Ted Kremenekd2fa5662009-08-26 22:36:44 +000012//
13//===----------------------------------------------------------------------===//
14
Ted Kremenekab188932010-01-05 19:32:54 +000015#include "CIndexer.h"
Ted Kremenek16c440a2010-01-15 20:35:54 +000016#include "CXCursor.h"
Ted Kremeneka297de22010-01-25 22:34:44 +000017#include "CXSourceLocation.h"
Douglas Gregor5352ac02010-01-28 00:27:43 +000018#include "CIndexDiagnostic.h"
Ted Kremenekab188932010-01-05 19:32:54 +000019
Ted Kremenek04bb7162010-01-22 22:44:15 +000020#include "clang/Basic/Version.h"
Douglas Gregor936ea3b2010-01-28 00:56:43 +000021
Steve Naroff50398192009-08-28 15:28:48 +000022#include "clang/AST/DeclVisitor.h"
Steve Narofffb570422009-09-22 19:25:29 +000023#include "clang/AST/StmtVisitor.h"
Douglas Gregor7d0d40e2010-01-21 16:28:34 +000024#include "clang/AST/TypeLocVisitor.h"
Benjamin Kramerb846deb2010-04-12 19:45:50 +000025#include "clang/Basic/Diagnostic.h"
26#include "clang/Frontend/ASTUnit.h"
27#include "clang/Frontend/CompilerInstance.h"
Douglas Gregor936ea3b2010-01-28 00:56:43 +000028#include "clang/Frontend/FrontendDiagnostic.h"
Ted Kremenekd8210652010-01-06 23:43:31 +000029#include "clang/Lex/Lexer.h"
Benjamin Kramerb846deb2010-04-12 19:45:50 +000030#include "clang/Lex/PreprocessingRecord.h"
Douglas Gregor33e9abd2010-01-22 19:49:59 +000031#include "clang/Lex/Preprocessor.h"
Douglas Gregor02465752009-10-16 21:24:31 +000032#include "llvm/Support/MemoryBuffer.h"
Benjamin Kramer0829a832009-10-18 11:19:36 +000033#include "llvm/System/Program.h"
Douglas Gregor0a812cf2010-02-18 23:07:20 +000034#include "llvm/System/Signals.h"
Ted Kremenekfc062212009-10-19 21:44:57 +000035
Benjamin Kramerc2a98162010-03-13 21:22:49 +000036// Needed to define L_TMPNAM on some systems.
37#include <cstdio>
38
Steve Naroff50398192009-08-28 15:28:48 +000039using namespace clang;
Ted Kremenek16c440a2010-01-15 20:35:54 +000040using namespace clang::cxcursor;
Ted Kremenekee4db4f2010-02-17 00:41:08 +000041using namespace clang::cxstring;
Steve Naroff50398192009-08-28 15:28:48 +000042
Ted Kremenek8a8da7d2010-01-06 03:42:32 +000043//===----------------------------------------------------------------------===//
44// Crash Reporting.
45//===----------------------------------------------------------------------===//
46
Ted Kremenekd7ffd082010-05-22 00:06:46 +000047#ifdef USE_CRASHTRACER
Ted Kremenek8a8da7d2010-01-06 03:42:32 +000048#include "clang/Analysis/Support/SaveAndRestore.h"
49// Integrate with crash reporter.
Daniel Dunbar439794e2010-05-20 23:50:23 +000050static const char *__crashreporter_info__ = 0;
51asm(".desc ___crashreporter_info__, 0x10");
Ted Kremenek6b569992010-02-17 21:12:23 +000052#define NUM_CRASH_STRINGS 32
Ted Kremenek29b72842010-01-07 22:49:05 +000053static unsigned crashtracer_counter = 0;
Ted Kremenek254ba7c2010-01-07 23:13:53 +000054static unsigned crashtracer_counter_id[NUM_CRASH_STRINGS] = { 0 };
Ted Kremenek29b72842010-01-07 22:49:05 +000055static const char *crashtracer_strings[NUM_CRASH_STRINGS] = { 0 };
56static const char *agg_crashtracer_strings[NUM_CRASH_STRINGS] = { 0 };
57
58static unsigned SetCrashTracerInfo(const char *str,
59 llvm::SmallString<1024> &AggStr) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +000060
Ted Kremenek254ba7c2010-01-07 23:13:53 +000061 unsigned slot = 0;
Ted Kremenek29b72842010-01-07 22:49:05 +000062 while (crashtracer_strings[slot]) {
63 if (++slot == NUM_CRASH_STRINGS)
64 slot = 0;
65 }
66 crashtracer_strings[slot] = str;
Ted Kremenek254ba7c2010-01-07 23:13:53 +000067 crashtracer_counter_id[slot] = ++crashtracer_counter;
Ted Kremenek29b72842010-01-07 22:49:05 +000068
69 // We need to create an aggregate string because multiple threads
70 // may be in this method at one time. The crash reporter string
71 // will attempt to overapproximate the set of in-flight invocations
72 // of this function. Race conditions can still cause this goal
73 // to not be achieved.
74 {
Ted Kremenekf0e23e82010-02-17 00:41:40 +000075 llvm::raw_svector_ostream Out(AggStr);
Ted Kremenek29b72842010-01-07 22:49:05 +000076 for (unsigned i = 0; i < NUM_CRASH_STRINGS; ++i)
77 if (crashtracer_strings[i]) Out << crashtracer_strings[i] << '\n';
78 }
79 __crashreporter_info__ = agg_crashtracer_strings[slot] = AggStr.c_str();
80 return slot;
81}
82
83static void ResetCrashTracerInfo(unsigned slot) {
Ted Kremenek254ba7c2010-01-07 23:13:53 +000084 unsigned max_slot = 0;
85 unsigned max_value = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +000086
Ted Kremenek254ba7c2010-01-07 23:13:53 +000087 crashtracer_strings[slot] = agg_crashtracer_strings[slot] = 0;
88
89 for (unsigned i = 0 ; i < NUM_CRASH_STRINGS; ++i)
90 if (agg_crashtracer_strings[i] &&
91 crashtracer_counter_id[i] > max_value) {
92 max_slot = i;
93 max_value = crashtracer_counter_id[i];
Ted Kremenek29b72842010-01-07 22:49:05 +000094 }
Ted Kremenek254ba7c2010-01-07 23:13:53 +000095
96 __crashreporter_info__ = agg_crashtracer_strings[max_slot];
Ted Kremenek29b72842010-01-07 22:49:05 +000097}
98
99namespace {
100class ArgsCrashTracerInfo {
101 llvm::SmallString<1024> CrashString;
102 llvm::SmallString<1024> AggregateString;
103 unsigned crashtracerSlot;
104public:
105 ArgsCrashTracerInfo(llvm::SmallVectorImpl<const char*> &Args)
106 : crashtracerSlot(0)
107 {
108 {
109 llvm::raw_svector_ostream Out(CrashString);
Ted Kremenek0baa9522010-03-05 22:43:25 +0000110 Out << "ClangCIndex [" << getClangFullVersion() << "]"
111 << "[createTranslationUnitFromSourceFile]: clang";
Ted Kremenek29b72842010-01-07 22:49:05 +0000112 for (llvm::SmallVectorImpl<const char*>::iterator I=Args.begin(),
113 E=Args.end(); I!=E; ++I)
114 Out << ' ' << *I;
115 }
116 crashtracerSlot = SetCrashTracerInfo(CrashString.c_str(),
117 AggregateString);
118 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000119
Ted Kremenek29b72842010-01-07 22:49:05 +0000120 ~ArgsCrashTracerInfo() {
121 ResetCrashTracerInfo(crashtracerSlot);
122 }
123};
124}
125#endif
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000126
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000127/// \brief The result of comparing two source ranges.
128enum RangeComparisonResult {
129 /// \brief Either the ranges overlap or one of the ranges is invalid.
130 RangeOverlap,
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000131
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000132 /// \brief The first range ends before the second range starts.
133 RangeBefore,
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000134
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000135 /// \brief The first range starts after the second range ends.
136 RangeAfter
137};
138
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000139/// \brief Compare two source ranges to determine their relative position in
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000140/// the translation unit.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000141static RangeComparisonResult RangeCompare(SourceManager &SM,
142 SourceRange R1,
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000143 SourceRange R2) {
144 assert(R1.isValid() && "First range is invalid?");
145 assert(R2.isValid() && "Second range is invalid?");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000146 if (R1.getEnd() != R2.getBegin() &&
Daniel Dunbard52864b2010-02-14 10:02:57 +0000147 SM.isBeforeInTranslationUnit(R1.getEnd(), R2.getBegin()))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000148 return RangeBefore;
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000149 if (R2.getEnd() != R1.getBegin() &&
Daniel Dunbard52864b2010-02-14 10:02:57 +0000150 SM.isBeforeInTranslationUnit(R2.getEnd(), R1.getBegin()))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000151 return RangeAfter;
152 return RangeOverlap;
153}
154
Ted Kremenekfbd84ca2010-05-05 00:55:23 +0000155/// \brief Determine if a source location falls within, before, or after a
156/// a given source range.
157static RangeComparisonResult LocationCompare(SourceManager &SM,
158 SourceLocation L, SourceRange R) {
159 assert(R.isValid() && "First range is invalid?");
160 assert(L.isValid() && "Second range is invalid?");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000161 if (L == R.getBegin() || L == R.getEnd())
Ted Kremenekfbd84ca2010-05-05 00:55:23 +0000162 return RangeOverlap;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +0000163 if (SM.isBeforeInTranslationUnit(L, R.getBegin()))
164 return RangeBefore;
165 if (SM.isBeforeInTranslationUnit(R.getEnd(), L))
166 return RangeAfter;
167 return RangeOverlap;
168}
169
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000170/// \brief Translate a Clang source range into a CIndex source range.
171///
172/// Clang internally represents ranges where the end location points to the
173/// start of the token at the end. However, for external clients it is more
174/// useful to have a CXSourceRange be a proper half-open interval. This routine
175/// does the appropriate translation.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000176CXSourceRange cxloc::translateSourceRange(const SourceManager &SM,
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000177 const LangOptions &LangOpts,
Chris Lattner0a76aae2010-06-18 22:45:06 +0000178 const CharSourceRange &R) {
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000179 // We want the last character in this location, so we will adjust the
Douglas Gregor6a5a23f2010-03-19 21:51:54 +0000180 // location accordingly.
181 // FIXME: How do do this with a macro instantiation location?
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000182 SourceLocation EndLoc = R.getEnd();
Chris Lattner0a76aae2010-06-18 22:45:06 +0000183 if (R.isTokenRange() && !EndLoc.isInvalid() && EndLoc.isFileID()) {
Douglas Gregor6a5a23f2010-03-19 21:51:54 +0000184 unsigned Length = Lexer::MeasureTokenLength(EndLoc, SM, LangOpts);
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000185 EndLoc = EndLoc.getFileLocWithOffset(Length);
186 }
187
188 CXSourceRange Result = { { (void *)&SM, (void *)&LangOpts },
189 R.getBegin().getRawEncoding(),
190 EndLoc.getRawEncoding() };
191 return Result;
192}
Douglas Gregor1db19de2010-01-19 21:36:55 +0000193
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000194//===----------------------------------------------------------------------===//
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000195// Cursor visitor.
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000196//===----------------------------------------------------------------------===//
197
Steve Naroff89922f82009-08-31 00:59:03 +0000198namespace {
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000199
Douglas Gregorb1373d02010-01-20 20:59:29 +0000200// Cursor visitor.
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000201class CursorVisitor : public DeclVisitor<CursorVisitor, bool>,
Douglas Gregora59e3902010-01-21 23:27:09 +0000202 public TypeLocVisitor<CursorVisitor, bool>,
203 public StmtVisitor<CursorVisitor, bool>
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000204{
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000205 /// \brief The translation unit we are traversing.
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000206 ASTUnit *TU;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000207
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000208 /// \brief The parent cursor whose children we are traversing.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000209 CXCursor Parent;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000210
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000211 /// \brief The declaration that serves at the parent of any statement or
212 /// expression nodes.
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000213 Decl *StmtParent;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000214
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000215 /// \brief The visitor function.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000216 CXCursorVisitor Visitor;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000217
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000218 /// \brief The opaque client data, to be passed along to the visitor.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000219 CXClientData ClientData;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000220
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000221 // MaxPCHLevel - the maximum PCH level of declarations that we will pass on
222 // to the visitor. Declarations with a PCH level greater than this value will
223 // be suppressed.
224 unsigned MaxPCHLevel;
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000225
226 /// \brief When valid, a source range to which the cursor should restrict
227 /// its search.
228 SourceRange RegionOfInterest;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000229
Douglas Gregorb1373d02010-01-20 20:59:29 +0000230 using DeclVisitor<CursorVisitor, bool>::Visit;
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000231 using TypeLocVisitor<CursorVisitor, bool>::Visit;
Douglas Gregora59e3902010-01-21 23:27:09 +0000232 using StmtVisitor<CursorVisitor, bool>::Visit;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000233
234 /// \brief Determine whether this particular source range comes before, comes
235 /// after, or overlaps the region of interest.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000236 ///
Daniel Dunbard52864b2010-02-14 10:02:57 +0000237 /// \param R a half-open source range retrieved from the abstract syntax tree.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000238 RangeComparisonResult CompareRegionOfInterest(SourceRange R);
239
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000240 class SetParentRAII {
241 CXCursor &Parent;
242 Decl *&StmtParent;
243 CXCursor OldParent;
244
245 public:
246 SetParentRAII(CXCursor &Parent, Decl *&StmtParent, CXCursor NewParent)
247 : Parent(Parent), StmtParent(StmtParent), OldParent(Parent)
248 {
249 Parent = NewParent;
250 if (clang_isDeclaration(Parent.kind))
251 StmtParent = getCursorDecl(Parent);
252 }
253
254 ~SetParentRAII() {
255 Parent = OldParent;
256 if (clang_isDeclaration(Parent.kind))
257 StmtParent = getCursorDecl(Parent);
258 }
259 };
260
Steve Naroff89922f82009-08-31 00:59:03 +0000261public:
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000262 CursorVisitor(ASTUnit *TU, CXCursorVisitor Visitor, CXClientData ClientData,
263 unsigned MaxPCHLevel,
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000264 SourceRange RegionOfInterest = SourceRange())
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000265 : TU(TU), Visitor(Visitor), ClientData(ClientData),
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000266 MaxPCHLevel(MaxPCHLevel), RegionOfInterest(RegionOfInterest)
Douglas Gregorb1373d02010-01-20 20:59:29 +0000267 {
268 Parent.kind = CXCursor_NoDeclFound;
269 Parent.data[0] = 0;
270 Parent.data[1] = 0;
271 Parent.data[2] = 0;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000272 StmtParent = 0;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000273 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000274
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000275 bool Visit(CXCursor Cursor, bool CheckedRegionOfInterest = false);
Douglas Gregor788f5a12010-03-20 00:41:21 +0000276
277 std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
278 getPreprocessedEntities();
279
Douglas Gregorb1373d02010-01-20 20:59:29 +0000280 bool VisitChildren(CXCursor Parent);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000281
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000282 // Declaration visitors
Ted Kremenek09dfa372010-02-18 05:46:33 +0000283 bool VisitAttributes(Decl *D);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000284 bool VisitBlockDecl(BlockDecl *B);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000285 bool VisitDeclContext(DeclContext *DC);
Ted Kremenek4540c9c2010-02-18 18:47:08 +0000286 bool VisitTranslationUnitDecl(TranslationUnitDecl *D);
287 bool VisitTypedefDecl(TypedefDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000288 bool VisitTagDecl(TagDecl *D);
289 bool VisitEnumConstantDecl(EnumConstantDecl *D);
290 bool VisitDeclaratorDecl(DeclaratorDecl *DD);
291 bool VisitFunctionDecl(FunctionDecl *ND);
292 bool VisitFieldDecl(FieldDecl *D);
Ted Kremenek4540c9c2010-02-18 18:47:08 +0000293 bool VisitVarDecl(VarDecl *);
Ted Kremenek79758f62010-02-18 22:36:18 +0000294 bool VisitObjCMethodDecl(ObjCMethodDecl *ND);
295 bool VisitObjCContainerDecl(ObjCContainerDecl *D);
296 bool VisitObjCCategoryDecl(ObjCCategoryDecl *ND);
297 bool VisitObjCProtocolDecl(ObjCProtocolDecl *PID);
Ted Kremenek23173d72010-05-18 21:09:07 +0000298 bool VisitObjCPropertyDecl(ObjCPropertyDecl *PD);
Ted Kremenek79758f62010-02-18 22:36:18 +0000299 bool VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
300 bool VisitObjCImplDecl(ObjCImplDecl *D);
301 bool VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
302 bool VisitObjCImplementationDecl(ObjCImplementationDecl *D);
303 // FIXME: ObjCPropertyDecl requires TypeSourceInfo, getter/setter locations,
304 // etc.
305 // FIXME: ObjCCompatibleAliasDecl requires aliased-class locations.
306 bool VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D);
307 bool VisitObjCClassDecl(ObjCClassDecl *D);
Ted Kremeneka0536d82010-05-07 01:04:29 +0000308 bool VisitLinkageSpecDecl(LinkageSpecDecl *D);
Ted Kremenek8f06e0e2010-05-06 23:38:21 +0000309 bool VisitNamespaceDecl(NamespaceDecl *D);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000310
311 // Type visitors
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000312 // FIXME: QualifiedTypeLoc doesn't provide any location information
313 bool VisitBuiltinTypeLoc(BuiltinTypeLoc TL);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000314 bool VisitTypedefTypeLoc(TypedefTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000315 bool VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL);
316 bool VisitTagTypeLoc(TagTypeLoc TL);
317 // FIXME: TemplateTypeParmTypeLoc doesn't provide any location information
318 bool VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL);
John McCallc12c5bb2010-05-15 11:32:37 +0000319 bool VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000320 bool VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL);
321 bool VisitPointerTypeLoc(PointerTypeLoc TL);
322 bool VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL);
323 bool VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL);
324 bool VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL);
325 bool VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL);
326 bool VisitFunctionTypeLoc(FunctionTypeLoc TL);
327 bool VisitArrayTypeLoc(ArrayTypeLoc TL);
Douglas Gregor2332c112010-01-21 20:48:56 +0000328 // FIXME: Implement for TemplateSpecializationTypeLoc
329 // FIXME: Implement visitors here when the unimplemented TypeLocs get
330 // implemented
331 bool VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL);
332 bool VisitTypeOfTypeLoc(TypeOfTypeLoc TL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000333
Douglas Gregora59e3902010-01-21 23:27:09 +0000334 // Statement visitors
335 bool VisitStmt(Stmt *S);
336 bool VisitDeclStmt(DeclStmt *S);
Douglas Gregorf5bab412010-01-22 01:00:11 +0000337 // FIXME: LabelStmt label?
338 bool VisitIfStmt(IfStmt *S);
339 bool VisitSwitchStmt(SwitchStmt *S);
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000340 bool VisitCaseStmt(CaseStmt *S);
Douglas Gregor263b47b2010-01-25 16:12:32 +0000341 bool VisitWhileStmt(WhileStmt *S);
342 bool VisitForStmt(ForStmt *S);
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000343// bool VisitSwitchCase(SwitchCase *S);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000344
Douglas Gregor336fd812010-01-23 00:40:08 +0000345 // Expression visitors
Douglas Gregor6cd24e22010-07-29 00:26:18 +0000346 bool VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000347 bool VisitBlockExpr(BlockExpr *B);
Douglas Gregor336fd812010-01-23 00:40:08 +0000348 bool VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000349 bool VisitExplicitCastExpr(ExplicitCastExpr *E);
Douglas Gregorc2350e52010-03-08 16:40:19 +0000350 bool VisitObjCMessageExpr(ObjCMessageExpr *E);
Douglas Gregor81d34662010-04-20 15:39:42 +0000351 bool VisitObjCEncodeExpr(ObjCEncodeExpr *E);
Douglas Gregor8ecdb652010-04-28 22:16:22 +0000352 bool VisitOffsetOfExpr(OffsetOfExpr *E);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000353 bool VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E);
Steve Naroff89922f82009-08-31 00:59:03 +0000354};
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000355
Ted Kremenekab188932010-01-05 19:32:54 +0000356} // end anonymous namespace
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000357
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000358static SourceRange getRawCursorExtent(CXCursor C);
359
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000360RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000361 return RangeCompare(TU->getSourceManager(), R, RegionOfInterest);
362}
363
Douglas Gregorb1373d02010-01-20 20:59:29 +0000364/// \brief Visit the given cursor and, if requested by the visitor,
365/// its children.
366///
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000367/// \param Cursor the cursor to visit.
368///
369/// \param CheckRegionOfInterest if true, then the caller already checked that
370/// this cursor is within the region of interest.
371///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000372/// \returns true if the visitation should be aborted, false if it
373/// should continue.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000374bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
Douglas Gregorb1373d02010-01-20 20:59:29 +0000375 if (clang_isInvalid(Cursor.kind))
376 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000377
Douglas Gregorb1373d02010-01-20 20:59:29 +0000378 if (clang_isDeclaration(Cursor.kind)) {
379 Decl *D = getCursorDecl(Cursor);
380 assert(D && "Invalid declaration cursor");
381 if (D->getPCHLevel() > MaxPCHLevel)
382 return false;
383
384 if (D->isImplicit())
385 return false;
386 }
387
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000388 // If we have a range of interest, and this cursor doesn't intersect with it,
389 // we're done.
390 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000391 SourceRange Range = getRawCursorExtent(Cursor);
Daniel Dunbarf408f322010-02-14 08:32:05 +0000392 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()) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000540 SourceRange Range = getRawCursorExtent(Cursor);
Daniel Dunbard52864b2010-02-14 10:02:57 +0000541 if (Range.isInvalid())
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000542 continue;
Daniel Dunbard52864b2010-02-14 10:02:57 +0000543
544 switch (CompareRegionOfInterest(Range)) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000545 case RangeBefore:
546 // This declaration comes before the region of interest; skip it.
547 continue;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000548
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000549 case RangeAfter:
550 // This declaration comes after the region of interest; we're done.
551 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000552
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000553 case RangeOverlap:
554 // This declaration overlaps the region of interest; visit it.
555 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000556 }
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000557 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000558
Daniel Dunbard52864b2010-02-14 10:02:57 +0000559 if (Visit(Cursor, true))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000560 return true;
561 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000562
Douglas Gregorb1373d02010-01-20 20:59:29 +0000563 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000564}
565
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000566bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
567 llvm_unreachable("Translation units are visited directly by Visit()");
568 return false;
569}
570
571bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
572 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
573 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000574
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000575 return false;
576}
577
578bool CursorVisitor::VisitTagDecl(TagDecl *D) {
579 return VisitDeclContext(D);
580}
581
582bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
583 if (Expr *Init = D->getInitExpr())
584 return Visit(MakeCXCursor(Init, StmtParent, TU));
585 return false;
586}
587
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000588bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
589 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
590 if (Visit(TSInfo->getTypeLoc()))
591 return true;
592
593 return false;
594}
595
Douglas Gregorb1373d02010-01-20 20:59:29 +0000596bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000597 if (VisitDeclaratorDecl(ND))
598 return true;
599
Douglas Gregora59e3902010-01-21 23:27:09 +0000600 if (ND->isThisDeclarationADefinition() &&
601 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
602 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000603
Douglas Gregorb1373d02010-01-20 20:59:29 +0000604 return false;
605}
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000606
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000607bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
608 if (VisitDeclaratorDecl(D))
609 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000610
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000611 if (Expr *BitWidth = D->getBitWidth())
612 return Visit(MakeCXCursor(BitWidth, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000613
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000614 return false;
615}
616
617bool CursorVisitor::VisitVarDecl(VarDecl *D) {
618 if (VisitDeclaratorDecl(D))
619 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000620
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000621 if (Expr *Init = D->getInit())
622 return Visit(MakeCXCursor(Init, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000623
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000624 return false;
625}
626
627bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
Douglas Gregor4bc1cb62010-03-08 14:59:44 +0000628 if (TypeSourceInfo *TSInfo = ND->getResultTypeSourceInfo())
629 if (Visit(TSInfo->getTypeLoc()))
630 return true;
631
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000632 for (ObjCMethodDecl::param_iterator P = ND->param_begin(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000633 PEnd = ND->param_end();
634 P != PEnd; ++P) {
635 if (Visit(MakeCXCursor(*P, TU)))
636 return true;
637 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000638
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000639 if (ND->isThisDeclarationADefinition() &&
640 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
641 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000642
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000643 return false;
644}
645
Douglas Gregora59e3902010-01-21 23:27:09 +0000646bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
647 return VisitDeclContext(D);
648}
649
Douglas Gregorb1373d02010-01-20 20:59:29 +0000650bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000651 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
652 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000653 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000654
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000655 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
656 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
657 E = ND->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000658 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000659 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000660
Douglas Gregora59e3902010-01-21 23:27:09 +0000661 return VisitObjCContainerDecl(ND);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000662}
663
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000664bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
665 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
666 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
667 E = PID->protocol_end(); I != E; ++I, ++PL)
668 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
669 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000670
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000671 return VisitObjCContainerDecl(PID);
672}
673
Ted Kremenek23173d72010-05-18 21:09:07 +0000674bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
John McCallfc929202010-06-04 22:33:30 +0000675 if (Visit(PD->getTypeSourceInfo()->getTypeLoc()))
676 return true;
677
Ted Kremenek23173d72010-05-18 21:09:07 +0000678 // FIXME: This implements a workaround with @property declarations also being
679 // installed in the DeclContext for the @interface. Eventually this code
680 // should be removed.
681 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
682 if (!CDecl || !CDecl->IsClassExtension())
683 return false;
684
685 ObjCInterfaceDecl *ID = CDecl->getClassInterface();
686 if (!ID)
687 return false;
688
689 IdentifierInfo *PropertyId = PD->getIdentifier();
690 ObjCPropertyDecl *prevDecl =
691 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId);
692
693 if (!prevDecl)
694 return false;
695
696 // Visit synthesized methods since they will be skipped when visiting
697 // the @interface.
698 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
699 if (MD->isSynthesized())
700 if (Visit(MakeCXCursor(MD, TU)))
701 return true;
702
703 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
704 if (MD->isSynthesized())
705 if (Visit(MakeCXCursor(MD, TU)))
706 return true;
707
708 return false;
709}
710
Douglas Gregorb1373d02010-01-20 20:59:29 +0000711bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000712 // Issue callbacks for super class.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000713 if (D->getSuperClass() &&
714 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000715 D->getSuperClassLoc(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000716 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000717 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000718
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000719 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
720 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
721 E = D->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000722 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000723 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000724
Douglas Gregora59e3902010-01-21 23:27:09 +0000725 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000726}
727
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000728bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
729 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000730}
731
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000732bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
Ted Kremenekebfa3392010-03-19 20:39:03 +0000733 // 'ID' could be null when dealing with invalid code.
734 if (ObjCInterfaceDecl *ID = D->getClassInterface())
735 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
736 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000737
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000738 return VisitObjCImplDecl(D);
739}
740
741bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
742#if 0
743 // Issue callbacks for super class.
744 // FIXME: No source location information!
745 if (D->getSuperClass() &&
746 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000747 D->getSuperClassLoc(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000748 TU)))
749 return true;
750#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000751
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000752 return VisitObjCImplDecl(D);
753}
754
755bool CursorVisitor::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D) {
756 ObjCForwardProtocolDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
757 for (ObjCForwardProtocolDecl::protocol_iterator I = D->protocol_begin(),
758 E = D->protocol_end();
759 I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000760 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000761 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000762
763 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000764}
765
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000766bool CursorVisitor::VisitObjCClassDecl(ObjCClassDecl *D) {
767 for (ObjCClassDecl::iterator C = D->begin(), CEnd = D->end(); C != CEnd; ++C)
768 if (Visit(MakeCursorObjCClassRef(C->getInterface(), C->getLocation(), TU)))
769 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000770
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000771 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000772}
773
Ted Kremenek8f06e0e2010-05-06 23:38:21 +0000774bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
775 return VisitDeclContext(D);
776}
777
Ted Kremeneka0536d82010-05-07 01:04:29 +0000778bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
779 return VisitDeclContext(D);
780}
781
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000782bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
783 ASTContext &Context = TU->getASTContext();
784
785 // Some builtin types (such as Objective-C's "id", "sel", and
786 // "Class") have associated declarations. Create cursors for those.
787 QualType VisitType;
788 switch (TL.getType()->getAs<BuiltinType>()->getKind()) {
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000789 case BuiltinType::Void:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000790 case BuiltinType::Bool:
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000791 case BuiltinType::Char_U:
792 case BuiltinType::UChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000793 case BuiltinType::Char16:
794 case BuiltinType::Char32:
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000795 case BuiltinType::UShort:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000796 case BuiltinType::UInt:
797 case BuiltinType::ULong:
798 case BuiltinType::ULongLong:
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000799 case BuiltinType::UInt128:
800 case BuiltinType::Char_S:
801 case BuiltinType::SChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000802 case BuiltinType::WChar:
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000803 case BuiltinType::Short:
804 case BuiltinType::Int:
805 case BuiltinType::Long:
806 case BuiltinType::LongLong:
807 case BuiltinType::Int128:
808 case BuiltinType::Float:
809 case BuiltinType::Double:
810 case BuiltinType::LongDouble:
811 case BuiltinType::NullPtr:
812 case BuiltinType::Overload:
813 case BuiltinType::Dependent:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000814 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000815
816 case BuiltinType::UndeducedAuto: // FIXME: Deserves a cursor?
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000817 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000818
Ted Kremenekc4174cc2010-02-18 18:52:18 +0000819 case BuiltinType::ObjCId:
820 VisitType = Context.getObjCIdType();
821 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000822
823 case BuiltinType::ObjCClass:
824 VisitType = Context.getObjCClassType();
825 break;
826
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000827 case BuiltinType::ObjCSel:
828 VisitType = Context.getObjCSelType();
829 break;
830 }
831
832 if (!VisitType.isNull()) {
833 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000834 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000835 TU));
836 }
837
838 return false;
839}
840
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000841bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
842 return Visit(MakeCursorTypeRef(TL.getTypedefDecl(), TL.getNameLoc(), TU));
843}
844
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000845bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
846 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
847}
848
849bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
850 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
851}
852
853bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
854 if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
855 return true;
856
John McCallc12c5bb2010-05-15 11:32:37 +0000857 return false;
858}
859
860bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
861 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
862 return true;
863
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000864 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
865 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
866 TU)))
867 return true;
868 }
869
870 return false;
871}
872
873bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
John McCallc12c5bb2010-05-15 11:32:37 +0000874 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000875}
876
877bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
878 return Visit(TL.getPointeeLoc());
879}
880
881bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
882 return Visit(TL.getPointeeLoc());
883}
884
885bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
886 return Visit(TL.getPointeeLoc());
887}
888
889bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000890 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000891}
892
893bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000894 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000895}
896
897bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
898 if (Visit(TL.getResultLoc()))
899 return true;
900
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000901 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
Ted Kremenek5dbacb42010-04-07 00:27:13 +0000902 if (Decl *D = TL.getArg(I))
903 if (Visit(MakeCXCursor(D, TU)))
904 return true;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000905
906 return false;
907}
908
909bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
910 if (Visit(TL.getElementLoc()))
911 return true;
912
913 if (Expr *Size = TL.getSizeExpr())
914 return Visit(MakeCXCursor(Size, StmtParent, TU));
915
916 return false;
917}
918
Douglas Gregor2332c112010-01-21 20:48:56 +0000919bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
920 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
921}
922
923bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
924 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
925 return Visit(TSInfo->getTypeLoc());
926
927 return false;
928}
929
Douglas Gregora59e3902010-01-21 23:27:09 +0000930bool CursorVisitor::VisitStmt(Stmt *S) {
931 for (Stmt::child_iterator Child = S->child_begin(), ChildEnd = S->child_end();
932 Child != ChildEnd; ++Child) {
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000933 if (Stmt *C = *Child)
934 if (Visit(MakeCXCursor(C, StmtParent, TU)))
935 return true;
Douglas Gregora59e3902010-01-21 23:27:09 +0000936 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000937
Douglas Gregora59e3902010-01-21 23:27:09 +0000938 return false;
939}
940
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000941bool CursorVisitor::VisitCaseStmt(CaseStmt *S) {
942 // Specially handle CaseStmts because they can be nested, e.g.:
943 //
944 // case 1:
945 // case 2:
946 //
947 // In this case the second CaseStmt is the child of the first. Walking
948 // these recursively can blow out the stack.
949 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU);
950 while (true) {
951 // Set the Parent field to Cursor, then back to its old value once we're
952 // done.
953 SetParentRAII SetParent(Parent, StmtParent, Cursor);
954
955 if (Stmt *LHS = S->getLHS())
956 if (Visit(MakeCXCursor(LHS, StmtParent, TU)))
957 return true;
958 if (Stmt *RHS = S->getRHS())
959 if (Visit(MakeCXCursor(RHS, StmtParent, TU)))
960 return true;
961 if (Stmt *SubStmt = S->getSubStmt()) {
962 if (!isa<CaseStmt>(SubStmt))
963 return Visit(MakeCXCursor(SubStmt, StmtParent, TU));
964
965 // Specially handle 'CaseStmt' so that we don't blow out the stack.
966 CaseStmt *CS = cast<CaseStmt>(SubStmt);
967 Cursor = MakeCXCursor(CS, StmtParent, TU);
968 if (RegionOfInterest.isValid()) {
969 SourceRange Range = CS->getSourceRange();
970 if (Range.isInvalid() || CompareRegionOfInterest(Range))
971 return false;
972 }
973
974 switch (Visitor(Cursor, Parent, ClientData)) {
975 case CXChildVisit_Break: return true;
976 case CXChildVisit_Continue: return false;
977 case CXChildVisit_Recurse:
978 // Perform tail-recursion manually.
979 S = CS;
980 continue;
981 }
982 }
983 return false;
984 }
985}
986
Douglas Gregora59e3902010-01-21 23:27:09 +0000987bool CursorVisitor::VisitDeclStmt(DeclStmt *S) {
988 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
989 D != DEnd; ++D) {
Douglas Gregor263b47b2010-01-25 16:12:32 +0000990 if (*D && Visit(MakeCXCursor(*D, TU)))
Douglas Gregora59e3902010-01-21 23:27:09 +0000991 return true;
992 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000993
Douglas Gregora59e3902010-01-21 23:27:09 +0000994 return false;
995}
996
Douglas Gregorf5bab412010-01-22 01:00:11 +0000997bool CursorVisitor::VisitIfStmt(IfStmt *S) {
998 if (VarDecl *Var = S->getConditionVariable()) {
999 if (Visit(MakeCXCursor(Var, TU)))
1000 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001001 }
1002
Douglas Gregor263b47b2010-01-25 16:12:32 +00001003 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1004 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +00001005 if (S->getThen() && Visit(MakeCXCursor(S->getThen(), StmtParent, TU)))
1006 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +00001007 if (S->getElse() && Visit(MakeCXCursor(S->getElse(), StmtParent, TU)))
1008 return true;
1009
1010 return false;
1011}
1012
1013bool CursorVisitor::VisitSwitchStmt(SwitchStmt *S) {
1014 if (VarDecl *Var = S->getConditionVariable()) {
1015 if (Visit(MakeCXCursor(Var, TU)))
1016 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001017 }
1018
Douglas Gregor263b47b2010-01-25 16:12:32 +00001019 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1020 return true;
1021 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
1022 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001023
Douglas Gregor263b47b2010-01-25 16:12:32 +00001024 return false;
1025}
1026
1027bool CursorVisitor::VisitWhileStmt(WhileStmt *S) {
1028 if (VarDecl *Var = S->getConditionVariable()) {
1029 if (Visit(MakeCXCursor(Var, TU)))
1030 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001031 }
1032
Douglas Gregor263b47b2010-01-25 16:12:32 +00001033 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1034 return true;
1035 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
Douglas Gregorf5bab412010-01-22 01:00:11 +00001036 return true;
1037
Douglas Gregor263b47b2010-01-25 16:12:32 +00001038 return false;
1039}
1040
1041bool CursorVisitor::VisitForStmt(ForStmt *S) {
1042 if (S->getInit() && Visit(MakeCXCursor(S->getInit(), StmtParent, TU)))
1043 return true;
1044 if (VarDecl *Var = S->getConditionVariable()) {
1045 if (Visit(MakeCXCursor(Var, TU)))
1046 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001047 }
1048
Douglas Gregor263b47b2010-01-25 16:12:32 +00001049 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1050 return true;
1051 if (S->getInc() && Visit(MakeCXCursor(S->getInc(), StmtParent, TU)))
1052 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +00001053 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
1054 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001055
Douglas Gregorf5bab412010-01-22 01:00:11 +00001056 return false;
1057}
1058
Douglas Gregor6cd24e22010-07-29 00:26:18 +00001059bool CursorVisitor::VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
1060 if (Visit(MakeCXCursor(E->getArg(0), StmtParent, TU)))
1061 return true;
1062
1063 if (Visit(MakeCXCursor(E->getCallee(), StmtParent, TU)))
1064 return true;
1065
1066 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I)
1067 if (Visit(MakeCXCursor(E->getArg(I), StmtParent, TU)))
1068 return true;
1069
1070 return false;
1071}
1072
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00001073bool CursorVisitor::VisitBlockExpr(BlockExpr *B) {
1074 return Visit(B->getBlockDecl());
1075}
1076
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001077bool CursorVisitor::VisitOffsetOfExpr(OffsetOfExpr *E) {
1078 // FIXME: Visit fields as well?
1079 if (Visit(E->getTypeSourceInfo()->getTypeLoc()))
1080 return true;
1081
1082 return VisitExpr(E);
1083}
1084
Douglas Gregor336fd812010-01-23 00:40:08 +00001085bool CursorVisitor::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E) {
1086 if (E->isArgumentType()) {
1087 if (TypeSourceInfo *TSInfo = E->getArgumentTypeInfo())
1088 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001089
Douglas Gregor336fd812010-01-23 00:40:08 +00001090 return false;
1091 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001092
Douglas Gregor336fd812010-01-23 00:40:08 +00001093 return VisitExpr(E);
1094}
1095
1096bool CursorVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
1097 if (TypeSourceInfo *TSInfo = E->getTypeInfoAsWritten())
1098 if (Visit(TSInfo->getTypeLoc()))
1099 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001100
Douglas Gregor336fd812010-01-23 00:40:08 +00001101 return VisitCastExpr(E);
1102}
1103
1104bool CursorVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
1105 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
1106 if (Visit(TSInfo->getTypeLoc()))
1107 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001108
Douglas Gregor336fd812010-01-23 00:40:08 +00001109 return VisitExpr(E);
1110}
1111
Douglas Gregorc2350e52010-03-08 16:40:19 +00001112bool CursorVisitor::VisitObjCMessageExpr(ObjCMessageExpr *E) {
Douglas Gregor04badcf2010-04-21 00:45:42 +00001113 if (TypeSourceInfo *TSInfo = E->getClassReceiverTypeInfo())
1114 if (Visit(TSInfo->getTypeLoc()))
1115 return true;
Douglas Gregorc2350e52010-03-08 16:40:19 +00001116
1117 return VisitExpr(E);
1118}
1119
Douglas Gregor81d34662010-04-20 15:39:42 +00001120bool CursorVisitor::VisitObjCEncodeExpr(ObjCEncodeExpr *E) {
1121 return Visit(E->getEncodedTypeSourceInfo()->getTypeLoc());
1122}
1123
1124
Ted Kremenek09dfa372010-02-18 05:46:33 +00001125bool CursorVisitor::VisitAttributes(Decl *D) {
1126 for (const Attr *A = D->getAttrs(); A; A = A->getNext())
1127 if (Visit(MakeCXCursor(A, D, TU)))
1128 return true;
1129
1130 return false;
1131}
1132
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00001133extern "C" {
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001134CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
1135 int displayDiagnostics) {
Douglas Gregora030b7c2010-01-22 20:35:53 +00001136 CIndexer *CIdxr = new CIndexer();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001137 if (excludeDeclarationsFromPCH)
1138 CIdxr->setOnlyLocalDecls();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001139 if (displayDiagnostics)
1140 CIdxr->setDisplayDiagnostics();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001141 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +00001142}
1143
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001144void clang_disposeIndex(CXIndex CIdx) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001145 if (CIdx)
1146 delete static_cast<CIndexer *>(CIdx);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00001147}
1148
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001149void clang_setUseExternalASTGeneration(CXIndex CIdx, int value) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001150 if (CIdx) {
1151 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
1152 CXXIdx->setUseExternalASTGeneration(value);
1153 }
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001154}
1155
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001156CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
Douglas Gregora88084b2010-02-18 18:08:43 +00001157 const char *ast_filename) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001158 if (!CIdx)
1159 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001160
Douglas Gregor7d1d49d2009-10-16 20:01:17 +00001161 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001162
Douglas Gregor28019772010-04-05 23:52:57 +00001163 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
1164 return ASTUnit::LoadFromPCHFile(ast_filename, Diags,
Douglas Gregora88084b2010-02-18 18:08:43 +00001165 CXXIdx->getOnlyLocalDecls(),
1166 0, 0, true);
Steve Naroff600866c2009-08-27 19:51:58 +00001167}
1168
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001169CXTranslationUnit
1170clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
1171 const char *source_filename,
1172 int num_command_line_args,
Douglas Gregor4db64a42010-01-23 00:14:00 +00001173 const char **command_line_args,
1174 unsigned num_unsaved_files,
Douglas Gregora88084b2010-02-18 18:08:43 +00001175 struct CXUnsavedFile *unsaved_files) {
Douglas Gregor5a430212010-07-21 18:52:53 +00001176 return clang_parseTranslationUnit(CIdx, source_filename,
1177 command_line_args, num_command_line_args,
1178 unsaved_files, num_unsaved_files,
1179 CXTranslationUnit_DetailedPreprocessingRecord);
1180}
1181
1182CXTranslationUnit clang_parseTranslationUnit(CXIndex CIdx,
1183 const char *source_filename,
1184 const char **command_line_args,
1185 int num_command_line_args,
1186 struct CXUnsavedFile *unsaved_files,
1187 unsigned num_unsaved_files,
1188 unsigned options) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001189 if (!CIdx)
1190 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001191
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001192 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
1193
Douglas Gregor44c181a2010-07-23 00:33:23 +00001194 // The "editing" option implies other options.
1195 if (options & CXTranslationUnit_Editing)
1196 options |= CXTranslationUnit_PrecompiledPreamble;
1197 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
1198
Douglas Gregor5352ac02010-01-28 00:27:43 +00001199 // Configure the diagnostics.
1200 DiagnosticOptions DiagOpts;
Douglas Gregor28019772010-04-05 23:52:57 +00001201 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
1202 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001203
Douglas Gregor4db64a42010-01-23 00:14:00 +00001204 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
1205 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattnera0a270c2010-04-05 22:42:27 +00001206 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001207 const llvm::MemoryBuffer *Buffer
Chris Lattnera0a270c2010-04-05 22:42:27 +00001208 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregor4db64a42010-01-23 00:14:00 +00001209 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
1210 Buffer));
1211 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001212
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001213 if (!CXXIdx->getUseExternalASTGeneration()) {
1214 llvm::SmallVector<const char *, 16> Args;
1215
1216 // The 'source_filename' argument is optional. If the caller does not
1217 // specify it then it is assumed that the source file is specified
1218 // in the actual argument list.
1219 if (source_filename)
1220 Args.push_back(source_filename);
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00001221
1222 // Since the Clang C library is primarily used by batch tools dealing with
1223 // (often very broken) source code, where spell-checking can have a
1224 // significant negative impact on performance (particularly when
1225 // precompiled headers are involved), we disable it by default.
1226 // Note that we place this argument early in the list, so that it can be
1227 // overridden by the caller with "-fspell-checking".
Douglas Gregora0068fc2010-07-09 17:35:33 +00001228 Args.push_back("-fno-spell-checking");
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00001229
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001230 Args.insert(Args.end(), command_line_args,
1231 command_line_args + num_command_line_args);
Douglas Gregor5a430212010-07-21 18:52:53 +00001232
Douglas Gregor44c181a2010-07-23 00:33:23 +00001233 // Do we need the detailed preprocessing record?
Douglas Gregor5a430212010-07-21 18:52:53 +00001234 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
1235 Args.push_back("-Xclang");
1236 Args.push_back("-detailed-preprocessing-record");
1237 }
Douglas Gregor44c181a2010-07-23 00:33:23 +00001238
Douglas Gregor5352ac02010-01-28 00:27:43 +00001239 unsigned NumErrors = Diags->getNumErrors();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001240
Ted Kremenek29b72842010-01-07 22:49:05 +00001241#ifdef USE_CRASHTRACER
1242 ArgsCrashTracerInfo ACTI(Args);
Ted Kremenek8a8da7d2010-01-06 03:42:32 +00001243#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001244
Daniel Dunbar94220972009-12-05 02:17:18 +00001245 llvm::OwningPtr<ASTUnit> Unit(
1246 ASTUnit::LoadFromCommandLine(Args.data(), Args.data() + Args.size(),
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001247 Diags,
Daniel Dunbar869824e2009-12-13 03:46:13 +00001248 CXXIdx->getClangResourcesPath(),
Daniel Dunbar94220972009-12-05 02:17:18 +00001249 CXXIdx->getOnlyLocalDecls(),
Douglas Gregor4db64a42010-01-23 00:14:00 +00001250 RemappedFiles.data(),
Douglas Gregora88084b2010-02-18 18:08:43 +00001251 RemappedFiles.size(),
Douglas Gregor44c181a2010-07-23 00:33:23 +00001252 /*CaptureDiagnostics=*/true,
1253 PrecompilePreamble));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001254
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001255 if (NumErrors != Diags->getNumErrors()) {
Ted Kremenek34f6a322010-03-05 22:43:29 +00001256 // Make sure to check that 'Unit' is non-NULL.
1257 if (CXXIdx->getDisplayDiagnostics() && Unit.get()) {
Douglas Gregor405634b2010-04-05 18:10:21 +00001258 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
1259 DEnd = Unit->stored_diag_end();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001260 D != DEnd; ++D) {
1261 CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOptions());
Douglas Gregor274f1902010-02-22 23:17:23 +00001262 CXString Msg = clang_formatDiagnostic(&Diag,
1263 clang_defaultDiagnosticDisplayOptions());
1264 fprintf(stderr, "%s\n", clang_getCString(Msg));
1265 clang_disposeString(Msg);
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001266 }
Douglas Gregor274f1902010-02-22 23:17:23 +00001267#ifdef LLVM_ON_WIN32
1268 // On Windows, force a flush, since there may be multiple copies of
1269 // stderr and stdout in the file system, all with different buffers
1270 // but writing to the same device.
1271 fflush(stderr);
Ted Kremenek83c51842010-03-26 01:34:51 +00001272#endif
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001273 }
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001274 }
Daniel Dunbar94220972009-12-05 02:17:18 +00001275
1276 return Unit.take();
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001277 }
1278
Ted Kremenek139ba862009-10-22 00:03:57 +00001279 // Build up the arguments for invoking 'clang'.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001280 std::vector<const char *> argv;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001281
Ted Kremenek139ba862009-10-22 00:03:57 +00001282 // First add the complete path to the 'clang' executable.
1283 llvm::sys::Path ClangPath = static_cast<CIndexer *>(CIdx)->getClangPath();
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00001284 argv.push_back(ClangPath.c_str());
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001285
Ted Kremenek139ba862009-10-22 00:03:57 +00001286 // Add the '-emit-ast' option as our execution mode for 'clang'.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001287 argv.push_back("-emit-ast");
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001288
Ted Kremenek139ba862009-10-22 00:03:57 +00001289 // The 'source_filename' argument is optional. If the caller does not
1290 // specify it then it is assumed that the source file is specified
1291 // in the actual argument list.
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001292 if (source_filename)
1293 argv.push_back(source_filename);
Ted Kremenek139ba862009-10-22 00:03:57 +00001294
Steve Naroff37b5ac22009-10-15 20:50:09 +00001295 // Generate a temporary name for the AST file.
Ted Kremenek139ba862009-10-22 00:03:57 +00001296 argv.push_back("-o");
Benjamin Kramerc2a98162010-03-13 21:22:49 +00001297 char astTmpFile[L_tmpnam];
1298 argv.push_back(tmpnam(astTmpFile));
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00001299
1300 // Since the Clang C library is primarily used by batch tools dealing with
1301 // (often very broken) source code, where spell-checking can have a
1302 // significant negative impact on performance (particularly when
1303 // precompiled headers are involved), we disable it by default.
1304 // Note that we place this argument early in the list, so that it can be
1305 // overridden by the caller with "-fspell-checking".
Douglas Gregora0068fc2010-07-09 17:35:33 +00001306 argv.push_back("-fno-spell-checking");
Ted Kremenek139ba862009-10-22 00:03:57 +00001307
Douglas Gregor4db64a42010-01-23 00:14:00 +00001308 // Remap any unsaved files to temporary files.
1309 std::vector<llvm::sys::Path> TemporaryFiles;
1310 std::vector<std::string> RemapArgs;
1311 if (RemapFiles(num_unsaved_files, unsaved_files, RemapArgs, TemporaryFiles))
1312 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001313
Douglas Gregor4db64a42010-01-23 00:14:00 +00001314 // The pointers into the elements of RemapArgs are stable because we
1315 // won't be adding anything to RemapArgs after this point.
1316 for (unsigned i = 0, e = RemapArgs.size(); i != e; ++i)
1317 argv.push_back(RemapArgs[i].c_str());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001318
Ted Kremenek139ba862009-10-22 00:03:57 +00001319 // Process the compiler options, stripping off '-o', '-c', '-fsyntax-only'.
1320 for (int i = 0; i < num_command_line_args; ++i)
1321 if (const char *arg = command_line_args[i]) {
1322 if (strcmp(arg, "-o") == 0) {
1323 ++i; // Also skip the matching argument.
1324 continue;
1325 }
1326 if (strcmp(arg, "-emit-ast") == 0 ||
1327 strcmp(arg, "-c") == 0 ||
1328 strcmp(arg, "-fsyntax-only") == 0) {
1329 continue;
1330 }
1331
1332 // Keep the argument.
1333 argv.push_back(arg);
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001334 }
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001335
Douglas Gregord93256e2010-01-28 06:00:51 +00001336 // Generate a temporary name for the diagnostics file.
Benjamin Kramerc2a98162010-03-13 21:22:49 +00001337 char tmpFileResults[L_tmpnam];
1338 char *tmpResultsFileName = tmpnam(tmpFileResults);
1339 llvm::sys::Path DiagnosticsFile(tmpResultsFileName);
Douglas Gregord93256e2010-01-28 06:00:51 +00001340 TemporaryFiles.push_back(DiagnosticsFile);
1341 argv.push_back("-fdiagnostics-binary");
1342
Douglas Gregor44c181a2010-07-23 00:33:23 +00001343 // Do we need the detailed preprocessing record?
1344 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
1345 argv.push_back("-Xclang");
1346 argv.push_back("-detailed-preprocessing-record");
1347 }
1348
Ted Kremenek139ba862009-10-22 00:03:57 +00001349 // Add the null terminator.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001350 argv.push_back(NULL);
1351
Ted Kremenekfeb15e32009-10-26 22:14:08 +00001352 // Invoke 'clang'.
1353 llvm::sys::Path DevNull; // leave empty, causes redirection to /dev/null
1354 // on Unix or NUL (Windows).
Ted Kremenek379afec2009-10-22 03:24:01 +00001355 std::string ErrMsg;
Douglas Gregord93256e2010-01-28 06:00:51 +00001356 const llvm::sys::Path *Redirects[] = { &DevNull, &DevNull, &DiagnosticsFile,
1357 NULL };
Ted Kremenek379afec2009-10-22 03:24:01 +00001358 llvm::sys::Program::ExecuteAndWait(ClangPath, &argv[0], /* env */ NULL,
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001359 /* redirects */ &Redirects[0],
Ted Kremenek379afec2009-10-22 03:24:01 +00001360 /* secondsToWait */ 0, /* memoryLimits */ 0, &ErrMsg);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001361
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001362 if (!ErrMsg.empty()) {
1363 std::string AllArgs;
Ted Kremenek379afec2009-10-22 03:24:01 +00001364 for (std::vector<const char*>::iterator I = argv.begin(), E = argv.end();
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001365 I != E; ++I) {
1366 AllArgs += ' ';
Ted Kremenek779e5f42009-10-26 22:08:39 +00001367 if (*I)
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001368 AllArgs += *I;
Ted Kremenek779e5f42009-10-26 22:08:39 +00001369 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001370
Daniel Dunbar32141c82010-02-23 20:23:45 +00001371 Diags->Report(diag::err_fe_invoking) << AllArgs << ErrMsg;
Ted Kremenek379afec2009-10-22 03:24:01 +00001372 }
Benjamin Kramer0829a832009-10-18 11:19:36 +00001373
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001374 ASTUnit *ATU = ASTUnit::LoadFromPCHFile(astTmpFile, Diags,
Douglas Gregor4db64a42010-01-23 00:14:00 +00001375 CXXIdx->getOnlyLocalDecls(),
Douglas Gregor4db64a42010-01-23 00:14:00 +00001376 RemappedFiles.data(),
Douglas Gregora88084b2010-02-18 18:08:43 +00001377 RemappedFiles.size(),
1378 /*CaptureDiagnostics=*/true);
Douglas Gregora88084b2010-02-18 18:08:43 +00001379 if (ATU) {
1380 LoadSerializedDiagnostics(DiagnosticsFile,
1381 num_unsaved_files, unsaved_files,
1382 ATU->getFileManager(),
1383 ATU->getSourceManager(),
Douglas Gregor405634b2010-04-05 18:10:21 +00001384 ATU->getStoredDiagnostics());
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001385 } else if (CXXIdx->getDisplayDiagnostics()) {
1386 // We failed to load the ASTUnit, but we can still deserialize the
1387 // diagnostics and emit them.
1388 FileManager FileMgr;
Douglas Gregorf715ca12010-03-16 00:06:06 +00001389 Diagnostic Diag;
1390 SourceManager SourceMgr(Diag);
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001391 // FIXME: Faked LangOpts!
1392 LangOptions LangOpts;
1393 llvm::SmallVector<StoredDiagnostic, 4> Diags;
1394 LoadSerializedDiagnostics(DiagnosticsFile,
1395 num_unsaved_files, unsaved_files,
1396 FileMgr, SourceMgr, Diags);
1397 for (llvm::SmallVector<StoredDiagnostic, 4>::iterator D = Diags.begin(),
1398 DEnd = Diags.end();
1399 D != DEnd; ++D) {
1400 CXStoredDiagnostic Diag(*D, LangOpts);
Douglas Gregor274f1902010-02-22 23:17:23 +00001401 CXString Msg = clang_formatDiagnostic(&Diag,
1402 clang_defaultDiagnosticDisplayOptions());
1403 fprintf(stderr, "%s\n", clang_getCString(Msg));
1404 clang_disposeString(Msg);
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001405 }
Douglas Gregor274f1902010-02-22 23:17:23 +00001406
1407#ifdef LLVM_ON_WIN32
1408 // On Windows, force a flush, since there may be multiple copies of
1409 // stderr and stdout in the file system, all with different buffers
1410 // but writing to the same device.
1411 fflush(stderr);
1412#endif
Douglas Gregora88084b2010-02-18 18:08:43 +00001413 }
Douglas Gregord93256e2010-01-28 06:00:51 +00001414
Douglas Gregor313e26c2010-02-18 23:35:40 +00001415 if (ATU) {
1416 // Make the translation unit responsible for destroying all temporary files.
1417 for (unsigned i = 0, e = TemporaryFiles.size(); i != e; ++i)
1418 ATU->addTemporaryFile(TemporaryFiles[i]);
1419 ATU->addTemporaryFile(llvm::sys::Path(ATU->getPCHFileName()));
1420 } else {
1421 // Destroy all of the temporary files now; they can't be referenced any
1422 // longer.
1423 llvm::sys::Path(astTmpFile).eraseFromDisk();
1424 for (unsigned i = 0, e = TemporaryFiles.size(); i != e; ++i)
1425 TemporaryFiles[i].eraseFromDisk();
1426 }
1427
Steve Naroffe19944c2009-10-15 22:23:48 +00001428 return ATU;
Steve Naroff5b7d8e22009-10-15 20:04:39 +00001429}
1430
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001431void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001432 if (CTUnit)
1433 delete static_cast<ASTUnit *>(CTUnit);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00001434}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001435
Douglas Gregorabc563f2010-07-19 21:46:24 +00001436int clang_reparseTranslationUnit(CXTranslationUnit TU,
1437 unsigned num_unsaved_files,
1438 struct CXUnsavedFile *unsaved_files) {
1439 if (!TU)
1440 return 1;
1441
1442 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
1443 for (unsigned I = 0; I != num_unsaved_files; ++I) {
1444 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
1445 const llvm::MemoryBuffer *Buffer
1446 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
1447 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
1448 Buffer));
1449 }
1450
1451 return static_cast<ASTUnit *>(TU)->Reparse(RemappedFiles.data(),
1452 RemappedFiles.size())? 1 : 0;
1453}
1454
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001455CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001456 if (!CTUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001457 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001458
Steve Naroff77accc12009-09-03 18:19:54 +00001459 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001460 return createCXString(CXXUnit->getOriginalSourceFileName(), true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +00001461}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +00001462
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001463CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001464 CXCursor Result = { CXCursor_TranslationUnit, { 0, 0, TU } };
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001465 return Result;
1466}
1467
Ted Kremenekfb480492010-01-13 21:46:36 +00001468} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +00001469
Ted Kremenekfb480492010-01-13 21:46:36 +00001470//===----------------------------------------------------------------------===//
Douglas Gregor1db19de2010-01-19 21:36:55 +00001471// CXSourceLocation and CXSourceRange Operations.
1472//===----------------------------------------------------------------------===//
1473
Douglas Gregorb9790342010-01-22 21:44:22 +00001474extern "C" {
1475CXSourceLocation clang_getNullLocation() {
Douglas Gregor5352ac02010-01-28 00:27:43 +00001476 CXSourceLocation Result = { { 0, 0 }, 0 };
Douglas Gregorb9790342010-01-22 21:44:22 +00001477 return Result;
1478}
1479
1480unsigned clang_equalLocations(CXSourceLocation loc1, CXSourceLocation loc2) {
Daniel Dunbar90a6b9e2010-01-30 23:58:27 +00001481 return (loc1.ptr_data[0] == loc2.ptr_data[0] &&
1482 loc1.ptr_data[1] == loc2.ptr_data[1] &&
1483 loc1.int_data == loc2.int_data);
Douglas Gregorb9790342010-01-22 21:44:22 +00001484}
1485
1486CXSourceLocation clang_getLocation(CXTranslationUnit tu,
1487 CXFile file,
1488 unsigned line,
1489 unsigned column) {
Douglas Gregor42748ec2010-04-30 19:45:53 +00001490 if (!tu || !file)
Douglas Gregorb9790342010-01-22 21:44:22 +00001491 return clang_getNullLocation();
Douglas Gregor42748ec2010-04-30 19:45:53 +00001492
Douglas Gregorb9790342010-01-22 21:44:22 +00001493 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
1494 SourceLocation SLoc
1495 = CXXUnit->getSourceManager().getLocation(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001496 static_cast<const FileEntry *>(file),
Douglas Gregorb9790342010-01-22 21:44:22 +00001497 line, column);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001498
Ted Kremenek1a9a0bc2010-06-28 23:54:17 +00001499 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
Douglas Gregorb9790342010-01-22 21:44:22 +00001500}
1501
Douglas Gregor5352ac02010-01-28 00:27:43 +00001502CXSourceRange clang_getNullRange() {
1503 CXSourceRange Result = { { 0, 0 }, 0, 0 };
1504 return Result;
1505}
Daniel Dunbard52864b2010-02-14 10:02:57 +00001506
Douglas Gregor5352ac02010-01-28 00:27:43 +00001507CXSourceRange clang_getRange(CXSourceLocation begin, CXSourceLocation end) {
1508 if (begin.ptr_data[0] != end.ptr_data[0] ||
1509 begin.ptr_data[1] != end.ptr_data[1])
1510 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001511
1512 CXSourceRange Result = { { begin.ptr_data[0], begin.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00001513 begin.int_data, end.int_data };
Douglas Gregorb9790342010-01-22 21:44:22 +00001514 return Result;
1515}
1516
Douglas Gregor46766dc2010-01-26 19:19:08 +00001517void clang_getInstantiationLocation(CXSourceLocation location,
1518 CXFile *file,
1519 unsigned *line,
1520 unsigned *column,
1521 unsigned *offset) {
Douglas Gregor1db19de2010-01-19 21:36:55 +00001522 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
1523
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00001524 if (!location.ptr_data[0] || Loc.isInvalid()) {
Douglas Gregor46766dc2010-01-26 19:19:08 +00001525 if (file)
1526 *file = 0;
1527 if (line)
1528 *line = 0;
1529 if (column)
1530 *column = 0;
1531 if (offset)
1532 *offset = 0;
1533 return;
1534 }
1535
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00001536 const SourceManager &SM =
1537 *static_cast<const SourceManager*>(location.ptr_data[0]);
Douglas Gregor1db19de2010-01-19 21:36:55 +00001538 SourceLocation InstLoc = SM.getInstantiationLoc(Loc);
Douglas Gregor1db19de2010-01-19 21:36:55 +00001539
1540 if (file)
1541 *file = (void *)SM.getFileEntryForID(SM.getFileID(InstLoc));
1542 if (line)
1543 *line = SM.getInstantiationLineNumber(InstLoc);
1544 if (column)
1545 *column = SM.getInstantiationColumnNumber(InstLoc);
Douglas Gregore69517c2010-01-26 03:07:15 +00001546 if (offset)
Douglas Gregor46766dc2010-01-26 19:19:08 +00001547 *offset = SM.getDecomposedLoc(InstLoc).second;
Douglas Gregore69517c2010-01-26 03:07:15 +00001548}
1549
Douglas Gregor1db19de2010-01-19 21:36:55 +00001550CXSourceLocation clang_getRangeStart(CXSourceRange range) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001551 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00001552 range.begin_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00001553 return Result;
1554}
1555
1556CXSourceLocation clang_getRangeEnd(CXSourceRange range) {
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00001557 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00001558 range.end_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00001559 return Result;
1560}
1561
Douglas Gregorb9790342010-01-22 21:44:22 +00001562} // end: extern "C"
1563
Douglas Gregor1db19de2010-01-19 21:36:55 +00001564//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00001565// CXFile Operations.
1566//===----------------------------------------------------------------------===//
1567
1568extern "C" {
Ted Kremenek74844072010-02-17 00:41:20 +00001569CXString clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00001570 if (!SFile)
Ted Kremenek74844072010-02-17 00:41:20 +00001571 return createCXString(NULL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001572
Steve Naroff88145032009-10-27 14:35:18 +00001573 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Ted Kremenek74844072010-02-17 00:41:20 +00001574 return createCXString(FEnt->getName());
Steve Naroff88145032009-10-27 14:35:18 +00001575}
1576
1577time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00001578 if (!SFile)
1579 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001580
Steve Naroff88145032009-10-27 14:35:18 +00001581 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
1582 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +00001583}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001584
Douglas Gregorb9790342010-01-22 21:44:22 +00001585CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
1586 if (!tu)
1587 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001588
Douglas Gregorb9790342010-01-22 21:44:22 +00001589 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001590
Douglas Gregorb9790342010-01-22 21:44:22 +00001591 FileManager &FMgr = CXXUnit->getFileManager();
1592 const FileEntry *File = FMgr.getFile(file_name, file_name+strlen(file_name));
1593 return const_cast<FileEntry *>(File);
1594}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001595
Ted Kremenekfb480492010-01-13 21:46:36 +00001596} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +00001597
Ted Kremenekfb480492010-01-13 21:46:36 +00001598//===----------------------------------------------------------------------===//
1599// CXCursor Operations.
1600//===----------------------------------------------------------------------===//
1601
Ted Kremenekfb480492010-01-13 21:46:36 +00001602static Decl *getDeclFromExpr(Stmt *E) {
1603 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
1604 return RefExpr->getDecl();
1605 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
1606 return ME->getMemberDecl();
1607 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
1608 return RE->getDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001609
Ted Kremenekfb480492010-01-13 21:46:36 +00001610 if (CallExpr *CE = dyn_cast<CallExpr>(E))
1611 return getDeclFromExpr(CE->getCallee());
1612 if (CastExpr *CE = dyn_cast<CastExpr>(E))
1613 return getDeclFromExpr(CE->getSubExpr());
1614 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
1615 return OME->getMethodDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001616
Ted Kremenekfb480492010-01-13 21:46:36 +00001617 return 0;
1618}
1619
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00001620static SourceLocation getLocationFromExpr(Expr *E) {
1621 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
1622 return /*FIXME:*/Msg->getLeftLoc();
1623 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
1624 return DRE->getLocation();
1625 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
1626 return Member->getMemberLoc();
1627 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
1628 return Ivar->getLocation();
1629 return E->getLocStart();
1630}
1631
Ted Kremenekfb480492010-01-13 21:46:36 +00001632extern "C" {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001633
1634unsigned clang_visitChildren(CXCursor parent,
Douglas Gregorb1373d02010-01-20 20:59:29 +00001635 CXCursorVisitor visitor,
1636 CXClientData client_data) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001637 ASTUnit *CXXUnit = getCursorASTUnit(parent);
Douglas Gregorb1373d02010-01-20 20:59:29 +00001638
1639 unsigned PCHLevel = Decl::MaxPCHLevel;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001640
Douglas Gregorb1373d02010-01-20 20:59:29 +00001641 // Set the PCHLevel to filter out unwanted decls if requested.
1642 if (CXXUnit->getOnlyLocalDecls()) {
1643 PCHLevel = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001644
Douglas Gregorb1373d02010-01-20 20:59:29 +00001645 // If the main input was an AST, bump the level.
1646 if (CXXUnit->isMainFileAST())
1647 ++PCHLevel;
1648 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001649
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001650 CursorVisitor CursorVis(CXXUnit, visitor, client_data, PCHLevel);
Douglas Gregorb1373d02010-01-20 20:59:29 +00001651 return CursorVis.VisitChildren(parent);
1652}
1653
Douglas Gregor78205d42010-01-20 21:45:58 +00001654static CXString getDeclSpelling(Decl *D) {
1655 NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
1656 if (!ND)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001657 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001658
Douglas Gregor78205d42010-01-20 21:45:58 +00001659 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001660 return createCXString(OMD->getSelector().getAsString());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001661
Douglas Gregor78205d42010-01-20 21:45:58 +00001662 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
1663 // No, this isn't the same as the code below. getIdentifier() is non-virtual
1664 // and returns different names. NamedDecl returns the class name and
1665 // ObjCCategoryImplDecl returns the category name.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001666 return createCXString(CIMP->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001667
Ted Kremenek50aa6ac2010-05-19 21:51:10 +00001668 llvm::SmallString<1024> S;
1669 llvm::raw_svector_ostream os(S);
1670 ND->printName(os);
1671
1672 return createCXString(os.str());
Douglas Gregor78205d42010-01-20 21:45:58 +00001673}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001674
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001675CXString clang_getCursorSpelling(CXCursor C) {
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001676 if (clang_isTranslationUnit(C.kind))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001677 return clang_getTranslationUnitSpelling(C.data[2]);
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001678
Steve Narofff334b4e2009-09-02 18:26:48 +00001679 if (clang_isReference(C.kind)) {
1680 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00001681 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +00001682 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001683 return createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00001684 }
1685 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +00001686 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001687 return createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00001688 }
1689 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +00001690 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +00001691 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001692 return createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00001693 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001694 case CXCursor_TypeRef: {
1695 TypeDecl *Type = getCursorTypeRef(C).first;
1696 assert(Type && "Missing type decl");
1697
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001698 return createCXString(getCursorContext(C).getTypeDeclType(Type).
1699 getAsString());
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001700 }
1701
Daniel Dunbaracca7252009-11-30 20:42:49 +00001702 default:
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001703 return createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +00001704 }
1705 }
Douglas Gregor97b98722010-01-19 23:20:36 +00001706
1707 if (clang_isExpression(C.kind)) {
1708 Decl *D = getDeclFromExpr(getCursorExpr(C));
1709 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +00001710 return getDeclSpelling(D);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001711 return createCXString("");
Douglas Gregor97b98722010-01-19 23:20:36 +00001712 }
1713
Douglas Gregor4ae8f292010-03-18 17:52:52 +00001714 if (C.kind == CXCursor_MacroInstantiation)
1715 return createCXString(getCursorMacroInstantiation(C)->getName()
1716 ->getNameStart());
1717
Douglas Gregor572feb22010-03-18 18:04:21 +00001718 if (C.kind == CXCursor_MacroDefinition)
1719 return createCXString(getCursorMacroDefinition(C)->getName()
1720 ->getNameStart());
1721
Douglas Gregor60cbfac2010-01-25 16:56:17 +00001722 if (clang_isDeclaration(C.kind))
1723 return getDeclSpelling(getCursorDecl(C));
Ted Kremeneke68fff62010-02-17 00:41:32 +00001724
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001725 return createCXString("");
Steve Narofff334b4e2009-09-02 18:26:48 +00001726}
1727
Ted Kremeneke68fff62010-02-17 00:41:32 +00001728CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00001729 switch (Kind) {
Ted Kremeneke68fff62010-02-17 00:41:32 +00001730 case CXCursor_FunctionDecl:
1731 return createCXString("FunctionDecl");
1732 case CXCursor_TypedefDecl:
1733 return createCXString("TypedefDecl");
1734 case CXCursor_EnumDecl:
1735 return createCXString("EnumDecl");
1736 case CXCursor_EnumConstantDecl:
1737 return createCXString("EnumConstantDecl");
1738 case CXCursor_StructDecl:
1739 return createCXString("StructDecl");
1740 case CXCursor_UnionDecl:
1741 return createCXString("UnionDecl");
1742 case CXCursor_ClassDecl:
1743 return createCXString("ClassDecl");
1744 case CXCursor_FieldDecl:
1745 return createCXString("FieldDecl");
1746 case CXCursor_VarDecl:
1747 return createCXString("VarDecl");
1748 case CXCursor_ParmDecl:
1749 return createCXString("ParmDecl");
1750 case CXCursor_ObjCInterfaceDecl:
1751 return createCXString("ObjCInterfaceDecl");
1752 case CXCursor_ObjCCategoryDecl:
1753 return createCXString("ObjCCategoryDecl");
1754 case CXCursor_ObjCProtocolDecl:
1755 return createCXString("ObjCProtocolDecl");
1756 case CXCursor_ObjCPropertyDecl:
1757 return createCXString("ObjCPropertyDecl");
1758 case CXCursor_ObjCIvarDecl:
1759 return createCXString("ObjCIvarDecl");
1760 case CXCursor_ObjCInstanceMethodDecl:
1761 return createCXString("ObjCInstanceMethodDecl");
1762 case CXCursor_ObjCClassMethodDecl:
1763 return createCXString("ObjCClassMethodDecl");
1764 case CXCursor_ObjCImplementationDecl:
1765 return createCXString("ObjCImplementationDecl");
1766 case CXCursor_ObjCCategoryImplDecl:
1767 return createCXString("ObjCCategoryImplDecl");
Ted Kremenek8bd5a692010-04-13 23:39:06 +00001768 case CXCursor_CXXMethod:
1769 return createCXString("CXXMethod");
Ted Kremeneke68fff62010-02-17 00:41:32 +00001770 case CXCursor_UnexposedDecl:
1771 return createCXString("UnexposedDecl");
1772 case CXCursor_ObjCSuperClassRef:
1773 return createCXString("ObjCSuperClassRef");
1774 case CXCursor_ObjCProtocolRef:
1775 return createCXString("ObjCProtocolRef");
1776 case CXCursor_ObjCClassRef:
1777 return createCXString("ObjCClassRef");
1778 case CXCursor_TypeRef:
1779 return createCXString("TypeRef");
1780 case CXCursor_UnexposedExpr:
1781 return createCXString("UnexposedExpr");
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00001782 case CXCursor_BlockExpr:
1783 return createCXString("BlockExpr");
Ted Kremeneke68fff62010-02-17 00:41:32 +00001784 case CXCursor_DeclRefExpr:
1785 return createCXString("DeclRefExpr");
1786 case CXCursor_MemberRefExpr:
1787 return createCXString("MemberRefExpr");
1788 case CXCursor_CallExpr:
1789 return createCXString("CallExpr");
1790 case CXCursor_ObjCMessageExpr:
1791 return createCXString("ObjCMessageExpr");
1792 case CXCursor_UnexposedStmt:
1793 return createCXString("UnexposedStmt");
1794 case CXCursor_InvalidFile:
1795 return createCXString("InvalidFile");
Ted Kremenek292db642010-03-19 20:39:05 +00001796 case CXCursor_InvalidCode:
1797 return createCXString("InvalidCode");
Ted Kremeneke68fff62010-02-17 00:41:32 +00001798 case CXCursor_NoDeclFound:
1799 return createCXString("NoDeclFound");
1800 case CXCursor_NotImplemented:
1801 return createCXString("NotImplemented");
1802 case CXCursor_TranslationUnit:
1803 return createCXString("TranslationUnit");
Ted Kremeneke77f4432010-02-18 03:09:07 +00001804 case CXCursor_UnexposedAttr:
1805 return createCXString("UnexposedAttr");
1806 case CXCursor_IBActionAttr:
1807 return createCXString("attribute(ibaction)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00001808 case CXCursor_IBOutletAttr:
1809 return createCXString("attribute(iboutlet)");
Ted Kremenek857e9182010-05-19 17:38:06 +00001810 case CXCursor_IBOutletCollectionAttr:
1811 return createCXString("attribute(iboutletcollection)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00001812 case CXCursor_PreprocessingDirective:
1813 return createCXString("preprocessing directive");
Douglas Gregor572feb22010-03-18 18:04:21 +00001814 case CXCursor_MacroDefinition:
1815 return createCXString("macro definition");
Douglas Gregor48072312010-03-18 15:23:44 +00001816 case CXCursor_MacroInstantiation:
1817 return createCXString("macro instantiation");
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00001818 case CXCursor_Namespace:
1819 return createCXString("Namespace");
Ted Kremeneka0536d82010-05-07 01:04:29 +00001820 case CXCursor_LinkageSpec:
1821 return createCXString("LinkageSpec");
Steve Naroff89922f82009-08-31 00:59:03 +00001822 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00001823
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00001824 llvm_unreachable("Unhandled CXCursorKind");
Ted Kremeneke68fff62010-02-17 00:41:32 +00001825 return createCXString(NULL);
Steve Naroff600866c2009-08-27 19:51:58 +00001826}
Steve Naroff89922f82009-08-31 00:59:03 +00001827
Ted Kremeneke68fff62010-02-17 00:41:32 +00001828enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
1829 CXCursor parent,
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001830 CXClientData client_data) {
1831 CXCursor *BestCursor = static_cast<CXCursor *>(client_data);
1832 *BestCursor = cursor;
1833 return CXChildVisit_Recurse;
1834}
Ted Kremeneke68fff62010-02-17 00:41:32 +00001835
Douglas Gregorb9790342010-01-22 21:44:22 +00001836CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
1837 if (!TU)
Ted Kremenekf4629892010-01-14 01:51:23 +00001838 return clang_getNullCursor();
Ted Kremeneke68fff62010-02-17 00:41:32 +00001839
Douglas Gregorb9790342010-01-22 21:44:22 +00001840 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregorbdf60622010-03-05 21:16:25 +00001841 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
1842
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00001843 // Translate the given source location to make it point at the beginning of
1844 // the token under the cursor.
Ted Kremeneka297de22010-01-25 22:34:44 +00001845 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
Ted Kremeneka629ea42010-07-29 00:52:07 +00001846
1847 // Guard against an invalid SourceLocation, or we may assert in one
1848 // of the following calls.
1849 if (SLoc.isInvalid())
1850 return clang_getNullCursor();
1851
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00001852 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
1853 CXXUnit->getASTContext().getLangOptions());
1854
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001855 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
1856 if (SLoc.isValid()) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001857 // FIXME: Would be great to have a "hint" cursor, then walk from that
1858 // hint cursor upward until we find a cursor whose source range encloses
1859 // the region of interest, rather than starting from the translation unit.
1860 CXCursor Parent = clang_getTranslationUnitCursor(CXXUnit);
Ted Kremeneke68fff62010-02-17 00:41:32 +00001861 CursorVisitor CursorVis(CXXUnit, GetCursorVisitor, &Result,
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00001862 Decl::MaxPCHLevel, SourceLocation(SLoc));
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001863 CursorVis.VisitChildren(Parent);
Steve Naroff77128dd2009-09-15 20:25:34 +00001864 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00001865 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00001866}
1867
Ted Kremenek73885552009-11-17 19:28:59 +00001868CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00001869 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00001870}
1871
1872unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00001873 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00001874}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001875
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001876unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00001877 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
1878}
1879
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001880unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +00001881 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
1882}
Steve Naroff2d4d6292009-08-31 14:26:51 +00001883
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001884unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00001885 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
1886}
1887
Douglas Gregor97b98722010-01-19 23:20:36 +00001888unsigned clang_isExpression(enum CXCursorKind K) {
1889 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
1890}
1891
1892unsigned clang_isStatement(enum CXCursorKind K) {
1893 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
1894}
1895
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001896unsigned clang_isTranslationUnit(enum CXCursorKind K) {
1897 return K == CXCursor_TranslationUnit;
1898}
1899
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00001900unsigned clang_isPreprocessing(enum CXCursorKind K) {
1901 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
1902}
1903
Ted Kremenekad6eff62010-03-08 21:17:29 +00001904unsigned clang_isUnexposed(enum CXCursorKind K) {
1905 switch (K) {
1906 case CXCursor_UnexposedDecl:
1907 case CXCursor_UnexposedExpr:
1908 case CXCursor_UnexposedStmt:
1909 case CXCursor_UnexposedAttr:
1910 return true;
1911 default:
1912 return false;
1913 }
1914}
1915
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001916CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00001917 return C.kind;
1918}
1919
Douglas Gregor98258af2010-01-18 22:46:11 +00001920CXSourceLocation clang_getCursorLocation(CXCursor C) {
1921 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00001922 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001923 case CXCursor_ObjCSuperClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00001924 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1925 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001926 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001927 }
1928
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001929 case CXCursor_ObjCProtocolRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00001930 std::pair<ObjCProtocolDecl *, SourceLocation> P
1931 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001932 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001933 }
1934
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001935 case CXCursor_ObjCClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00001936 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1937 = getCursorObjCClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001938 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001939 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001940
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001941 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001942 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001943 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001944 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001945
Douglas Gregorf46034a2010-01-18 23:41:10 +00001946 default:
1947 // FIXME: Need a way to enumerate all non-reference cases.
1948 llvm_unreachable("Missed a reference kind");
1949 }
Douglas Gregor98258af2010-01-18 22:46:11 +00001950 }
Douglas Gregor97b98722010-01-19 23:20:36 +00001951
1952 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001953 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00001954 getLocationFromExpr(getCursorExpr(C)));
1955
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00001956 if (C.kind == CXCursor_PreprocessingDirective) {
1957 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
1958 return cxloc::translateSourceLocation(getCursorContext(C), L);
1959 }
Douglas Gregor48072312010-03-18 15:23:44 +00001960
1961 if (C.kind == CXCursor_MacroInstantiation) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00001962 SourceLocation L
1963 = cxcursor::getCursorMacroInstantiation(C)->getSourceRange().getBegin();
Douglas Gregor48072312010-03-18 15:23:44 +00001964 return cxloc::translateSourceLocation(getCursorContext(C), L);
1965 }
Douglas Gregor572feb22010-03-18 18:04:21 +00001966
1967 if (C.kind == CXCursor_MacroDefinition) {
1968 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
1969 return cxloc::translateSourceLocation(getCursorContext(C), L);
1970 }
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00001971
Ted Kremenek9a700d22010-05-12 06:16:13 +00001972 if (C.kind < CXCursor_FirstDecl || C.kind > CXCursor_LastDecl)
Douglas Gregor5352ac02010-01-28 00:27:43 +00001973 return clang_getNullLocation();
Douglas Gregor98258af2010-01-18 22:46:11 +00001974
Douglas Gregorf46034a2010-01-18 23:41:10 +00001975 Decl *D = getCursorDecl(C);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001976 SourceLocation Loc = D->getLocation();
1977 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
1978 Loc = Class->getClassLoc();
Douglas Gregor2ca54fe2010-03-22 15:53:50 +00001979 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00001980}
Douglas Gregora7bde202010-01-19 00:34:46 +00001981
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00001982} // end extern "C"
1983
1984static SourceRange getRawCursorExtent(CXCursor C) {
Douglas Gregora7bde202010-01-19 00:34:46 +00001985 if (clang_isReference(C.kind)) {
1986 switch (C.kind) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00001987 case CXCursor_ObjCSuperClassRef:
1988 return getCursorObjCSuperClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001989
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00001990 case CXCursor_ObjCProtocolRef:
1991 return getCursorObjCProtocolRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001992
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00001993 case CXCursor_ObjCClassRef:
1994 return getCursorObjCClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001995
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00001996 case CXCursor_TypeRef:
1997 return getCursorTypeRef(C).second;
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001998
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00001999 default:
2000 // FIXME: Need a way to enumerate all non-reference cases.
2001 llvm_unreachable("Missed a reference kind");
Douglas Gregora7bde202010-01-19 00:34:46 +00002002 }
2003 }
Douglas Gregor97b98722010-01-19 23:20:36 +00002004
2005 if (clang_isExpression(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002006 return getCursorExpr(C)->getSourceRange();
Douglas Gregor33e9abd2010-01-22 19:49:59 +00002007
2008 if (clang_isStatement(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002009 return getCursorStmt(C)->getSourceRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002010
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002011 if (C.kind == CXCursor_PreprocessingDirective)
2012 return cxcursor::getCursorPreprocessingDirective(C);
Douglas Gregor48072312010-03-18 15:23:44 +00002013
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002014 if (C.kind == CXCursor_MacroInstantiation)
2015 return cxcursor::getCursorMacroInstantiation(C)->getSourceRange();
Douglas Gregor572feb22010-03-18 18:04:21 +00002016
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002017 if (C.kind == CXCursor_MacroDefinition)
2018 return cxcursor::getCursorMacroDefinition(C)->getSourceRange();
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002019
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002020 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl)
2021 return getCursorDecl(C)->getSourceRange();
2022
2023 return SourceRange();
2024}
2025
2026extern "C" {
2027
2028CXSourceRange clang_getCursorExtent(CXCursor C) {
2029 SourceRange R = getRawCursorExtent(C);
2030 if (R.isInvalid())
Douglas Gregor5352ac02010-01-28 00:27:43 +00002031 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002032
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002033 return cxloc::translateSourceRange(getCursorContext(C), R);
Douglas Gregora7bde202010-01-19 00:34:46 +00002034}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002035
2036CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002037 if (clang_isInvalid(C.kind))
2038 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002039
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002040 ASTUnit *CXXUnit = getCursorASTUnit(C);
Douglas Gregorb6998662010-01-19 19:34:47 +00002041 if (clang_isDeclaration(C.kind))
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002042 return C;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002043
Douglas Gregor97b98722010-01-19 23:20:36 +00002044 if (clang_isExpression(C.kind)) {
2045 Decl *D = getDeclFromExpr(getCursorExpr(C));
2046 if (D)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002047 return MakeCXCursor(D, CXXUnit);
Douglas Gregor97b98722010-01-19 23:20:36 +00002048 return clang_getNullCursor();
2049 }
2050
Douglas Gregorbf7efa22010-03-18 18:23:03 +00002051 if (C.kind == CXCursor_MacroInstantiation) {
2052 if (MacroDefinition *Def = getCursorMacroInstantiation(C)->getDefinition())
2053 return MakeMacroDefinitionCursor(Def, CXXUnit);
2054 }
2055
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002056 if (!clang_isReference(C.kind))
2057 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002058
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002059 switch (C.kind) {
2060 case CXCursor_ObjCSuperClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002061 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002062
2063 case CXCursor_ObjCProtocolRef: {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002064 return MakeCXCursor(getCursorObjCProtocolRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002065
2066 case CXCursor_ObjCClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002067 return MakeCXCursor(getCursorObjCClassRef(C).first, CXXUnit);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002068
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002069 case CXCursor_TypeRef:
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002070 return MakeCXCursor(getCursorTypeRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002071
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002072 default:
2073 // We would prefer to enumerate all non-reference cursor kinds here.
2074 llvm_unreachable("Unhandled reference cursor kind");
2075 break;
2076 }
2077 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002078
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002079 return clang_getNullCursor();
2080}
2081
Douglas Gregorb6998662010-01-19 19:34:47 +00002082CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002083 if (clang_isInvalid(C.kind))
2084 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002085
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002086 ASTUnit *CXXUnit = getCursorASTUnit(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002087
Douglas Gregorb6998662010-01-19 19:34:47 +00002088 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00002089 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00002090 C = clang_getCursorReferenced(C);
2091 WasReference = true;
2092 }
2093
Douglas Gregorbf7efa22010-03-18 18:23:03 +00002094 if (C.kind == CXCursor_MacroInstantiation)
2095 return clang_getCursorReferenced(C);
2096
Douglas Gregorb6998662010-01-19 19:34:47 +00002097 if (!clang_isDeclaration(C.kind))
2098 return clang_getNullCursor();
2099
2100 Decl *D = getCursorDecl(C);
2101 if (!D)
2102 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002103
Douglas Gregorb6998662010-01-19 19:34:47 +00002104 switch (D->getKind()) {
2105 // Declaration kinds that don't really separate the notions of
2106 // declaration and definition.
2107 case Decl::Namespace:
2108 case Decl::Typedef:
2109 case Decl::TemplateTypeParm:
2110 case Decl::EnumConstant:
2111 case Decl::Field:
2112 case Decl::ObjCIvar:
2113 case Decl::ObjCAtDefsField:
2114 case Decl::ImplicitParam:
2115 case Decl::ParmVar:
2116 case Decl::NonTypeTemplateParm:
2117 case Decl::TemplateTemplateParm:
2118 case Decl::ObjCCategoryImpl:
2119 case Decl::ObjCImplementation:
Abramo Bagnara6206d532010-06-05 05:09:32 +00002120 case Decl::AccessSpec:
Douglas Gregorb6998662010-01-19 19:34:47 +00002121 case Decl::LinkageSpec:
2122 case Decl::ObjCPropertyImpl:
2123 case Decl::FileScopeAsm:
2124 case Decl::StaticAssert:
2125 case Decl::Block:
2126 return C;
2127
2128 // Declaration kinds that don't make any sense here, but are
2129 // nonetheless harmless.
2130 case Decl::TranslationUnit:
Douglas Gregorb6998662010-01-19 19:34:47 +00002131 break;
2132
2133 // Declaration kinds for which the definition is not resolvable.
2134 case Decl::UnresolvedUsingTypename:
2135 case Decl::UnresolvedUsingValue:
2136 break;
2137
2138 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002139 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
2140 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002141
2142 case Decl::NamespaceAlias:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002143 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002144
2145 case Decl::Enum:
2146 case Decl::Record:
2147 case Decl::CXXRecord:
2148 case Decl::ClassTemplateSpecialization:
2149 case Decl::ClassTemplatePartialSpecialization:
Douglas Gregor952b0172010-02-11 01:04:33 +00002150 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002151 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002152 return clang_getNullCursor();
2153
2154 case Decl::Function:
2155 case Decl::CXXMethod:
2156 case Decl::CXXConstructor:
2157 case Decl::CXXDestructor:
2158 case Decl::CXXConversion: {
2159 const FunctionDecl *Def = 0;
2160 if (cast<FunctionDecl>(D)->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002161 return MakeCXCursor(const_cast<FunctionDecl *>(Def), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002162 return clang_getNullCursor();
2163 }
2164
2165 case Decl::Var: {
Sebastian Redl31310a22010-02-01 20:16:42 +00002166 // Ask the variable if it has a definition.
2167 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
2168 return MakeCXCursor(Def, CXXUnit);
2169 return clang_getNullCursor();
Douglas Gregorb6998662010-01-19 19:34:47 +00002170 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002171
Douglas Gregorb6998662010-01-19 19:34:47 +00002172 case Decl::FunctionTemplate: {
2173 const FunctionDecl *Def = 0;
2174 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002175 return MakeCXCursor(Def->getDescribedFunctionTemplate(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002176 return clang_getNullCursor();
2177 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002178
Douglas Gregorb6998662010-01-19 19:34:47 +00002179 case Decl::ClassTemplate: {
2180 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
Douglas Gregor952b0172010-02-11 01:04:33 +00002181 ->getDefinition())
Douglas Gregorb6998662010-01-19 19:34:47 +00002182 return MakeCXCursor(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002183 cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002184 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002185 return clang_getNullCursor();
2186 }
2187
2188 case Decl::Using: {
2189 UsingDecl *Using = cast<UsingDecl>(D);
2190 CXCursor Def = clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002191 for (UsingDecl::shadow_iterator S = Using->shadow_begin(),
2192 SEnd = Using->shadow_end();
Douglas Gregorb6998662010-01-19 19:34:47 +00002193 S != SEnd; ++S) {
2194 if (Def != clang_getNullCursor()) {
2195 // FIXME: We have no way to return multiple results.
2196 return clang_getNullCursor();
2197 }
2198
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002199 Def = clang_getCursorDefinition(MakeCXCursor((*S)->getTargetDecl(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002200 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002201 }
2202
2203 return Def;
2204 }
2205
2206 case Decl::UsingShadow:
2207 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002208 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002209 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002210
2211 case Decl::ObjCMethod: {
2212 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
2213 if (Method->isThisDeclarationADefinition())
2214 return C;
2215
2216 // Dig out the method definition in the associated
2217 // @implementation, if we have it.
2218 // FIXME: The ASTs should make finding the definition easier.
2219 if (ObjCInterfaceDecl *Class
2220 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
2221 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
2222 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
2223 Method->isInstanceMethod()))
2224 if (Def->isThisDeclarationADefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002225 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002226
2227 return clang_getNullCursor();
2228 }
2229
2230 case Decl::ObjCCategory:
2231 if (ObjCCategoryImplDecl *Impl
2232 = cast<ObjCCategoryDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002233 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002234 return clang_getNullCursor();
2235
2236 case Decl::ObjCProtocol:
2237 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
2238 return C;
2239 return clang_getNullCursor();
2240
2241 case Decl::ObjCInterface:
2242 // There are two notions of a "definition" for an Objective-C
2243 // class: the interface and its implementation. When we resolved a
2244 // reference to an Objective-C class, produce the @interface as
2245 // the definition; when we were provided with the interface,
2246 // produce the @implementation as the definition.
2247 if (WasReference) {
2248 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
2249 return C;
2250 } else if (ObjCImplementationDecl *Impl
2251 = cast<ObjCInterfaceDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002252 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002253 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002254
Douglas Gregorb6998662010-01-19 19:34:47 +00002255 case Decl::ObjCProperty:
2256 // FIXME: We don't really know where to find the
2257 // ObjCPropertyImplDecls that implement this property.
2258 return clang_getNullCursor();
2259
2260 case Decl::ObjCCompatibleAlias:
2261 if (ObjCInterfaceDecl *Class
2262 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
2263 if (!Class->isForwardDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002264 return MakeCXCursor(Class, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002265
Douglas Gregorb6998662010-01-19 19:34:47 +00002266 return clang_getNullCursor();
2267
2268 case Decl::ObjCForwardProtocol: {
2269 ObjCForwardProtocolDecl *Forward = cast<ObjCForwardProtocolDecl>(D);
2270 if (Forward->protocol_size() == 1)
2271 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002272 MakeCXCursor(*Forward->protocol_begin(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002273 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002274
2275 // FIXME: Cannot return multiple definitions.
2276 return clang_getNullCursor();
2277 }
2278
2279 case Decl::ObjCClass: {
2280 ObjCClassDecl *Class = cast<ObjCClassDecl>(D);
2281 if (Class->size() == 1) {
2282 ObjCInterfaceDecl *IFace = Class->begin()->getInterface();
2283 if (!IFace->isForwardDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002284 return MakeCXCursor(IFace, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002285 return clang_getNullCursor();
2286 }
2287
2288 // FIXME: Cannot return multiple definitions.
2289 return clang_getNullCursor();
2290 }
2291
2292 case Decl::Friend:
2293 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002294 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002295 return clang_getNullCursor();
2296
2297 case Decl::FriendTemplate:
2298 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002299 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002300 return clang_getNullCursor();
2301 }
2302
2303 return clang_getNullCursor();
2304}
2305
2306unsigned clang_isCursorDefinition(CXCursor C) {
2307 if (!clang_isDeclaration(C.kind))
2308 return 0;
2309
2310 return clang_getCursorDefinition(C) == C;
2311}
2312
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002313void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00002314 const char **startBuf,
2315 const char **endBuf,
2316 unsigned *startLine,
2317 unsigned *startColumn,
2318 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002319 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00002320 assert(getCursorDecl(C) && "CXCursor has null decl");
2321 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00002322 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
2323 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002324
Steve Naroff4ade6d62009-09-23 17:52:52 +00002325 SourceManager &SM = FD->getASTContext().getSourceManager();
2326 *startBuf = SM.getCharacterData(Body->getLBracLoc());
2327 *endBuf = SM.getCharacterData(Body->getRBracLoc());
2328 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
2329 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
2330 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
2331 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
2332}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002333
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002334void clang_enableStackTraces(void) {
2335 llvm::sys::PrintStackTraceOnErrorSignal();
2336}
2337
Ted Kremenekfb480492010-01-13 21:46:36 +00002338} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00002339
Ted Kremenekfb480492010-01-13 21:46:36 +00002340//===----------------------------------------------------------------------===//
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002341// Token-based Operations.
2342//===----------------------------------------------------------------------===//
2343
2344/* CXToken layout:
2345 * int_data[0]: a CXTokenKind
2346 * int_data[1]: starting token location
2347 * int_data[2]: token length
2348 * int_data[3]: reserved
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002349 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002350 * otherwise unused.
2351 */
2352extern "C" {
2353
2354CXTokenKind clang_getTokenKind(CXToken CXTok) {
2355 return static_cast<CXTokenKind>(CXTok.int_data[0]);
2356}
2357
2358CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
2359 switch (clang_getTokenKind(CXTok)) {
2360 case CXToken_Identifier:
2361 case CXToken_Keyword:
2362 // We know we have an IdentifierInfo*, so use that.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002363 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
2364 ->getNameStart());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002365
2366 case CXToken_Literal: {
2367 // We have stashed the starting pointer in the ptr_data field. Use it.
2368 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002369 return createCXString(llvm::StringRef(Text, 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 +00002372 case CXToken_Punctuation:
2373 case CXToken_Comment:
2374 break;
2375 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002376
2377 // We have to find the starting buffer pointer the hard way, by
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002378 // deconstructing the source location.
2379 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2380 if (!CXXUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002381 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002382
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002383 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
2384 std::pair<FileID, unsigned> LocInfo
2385 = CXXUnit->getSourceManager().getDecomposedLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +00002386 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002387 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00002388 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
2389 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00002390 return createCXString("");
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002391
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002392 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002393}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002394
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002395CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
2396 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2397 if (!CXXUnit)
2398 return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002399
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002400 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
2401 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
2402}
2403
2404CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
2405 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregor5352ac02010-01-28 00:27:43 +00002406 if (!CXXUnit)
2407 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002408
2409 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002410 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
2411}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002412
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002413void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
2414 CXToken **Tokens, unsigned *NumTokens) {
2415 if (Tokens)
2416 *Tokens = 0;
2417 if (NumTokens)
2418 *NumTokens = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002419
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002420 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2421 if (!CXXUnit || !Tokens || !NumTokens)
2422 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002423
Douglas Gregorbdf60622010-03-05 21:16:25 +00002424 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
2425
Daniel Dunbar85b988f2010-02-14 08:31:57 +00002426 SourceRange R = cxloc::translateCXSourceRange(Range);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002427 if (R.isInvalid())
2428 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002429
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002430 SourceManager &SourceMgr = CXXUnit->getSourceManager();
2431 std::pair<FileID, unsigned> BeginLocInfo
2432 = SourceMgr.getDecomposedLoc(R.getBegin());
2433 std::pair<FileID, unsigned> EndLocInfo
2434 = SourceMgr.getDecomposedLoc(R.getEnd());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002435
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002436 // Cannot tokenize across files.
2437 if (BeginLocInfo.first != EndLocInfo.first)
2438 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002439
2440 // Create a lexer
Douglas Gregorf715ca12010-03-16 00:06:06 +00002441 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002442 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00002443 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
Douglas Gregor47a3fcd2010-03-16 20:26:15 +00002444 if (Invalid)
2445 return;
Douglas Gregoraea67db2010-03-15 22:54:52 +00002446
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002447 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
2448 CXXUnit->getASTContext().getLangOptions(),
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002449 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002450 Lex.SetCommentRetentionState(true);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002451
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002452 // Lex tokens until we hit the end of the range.
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002453 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002454 llvm::SmallVector<CXToken, 32> CXTokens;
2455 Token Tok;
2456 do {
2457 // Lex the next token
2458 Lex.LexFromRawLexer(Tok);
2459 if (Tok.is(tok::eof))
2460 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002461
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002462 // Initialize the CXToken.
2463 CXToken CXTok;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002464
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002465 // - Common fields
2466 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
2467 CXTok.int_data[2] = Tok.getLength();
2468 CXTok.int_data[3] = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002469
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002470 // - Kind-specific fields
2471 if (Tok.isLiteral()) {
2472 CXTok.int_data[0] = CXToken_Literal;
2473 CXTok.ptr_data = (void *)Tok.getLiteralData();
2474 } else if (Tok.is(tok::identifier)) {
Douglas Gregoraea67db2010-03-15 22:54:52 +00002475 // Lookup the identifier to determine whether we have a keyword.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002476 std::pair<FileID, unsigned> LocInfo
2477 = SourceMgr.getDecomposedLoc(Tok.getLocation());
Douglas Gregorf715ca12010-03-16 00:06:06 +00002478 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002479 llvm::StringRef Buf
Douglas Gregorf715ca12010-03-16 00:06:06 +00002480 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
2481 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00002482 return;
2483
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002484 const char *StartPos = Buf.data() + LocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002485 IdentifierInfo *II
2486 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok, StartPos);
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00002487
2488 if (II->getObjCKeywordID() != tok::objc_not_keyword) {
2489 CXTok.int_data[0] = CXToken_Keyword;
2490 }
2491 else {
2492 CXTok.int_data[0] = II->getTokenID() == tok::identifier?
2493 CXToken_Identifier
2494 : CXToken_Keyword;
2495 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002496 CXTok.ptr_data = II;
2497 } else if (Tok.is(tok::comment)) {
2498 CXTok.int_data[0] = CXToken_Comment;
2499 CXTok.ptr_data = 0;
2500 } else {
2501 CXTok.int_data[0] = CXToken_Punctuation;
2502 CXTok.ptr_data = 0;
2503 }
2504 CXTokens.push_back(CXTok);
2505 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002506
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002507 if (CXTokens.empty())
2508 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002509
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002510 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
2511 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
2512 *NumTokens = CXTokens.size();
2513}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002514
Ted Kremenek6db61092010-05-05 00:55:15 +00002515void clang_disposeTokens(CXTranslationUnit TU,
2516 CXToken *Tokens, unsigned NumTokens) {
2517 free(Tokens);
2518}
2519
2520} // end: extern "C"
2521
2522//===----------------------------------------------------------------------===//
2523// Token annotation APIs.
2524//===----------------------------------------------------------------------===//
2525
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002526typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002527static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
2528 CXCursor parent,
2529 CXClientData client_data);
Ted Kremenek6db61092010-05-05 00:55:15 +00002530namespace {
2531class AnnotateTokensWorker {
2532 AnnotateTokensData &Annotated;
Ted Kremenek11949cb2010-05-05 00:55:17 +00002533 CXToken *Tokens;
2534 CXCursor *Cursors;
2535 unsigned NumTokens;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002536 unsigned TokIdx;
2537 CursorVisitor AnnotateVis;
2538 SourceManager &SrcMgr;
2539
2540 bool MoreTokens() const { return TokIdx < NumTokens; }
2541 unsigned NextToken() const { return TokIdx; }
2542 void AdvanceToken() { ++TokIdx; }
2543 SourceLocation GetTokenLoc(unsigned tokI) {
2544 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
2545 }
2546
Ted Kremenek6db61092010-05-05 00:55:15 +00002547public:
Ted Kremenek11949cb2010-05-05 00:55:17 +00002548 AnnotateTokensWorker(AnnotateTokensData &annotated,
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002549 CXToken *tokens, CXCursor *cursors, unsigned numTokens,
2550 ASTUnit *CXXUnit, SourceRange RegionOfInterest)
Ted Kremenek11949cb2010-05-05 00:55:17 +00002551 : Annotated(annotated), Tokens(tokens), Cursors(cursors),
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002552 NumTokens(numTokens), TokIdx(0),
2553 AnnotateVis(CXXUnit, AnnotateTokensVisitor, this,
2554 Decl::MaxPCHLevel, RegionOfInterest),
2555 SrcMgr(CXXUnit->getSourceManager()) {}
Ted Kremenek11949cb2010-05-05 00:55:17 +00002556
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002557 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
Ted Kremenek6db61092010-05-05 00:55:15 +00002558 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002559 void AnnotateTokens(CXCursor parent);
Ted Kremenek6db61092010-05-05 00:55:15 +00002560};
2561}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002562
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002563void AnnotateTokensWorker::AnnotateTokens(CXCursor parent) {
2564 // Walk the AST within the region of interest, annotating tokens
2565 // along the way.
2566 VisitChildren(parent);
Ted Kremenek11949cb2010-05-05 00:55:17 +00002567
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002568 for (unsigned I = 0 ; I < TokIdx ; ++I) {
2569 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
2570 if (Pos != Annotated.end())
2571 Cursors[I] = Pos->second;
2572 }
2573
2574 // Finish up annotating any tokens left.
2575 if (!MoreTokens())
2576 return;
2577
2578 const CXCursor &C = clang_getNullCursor();
2579 for (unsigned I = TokIdx ; I < NumTokens ; ++I) {
2580 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
2581 Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second;
Ted Kremenek11949cb2010-05-05 00:55:17 +00002582 }
2583}
2584
Ted Kremenek6db61092010-05-05 00:55:15 +00002585enum CXChildVisitResult
2586AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002587 CXSourceLocation Loc = clang_getCursorLocation(cursor);
2588 // We can always annotate a preprocessing directive/macro instantiation.
2589 if (clang_isPreprocessing(cursor.kind)) {
2590 Annotated[Loc.int_data] = cursor;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002591 return CXChildVisit_Recurse;
2592 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002593
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002594 SourceRange cursorRange = getRawCursorExtent(cursor);
Ted Kremeneka333c662010-05-12 05:29:33 +00002595
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002596 if (cursorRange.isInvalid())
2597 return CXChildVisit_Continue;
Ted Kremeneka333c662010-05-12 05:29:33 +00002598
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002599 SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data);
2600
Ted Kremeneka333c662010-05-12 05:29:33 +00002601 // Adjust the annotated range based specific declarations.
2602 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
2603 if (cursorK >= CXCursor_FirstDecl && cursorK <= CXCursor_LastDecl) {
Ted Kremenek23173d72010-05-18 21:09:07 +00002604 Decl *D = cxcursor::getCursorDecl(cursor);
2605 // Don't visit synthesized ObjC methods, since they have no syntatic
2606 // representation in the source.
2607 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
2608 if (MD->isSynthesized())
2609 return CXChildVisit_Continue;
2610 }
2611 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
Ted Kremeneka333c662010-05-12 05:29:33 +00002612 if (TypeSourceInfo *TI = DD->getTypeSourceInfo()) {
2613 TypeLoc TL = TI->getTypeLoc();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00002614 SourceLocation TLoc = TL.getSourceRange().getBegin();
Ted Kremenek6bfd5332010-05-13 15:38:38 +00002615 if (TLoc.isValid() &&
2616 SrcMgr.isBeforeInTranslationUnit(TLoc, L))
Ted Kremeneka333c662010-05-12 05:29:33 +00002617 cursorRange.setBegin(TLoc);
Ted Kremeneka333c662010-05-12 05:29:33 +00002618 }
2619 }
2620 }
2621
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002622 const enum CXCursorKind K = clang_getCursorKind(parent);
2623 const CXCursor updateC =
2624 (clang_isInvalid(K) || K == CXCursor_TranslationUnit ||
2625 L.isMacroID())
2626 ? clang_getNullCursor() : parent;
2627
2628 while (MoreTokens()) {
2629 const unsigned I = NextToken();
2630 SourceLocation TokLoc = GetTokenLoc(I);
2631 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
2632 case RangeBefore:
2633 Cursors[I] = updateC;
2634 AdvanceToken();
2635 continue;
2636 case RangeAfter:
2637 return CXChildVisit_Continue;
2638 case RangeOverlap:
2639 break;
2640 }
2641 break;
2642 }
2643
2644 // Visit children to get their cursor information.
2645 const unsigned BeforeChildren = NextToken();
2646 VisitChildren(cursor);
2647 const unsigned AfterChildren = NextToken();
2648
2649 // Adjust 'Last' to the last token within the extent of the cursor.
2650 while (MoreTokens()) {
2651 const unsigned I = NextToken();
2652 SourceLocation TokLoc = GetTokenLoc(I);
2653 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
2654 case RangeBefore:
2655 assert(0 && "Infeasible");
2656 case RangeAfter:
2657 break;
2658 case RangeOverlap:
2659 Cursors[I] = updateC;
2660 AdvanceToken();
2661 continue;
2662 }
2663 break;
2664 }
2665 const unsigned Last = NextToken();
Ted Kremenek6db61092010-05-05 00:55:15 +00002666
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002667 // Scan the tokens that are at the beginning of the cursor, but are not
2668 // capture by the child cursors.
2669
2670 // For AST elements within macros, rely on a post-annotate pass to
2671 // to correctly annotate the tokens with cursors. Otherwise we can
2672 // get confusing results of having tokens that map to cursors that really
2673 // are expanded by an instantiation.
2674 if (L.isMacroID())
2675 cursor = clang_getNullCursor();
2676
2677 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
2678 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
2679 break;
2680 Cursors[I] = cursor;
2681 }
2682 // Scan the tokens that are at the end of the cursor, but are not captured
2683 // but the child cursors.
2684 for (unsigned I = AfterChildren; I != Last; ++I)
2685 Cursors[I] = cursor;
2686
2687 TokIdx = Last;
2688 return CXChildVisit_Continue;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002689}
2690
Ted Kremenek6db61092010-05-05 00:55:15 +00002691static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
2692 CXCursor parent,
2693 CXClientData client_data) {
2694 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
2695}
2696
2697extern "C" {
2698
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002699void clang_annotateTokens(CXTranslationUnit TU,
2700 CXToken *Tokens, unsigned NumTokens,
2701 CXCursor *Cursors) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002702
2703 if (NumTokens == 0 || !Tokens || !Cursors)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002704 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002705
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002706 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002707 if (!CXXUnit) {
2708 // Any token we don't specifically annotate will have a NULL cursor.
2709 const CXCursor &C = clang_getNullCursor();
2710 for (unsigned I = 0; I != NumTokens; ++I)
2711 Cursors[I] = C;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002712 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002713 }
2714
Douglas Gregorbdf60622010-03-05 21:16:25 +00002715 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002716
Douglas Gregor0396f462010-03-19 05:22:59 +00002717 // Determine the region of interest, which contains all of the tokens.
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002718 SourceRange RegionOfInterest;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002719 RegionOfInterest.setBegin(cxloc::translateSourceLocation(
2720 clang_getTokenLocation(TU, Tokens[0])));
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002721 RegionOfInterest.setEnd(cxloc::translateSourceLocation(
2722 clang_getTokenLocation(TU,
2723 Tokens[NumTokens - 1])));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002724
Douglas Gregor0396f462010-03-19 05:22:59 +00002725 // A mapping from the source locations found when re-lexing or traversing the
2726 // region of interest to the corresponding cursors.
2727 AnnotateTokensData Annotated;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002728
2729 // Relex the tokens within the source range to look for preprocessing
Douglas Gregor0396f462010-03-19 05:22:59 +00002730 // directives.
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002731 SourceManager &SourceMgr = CXXUnit->getSourceManager();
2732 std::pair<FileID, unsigned> BeginLocInfo
2733 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
2734 std::pair<FileID, unsigned> EndLocInfo
2735 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002736
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002737 llvm::StringRef Buffer;
Douglas Gregor0396f462010-03-19 05:22:59 +00002738 bool Invalid = false;
2739 if (BeginLocInfo.first == EndLocInfo.first &&
2740 ((Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid)),true) &&
2741 !Invalid) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002742 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
2743 CXXUnit->getASTContext().getLangOptions(),
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002744 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002745 Buffer.end());
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002746 Lex.SetCommentRetentionState(true);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002747
2748 // Lex tokens in raw mode until we hit the end of the range, to avoid
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002749 // entering #includes or expanding macros.
Douglas Gregor48072312010-03-18 15:23:44 +00002750 while (true) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002751 Token Tok;
2752 Lex.LexFromRawLexer(Tok);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002753
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002754 reprocess:
2755 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
2756 // We have found a preprocessing directive. Gobble it up so that we
2757 // don't see it while preprocessing these tokens later, but keep track of
2758 // all of the token locations inside this preprocessing directive so that
2759 // we can annotate them appropriately.
2760 //
2761 // FIXME: Some simple tests here could identify macro definitions and
2762 // #undefs, to provide specific cursor kinds for those.
2763 std::vector<SourceLocation> Locations;
2764 do {
2765 Locations.push_back(Tok.getLocation());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002766 Lex.LexFromRawLexer(Tok);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002767 } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002768
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002769 using namespace cxcursor;
2770 CXCursor Cursor
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002771 = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
2772 Locations.back()),
Ted Kremenek6db61092010-05-05 00:55:15 +00002773 CXXUnit);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002774 for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
2775 Annotated[Locations[I].getRawEncoding()] = Cursor;
2776 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002777
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002778 if (Tok.isAtStartOfLine())
2779 goto reprocess;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002780
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002781 continue;
2782 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002783
Douglas Gregor48072312010-03-18 15:23:44 +00002784 if (Tok.is(tok::eof))
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002785 break;
2786 }
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002787 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002788
Douglas Gregor0396f462010-03-19 05:22:59 +00002789 // Annotate all of the source locations in the region of interest that map to
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002790 // a specific cursor.
2791 AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens,
2792 CXXUnit, RegionOfInterest);
2793 W.AnnotateTokens(clang_getTranslationUnitCursor(CXXUnit));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002794}
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002795} // end: extern "C"
2796
2797//===----------------------------------------------------------------------===//
Ted Kremenek16b42592010-03-03 06:36:57 +00002798// Operations for querying linkage of a cursor.
2799//===----------------------------------------------------------------------===//
2800
2801extern "C" {
2802CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
Douglas Gregor0396f462010-03-19 05:22:59 +00002803 if (!clang_isDeclaration(cursor.kind))
2804 return CXLinkage_Invalid;
2805
Ted Kremenek16b42592010-03-03 06:36:57 +00002806 Decl *D = cxcursor::getCursorDecl(cursor);
2807 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
2808 switch (ND->getLinkage()) {
2809 case NoLinkage: return CXLinkage_NoLinkage;
2810 case InternalLinkage: return CXLinkage_Internal;
2811 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
2812 case ExternalLinkage: return CXLinkage_External;
2813 };
2814
2815 return CXLinkage_Invalid;
2816}
2817} // end: extern "C"
2818
2819//===----------------------------------------------------------------------===//
Ted Kremenek45e1dae2010-04-12 21:22:16 +00002820// Operations for querying language of a cursor.
2821//===----------------------------------------------------------------------===//
2822
2823static CXLanguageKind getDeclLanguage(const Decl *D) {
2824 switch (D->getKind()) {
2825 default:
2826 break;
2827 case Decl::ImplicitParam:
2828 case Decl::ObjCAtDefsField:
2829 case Decl::ObjCCategory:
2830 case Decl::ObjCCategoryImpl:
2831 case Decl::ObjCClass:
2832 case Decl::ObjCCompatibleAlias:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00002833 case Decl::ObjCForwardProtocol:
2834 case Decl::ObjCImplementation:
2835 case Decl::ObjCInterface:
2836 case Decl::ObjCIvar:
2837 case Decl::ObjCMethod:
2838 case Decl::ObjCProperty:
2839 case Decl::ObjCPropertyImpl:
2840 case Decl::ObjCProtocol:
2841 return CXLanguage_ObjC;
2842 case Decl::CXXConstructor:
2843 case Decl::CXXConversion:
2844 case Decl::CXXDestructor:
2845 case Decl::CXXMethod:
2846 case Decl::CXXRecord:
2847 case Decl::ClassTemplate:
2848 case Decl::ClassTemplatePartialSpecialization:
2849 case Decl::ClassTemplateSpecialization:
2850 case Decl::Friend:
2851 case Decl::FriendTemplate:
2852 case Decl::FunctionTemplate:
2853 case Decl::LinkageSpec:
2854 case Decl::Namespace:
2855 case Decl::NamespaceAlias:
2856 case Decl::NonTypeTemplateParm:
2857 case Decl::StaticAssert:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00002858 case Decl::TemplateTemplateParm:
2859 case Decl::TemplateTypeParm:
2860 case Decl::UnresolvedUsingTypename:
2861 case Decl::UnresolvedUsingValue:
2862 case Decl::Using:
2863 case Decl::UsingDirective:
2864 case Decl::UsingShadow:
2865 return CXLanguage_CPlusPlus;
2866 }
2867
2868 return CXLanguage_C;
2869}
2870
2871extern "C" {
2872CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
2873 if (clang_isDeclaration(cursor.kind))
2874 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
2875
2876 return CXLanguage_Invalid;
2877}
2878} // end: extern "C"
2879
Ted Kremenek9ada39a2010-05-17 20:06:56 +00002880
2881//===----------------------------------------------------------------------===//
2882// C++ AST instrospection.
2883//===----------------------------------------------------------------------===//
2884
2885extern "C" {
2886unsigned clang_CXXMethod_isStatic(CXCursor C) {
2887 if (!clang_isDeclaration(C.kind))
2888 return 0;
2889 CXXMethodDecl *D = dyn_cast<CXXMethodDecl>(cxcursor::getCursorDecl(C));
2890 return (D && D->isStatic()) ? 1 : 0;
Ted Kremenek40b492a2010-05-17 20:12:45 +00002891}
Ted Kremenekb12903e2010-05-18 22:32:15 +00002892
Ted Kremenek9ada39a2010-05-17 20:06:56 +00002893} // end: extern "C"
2894
Ted Kremenek45e1dae2010-04-12 21:22:16 +00002895//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00002896// CXString Operations.
2897//===----------------------------------------------------------------------===//
2898
2899extern "C" {
2900const char *clang_getCString(CXString string) {
2901 return string.Spelling;
2902}
2903
2904void clang_disposeString(CXString string) {
2905 if (string.MustFreeString && string.Spelling)
2906 free((void*)string.Spelling);
2907}
Ted Kremenek04bb7162010-01-22 22:44:15 +00002908
Ted Kremenekfb480492010-01-13 21:46:36 +00002909} // end: extern "C"
Ted Kremenek04bb7162010-01-22 22:44:15 +00002910
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002911namespace clang { namespace cxstring {
2912CXString createCXString(const char *String, bool DupString){
2913 CXString Str;
2914 if (DupString) {
2915 Str.Spelling = strdup(String);
2916 Str.MustFreeString = 1;
2917 } else {
2918 Str.Spelling = String;
2919 Str.MustFreeString = 0;
2920 }
2921 return Str;
2922}
2923
2924CXString createCXString(llvm::StringRef String, bool DupString) {
2925 CXString Result;
2926 if (DupString || (!String.empty() && String.data()[String.size()] != 0)) {
2927 char *Spelling = (char *)malloc(String.size() + 1);
2928 memmove(Spelling, String.data(), String.size());
2929 Spelling[String.size()] = 0;
2930 Result.Spelling = Spelling;
2931 Result.MustFreeString = 1;
2932 } else {
2933 Result.Spelling = String.data();
2934 Result.MustFreeString = 0;
2935 }
2936 return Result;
2937}
2938}}
2939
Ted Kremenek04bb7162010-01-22 22:44:15 +00002940//===----------------------------------------------------------------------===//
2941// Misc. utility functions.
2942//===----------------------------------------------------------------------===//
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002943
Ted Kremenek04bb7162010-01-22 22:44:15 +00002944extern "C" {
2945
Ted Kremeneka2a9d6e2010-02-12 22:54:40 +00002946CXString clang_getClangVersion() {
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002947 return createCXString(getClangFullVersion());
Ted Kremenek04bb7162010-01-22 22:44:15 +00002948}
2949
2950} // end: extern "C"