blob: c3095e7c915e988fd7401e4db6684868cda166af [file] [log] [blame]
Ted Kremenekd2fa5662009-08-26 22:36:44 +00001//===- CIndex.cpp - Clang-C Source Indexing Library -----------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00007//
Ted Kremenekd2fa5662009-08-26 22:36:44 +00008//===----------------------------------------------------------------------===//
9//
Ted Kremenekab188932010-01-05 19:32:54 +000010// This file implements the main API hooks in the Clang-C Source Indexing
11// library.
Ted Kremenekd2fa5662009-08-26 22:36:44 +000012//
13//===----------------------------------------------------------------------===//
14
Ted Kremenekab188932010-01-05 19:32:54 +000015#include "CIndexer.h"
Ted Kremenek16c440a2010-01-15 20:35:54 +000016#include "CXCursor.h"
Ted Kremeneka297de22010-01-25 22:34:44 +000017#include "CXSourceLocation.h"
Douglas Gregor5352ac02010-01-28 00:27:43 +000018#include "CIndexDiagnostic.h"
Ted Kremenekab188932010-01-05 19:32:54 +000019
Ted Kremenek04bb7162010-01-22 22:44:15 +000020#include "clang/Basic/Version.h"
Douglas Gregor936ea3b2010-01-28 00:56:43 +000021
Steve Naroff50398192009-08-28 15:28:48 +000022#include "clang/AST/DeclVisitor.h"
Steve Narofffb570422009-09-22 19:25:29 +000023#include "clang/AST/StmtVisitor.h"
Douglas Gregor7d0d40e2010-01-21 16:28:34 +000024#include "clang/AST/TypeLocVisitor.h"
Benjamin Kramerb846deb2010-04-12 19:45:50 +000025#include "clang/Basic/Diagnostic.h"
26#include "clang/Frontend/ASTUnit.h"
27#include "clang/Frontend/CompilerInstance.h"
Douglas Gregor936ea3b2010-01-28 00:56:43 +000028#include "clang/Frontend/FrontendDiagnostic.h"
Ted Kremenekd8210652010-01-06 23:43:31 +000029#include "clang/Lex/Lexer.h"
Benjamin Kramerb846deb2010-04-12 19:45:50 +000030#include "clang/Lex/PreprocessingRecord.h"
Douglas Gregor33e9abd2010-01-22 19:49:59 +000031#include "clang/Lex/Preprocessor.h"
Douglas Gregor02465752009-10-16 21:24:31 +000032#include "llvm/Support/MemoryBuffer.h"
Benjamin Kramer0829a832009-10-18 11:19:36 +000033#include "llvm/System/Program.h"
Douglas Gregor0a812cf2010-02-18 23:07:20 +000034#include "llvm/System/Signals.h"
Ted Kremenekfc062212009-10-19 21:44:57 +000035
Benjamin Kramerc2a98162010-03-13 21:22:49 +000036// Needed to define L_TMPNAM on some systems.
37#include <cstdio>
38
Steve Naroff50398192009-08-28 15:28:48 +000039using namespace clang;
Ted Kremenek16c440a2010-01-15 20:35:54 +000040using namespace clang::cxcursor;
Ted Kremenekee4db4f2010-02-17 00:41:08 +000041using namespace clang::cxstring;
Steve Naroff50398192009-08-28 15:28:48 +000042
Ted Kremenek8a8da7d2010-01-06 03:42:32 +000043//===----------------------------------------------------------------------===//
44// Crash Reporting.
45//===----------------------------------------------------------------------===//
46
Ted Kremenekd7ffd082010-05-22 00:06:46 +000047#ifdef USE_CRASHTRACER
Ted Kremenek8a8da7d2010-01-06 03:42:32 +000048#include "clang/Analysis/Support/SaveAndRestore.h"
49// Integrate with crash reporter.
Daniel Dunbar439794e2010-05-20 23:50:23 +000050static const char *__crashreporter_info__ = 0;
51asm(".desc ___crashreporter_info__, 0x10");
Ted Kremenek6b569992010-02-17 21:12:23 +000052#define NUM_CRASH_STRINGS 32
Ted Kremenek29b72842010-01-07 22:49:05 +000053static unsigned crashtracer_counter = 0;
Ted Kremenek254ba7c2010-01-07 23:13:53 +000054static unsigned crashtracer_counter_id[NUM_CRASH_STRINGS] = { 0 };
Ted Kremenek29b72842010-01-07 22:49:05 +000055static const char *crashtracer_strings[NUM_CRASH_STRINGS] = { 0 };
56static const char *agg_crashtracer_strings[NUM_CRASH_STRINGS] = { 0 };
57
58static unsigned SetCrashTracerInfo(const char *str,
59 llvm::SmallString<1024> &AggStr) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +000060
Ted Kremenek254ba7c2010-01-07 23:13:53 +000061 unsigned slot = 0;
Ted Kremenek29b72842010-01-07 22:49:05 +000062 while (crashtracer_strings[slot]) {
63 if (++slot == NUM_CRASH_STRINGS)
64 slot = 0;
65 }
66 crashtracer_strings[slot] = str;
Ted Kremenek254ba7c2010-01-07 23:13:53 +000067 crashtracer_counter_id[slot] = ++crashtracer_counter;
Ted Kremenek29b72842010-01-07 22:49:05 +000068
69 // We need to create an aggregate string because multiple threads
70 // may be in this method at one time. The crash reporter string
71 // will attempt to overapproximate the set of in-flight invocations
72 // of this function. Race conditions can still cause this goal
73 // to not be achieved.
74 {
Ted Kremenekf0e23e82010-02-17 00:41:40 +000075 llvm::raw_svector_ostream Out(AggStr);
Ted Kremenek29b72842010-01-07 22:49:05 +000076 for (unsigned i = 0; i < NUM_CRASH_STRINGS; ++i)
77 if (crashtracer_strings[i]) Out << crashtracer_strings[i] << '\n';
78 }
79 __crashreporter_info__ = agg_crashtracer_strings[slot] = AggStr.c_str();
80 return slot;
81}
82
83static void ResetCrashTracerInfo(unsigned slot) {
Ted Kremenek254ba7c2010-01-07 23:13:53 +000084 unsigned max_slot = 0;
85 unsigned max_value = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +000086
Ted Kremenek254ba7c2010-01-07 23:13:53 +000087 crashtracer_strings[slot] = agg_crashtracer_strings[slot] = 0;
88
89 for (unsigned i = 0 ; i < NUM_CRASH_STRINGS; ++i)
90 if (agg_crashtracer_strings[i] &&
91 crashtracer_counter_id[i] > max_value) {
92 max_slot = i;
93 max_value = crashtracer_counter_id[i];
Ted Kremenek29b72842010-01-07 22:49:05 +000094 }
Ted Kremenek254ba7c2010-01-07 23:13:53 +000095
96 __crashreporter_info__ = agg_crashtracer_strings[max_slot];
Ted Kremenek29b72842010-01-07 22:49:05 +000097}
98
99namespace {
100class ArgsCrashTracerInfo {
101 llvm::SmallString<1024> CrashString;
102 llvm::SmallString<1024> AggregateString;
103 unsigned crashtracerSlot;
104public:
105 ArgsCrashTracerInfo(llvm::SmallVectorImpl<const char*> &Args)
106 : crashtracerSlot(0)
107 {
108 {
109 llvm::raw_svector_ostream Out(CrashString);
Ted Kremenek0baa9522010-03-05 22:43:25 +0000110 Out << "ClangCIndex [" << getClangFullVersion() << "]"
111 << "[createTranslationUnitFromSourceFile]: clang";
Ted Kremenek29b72842010-01-07 22:49:05 +0000112 for (llvm::SmallVectorImpl<const char*>::iterator I=Args.begin(),
113 E=Args.end(); I!=E; ++I)
114 Out << ' ' << *I;
115 }
116 crashtracerSlot = SetCrashTracerInfo(CrashString.c_str(),
117 AggregateString);
118 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000119
Ted Kremenek29b72842010-01-07 22:49:05 +0000120 ~ArgsCrashTracerInfo() {
121 ResetCrashTracerInfo(crashtracerSlot);
122 }
123};
124}
125#endif
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000126
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000127/// \brief The result of comparing two source ranges.
128enum RangeComparisonResult {
129 /// \brief Either the ranges overlap or one of the ranges is invalid.
130 RangeOverlap,
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000131
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000132 /// \brief The first range ends before the second range starts.
133 RangeBefore,
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000134
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000135 /// \brief The first range starts after the second range ends.
136 RangeAfter
137};
138
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000139/// \brief Compare two source ranges to determine their relative position in
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000140/// the translation unit.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000141static RangeComparisonResult RangeCompare(SourceManager &SM,
142 SourceRange R1,
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000143 SourceRange R2) {
144 assert(R1.isValid() && "First range is invalid?");
145 assert(R2.isValid() && "Second range is invalid?");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000146 if (R1.getEnd() != R2.getBegin() &&
Daniel Dunbard52864b2010-02-14 10:02:57 +0000147 SM.isBeforeInTranslationUnit(R1.getEnd(), R2.getBegin()))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000148 return RangeBefore;
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000149 if (R2.getEnd() != R1.getBegin() &&
Daniel Dunbard52864b2010-02-14 10:02:57 +0000150 SM.isBeforeInTranslationUnit(R2.getEnd(), R1.getBegin()))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000151 return RangeAfter;
152 return RangeOverlap;
153}
154
Ted Kremenekfbd84ca2010-05-05 00:55:23 +0000155/// \brief Determine if a source location falls within, before, or after a
156/// a given source range.
157static RangeComparisonResult LocationCompare(SourceManager &SM,
158 SourceLocation L, SourceRange R) {
159 assert(R.isValid() && "First range is invalid?");
160 assert(L.isValid() && "Second range is invalid?");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000161 if (L == R.getBegin() || L == R.getEnd())
Ted Kremenekfbd84ca2010-05-05 00:55:23 +0000162 return RangeOverlap;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +0000163 if (SM.isBeforeInTranslationUnit(L, R.getBegin()))
164 return RangeBefore;
165 if (SM.isBeforeInTranslationUnit(R.getEnd(), L))
166 return RangeAfter;
167 return RangeOverlap;
168}
169
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000170/// \brief Translate a Clang source range into a CIndex source range.
171///
172/// Clang internally represents ranges where the end location points to the
173/// start of the token at the end. However, for external clients it is more
174/// useful to have a CXSourceRange be a proper half-open interval. This routine
175/// does the appropriate translation.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000176CXSourceRange cxloc::translateSourceRange(const SourceManager &SM,
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000177 const LangOptions &LangOpts,
Chris Lattner0a76aae2010-06-18 22:45:06 +0000178 const CharSourceRange &R) {
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000179 // We want the last character in this location, so we will adjust the
Douglas Gregor6a5a23f2010-03-19 21:51:54 +0000180 // location accordingly.
181 // FIXME: How do do this with a macro instantiation location?
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000182 SourceLocation EndLoc = R.getEnd();
Chris Lattner0a76aae2010-06-18 22:45:06 +0000183 if (R.isTokenRange() && !EndLoc.isInvalid() && EndLoc.isFileID()) {
Douglas Gregor6a5a23f2010-03-19 21:51:54 +0000184 unsigned Length = Lexer::MeasureTokenLength(EndLoc, SM, LangOpts);
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000185 EndLoc = EndLoc.getFileLocWithOffset(Length);
186 }
187
188 CXSourceRange Result = { { (void *)&SM, (void *)&LangOpts },
189 R.getBegin().getRawEncoding(),
190 EndLoc.getRawEncoding() };
191 return Result;
192}
Douglas Gregor1db19de2010-01-19 21:36:55 +0000193
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000194//===----------------------------------------------------------------------===//
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000195// Cursor visitor.
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000196//===----------------------------------------------------------------------===//
197
Steve Naroff89922f82009-08-31 00:59:03 +0000198namespace {
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000199
Douglas Gregorb1373d02010-01-20 20:59:29 +0000200// Cursor visitor.
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000201class CursorVisitor : public DeclVisitor<CursorVisitor, bool>,
Douglas Gregora59e3902010-01-21 23:27:09 +0000202 public TypeLocVisitor<CursorVisitor, bool>,
203 public StmtVisitor<CursorVisitor, bool>
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000204{
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000205 /// \brief The translation unit we are traversing.
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000206 ASTUnit *TU;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000207
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000208 /// \brief The parent cursor whose children we are traversing.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000209 CXCursor Parent;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000210
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000211 /// \brief The declaration that serves at the parent of any statement or
212 /// expression nodes.
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000213 Decl *StmtParent;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000214
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000215 /// \brief The visitor function.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000216 CXCursorVisitor Visitor;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000217
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000218 /// \brief The opaque client data, to be passed along to the visitor.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000219 CXClientData ClientData;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000220
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000221 // MaxPCHLevel - the maximum PCH level of declarations that we will pass on
222 // to the visitor. Declarations with a PCH level greater than this value will
223 // be suppressed.
224 unsigned MaxPCHLevel;
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000225
226 /// \brief When valid, a source range to which the cursor should restrict
227 /// its search.
228 SourceRange RegionOfInterest;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000229
Douglas Gregorb1373d02010-01-20 20:59:29 +0000230 using DeclVisitor<CursorVisitor, bool>::Visit;
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000231 using TypeLocVisitor<CursorVisitor, bool>::Visit;
Douglas Gregora59e3902010-01-21 23:27:09 +0000232 using StmtVisitor<CursorVisitor, bool>::Visit;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000233
234 /// \brief Determine whether this particular source range comes before, comes
235 /// after, or overlaps the region of interest.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000236 ///
Daniel Dunbard52864b2010-02-14 10:02:57 +0000237 /// \param R a half-open source range retrieved from the abstract syntax tree.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000238 RangeComparisonResult CompareRegionOfInterest(SourceRange R);
239
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000240 class SetParentRAII {
241 CXCursor &Parent;
242 Decl *&StmtParent;
243 CXCursor OldParent;
244
245 public:
246 SetParentRAII(CXCursor &Parent, Decl *&StmtParent, CXCursor NewParent)
247 : Parent(Parent), StmtParent(StmtParent), OldParent(Parent)
248 {
249 Parent = NewParent;
250 if (clang_isDeclaration(Parent.kind))
251 StmtParent = getCursorDecl(Parent);
252 }
253
254 ~SetParentRAII() {
255 Parent = OldParent;
256 if (clang_isDeclaration(Parent.kind))
257 StmtParent = getCursorDecl(Parent);
258 }
259 };
260
Steve Naroff89922f82009-08-31 00:59:03 +0000261public:
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000262 CursorVisitor(ASTUnit *TU, CXCursorVisitor Visitor, CXClientData ClientData,
263 unsigned MaxPCHLevel,
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000264 SourceRange RegionOfInterest = SourceRange())
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000265 : TU(TU), Visitor(Visitor), ClientData(ClientData),
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000266 MaxPCHLevel(MaxPCHLevel), RegionOfInterest(RegionOfInterest)
Douglas Gregorb1373d02010-01-20 20:59:29 +0000267 {
268 Parent.kind = CXCursor_NoDeclFound;
269 Parent.data[0] = 0;
270 Parent.data[1] = 0;
271 Parent.data[2] = 0;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000272 StmtParent = 0;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000273 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000274
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000275 bool Visit(CXCursor Cursor, bool CheckedRegionOfInterest = false);
Douglas Gregor788f5a12010-03-20 00:41:21 +0000276
277 std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
278 getPreprocessedEntities();
279
Douglas Gregorb1373d02010-01-20 20:59:29 +0000280 bool VisitChildren(CXCursor Parent);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000281
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000282 // Declaration visitors
Ted Kremenek09dfa372010-02-18 05:46:33 +0000283 bool VisitAttributes(Decl *D);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000284 bool VisitBlockDecl(BlockDecl *B);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000285 bool VisitDeclContext(DeclContext *DC);
Ted Kremenek4540c9c2010-02-18 18:47:08 +0000286 bool VisitTranslationUnitDecl(TranslationUnitDecl *D);
287 bool VisitTypedefDecl(TypedefDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000288 bool VisitTagDecl(TagDecl *D);
289 bool VisitEnumConstantDecl(EnumConstantDecl *D);
290 bool VisitDeclaratorDecl(DeclaratorDecl *DD);
291 bool VisitFunctionDecl(FunctionDecl *ND);
292 bool VisitFieldDecl(FieldDecl *D);
Ted Kremenek4540c9c2010-02-18 18:47:08 +0000293 bool VisitVarDecl(VarDecl *);
Ted Kremenek79758f62010-02-18 22:36:18 +0000294 bool VisitObjCMethodDecl(ObjCMethodDecl *ND);
295 bool VisitObjCContainerDecl(ObjCContainerDecl *D);
296 bool VisitObjCCategoryDecl(ObjCCategoryDecl *ND);
297 bool VisitObjCProtocolDecl(ObjCProtocolDecl *PID);
Ted Kremenek23173d72010-05-18 21:09:07 +0000298 bool VisitObjCPropertyDecl(ObjCPropertyDecl *PD);
Ted Kremenek79758f62010-02-18 22:36:18 +0000299 bool VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
300 bool VisitObjCImplDecl(ObjCImplDecl *D);
301 bool VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
302 bool VisitObjCImplementationDecl(ObjCImplementationDecl *D);
303 // FIXME: ObjCPropertyDecl requires TypeSourceInfo, getter/setter locations,
304 // etc.
305 // FIXME: ObjCCompatibleAliasDecl requires aliased-class locations.
306 bool VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D);
307 bool VisitObjCClassDecl(ObjCClassDecl *D);
Ted Kremeneka0536d82010-05-07 01:04:29 +0000308 bool VisitLinkageSpecDecl(LinkageSpecDecl *D);
Ted Kremenek8f06e0e2010-05-06 23:38:21 +0000309 bool VisitNamespaceDecl(NamespaceDecl *D);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000310
311 // Type visitors
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000312 // FIXME: QualifiedTypeLoc doesn't provide any location information
313 bool VisitBuiltinTypeLoc(BuiltinTypeLoc TL);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000314 bool VisitTypedefTypeLoc(TypedefTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000315 bool VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL);
316 bool VisitTagTypeLoc(TagTypeLoc TL);
317 // FIXME: TemplateTypeParmTypeLoc doesn't provide any location information
318 bool VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL);
John McCallc12c5bb2010-05-15 11:32:37 +0000319 bool VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000320 bool VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL);
321 bool VisitPointerTypeLoc(PointerTypeLoc TL);
322 bool VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL);
323 bool VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL);
324 bool VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL);
325 bool VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL);
326 bool VisitFunctionTypeLoc(FunctionTypeLoc TL);
327 bool VisitArrayTypeLoc(ArrayTypeLoc TL);
Douglas Gregor2332c112010-01-21 20:48:56 +0000328 // FIXME: Implement for TemplateSpecializationTypeLoc
329 // FIXME: Implement visitors here when the unimplemented TypeLocs get
330 // implemented
331 bool VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL);
332 bool VisitTypeOfTypeLoc(TypeOfTypeLoc TL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000333
Douglas Gregora59e3902010-01-21 23:27:09 +0000334 // Statement visitors
335 bool VisitStmt(Stmt *S);
336 bool VisitDeclStmt(DeclStmt *S);
Douglas Gregorf5bab412010-01-22 01:00:11 +0000337 // FIXME: LabelStmt label?
338 bool VisitIfStmt(IfStmt *S);
339 bool VisitSwitchStmt(SwitchStmt *S);
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000340 bool VisitCaseStmt(CaseStmt *S);
Douglas Gregor263b47b2010-01-25 16:12:32 +0000341 bool VisitWhileStmt(WhileStmt *S);
342 bool VisitForStmt(ForStmt *S);
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000343// bool VisitSwitchCase(SwitchCase *S);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000344
Douglas Gregor336fd812010-01-23 00:40:08 +0000345 // Expression visitors
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000346 bool VisitBlockExpr(BlockExpr *B);
Douglas Gregor336fd812010-01-23 00:40:08 +0000347 bool VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000348 bool VisitExplicitCastExpr(ExplicitCastExpr *E);
Douglas Gregorc2350e52010-03-08 16:40:19 +0000349 bool VisitObjCMessageExpr(ObjCMessageExpr *E);
Douglas Gregor81d34662010-04-20 15:39:42 +0000350 bool VisitObjCEncodeExpr(ObjCEncodeExpr *E);
Douglas Gregor8ecdb652010-04-28 22:16:22 +0000351 bool VisitOffsetOfExpr(OffsetOfExpr *E);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000352 bool VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E);
Steve Naroff89922f82009-08-31 00:59:03 +0000353};
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000354
Ted Kremenekab188932010-01-05 19:32:54 +0000355} // end anonymous namespace
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000356
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000357static SourceRange getRawCursorExtent(CXCursor C);
358
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000359RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000360 return RangeCompare(TU->getSourceManager(), R, RegionOfInterest);
361}
362
Douglas Gregorb1373d02010-01-20 20:59:29 +0000363/// \brief Visit the given cursor and, if requested by the visitor,
364/// its children.
365///
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000366/// \param Cursor the cursor to visit.
367///
368/// \param CheckRegionOfInterest if true, then the caller already checked that
369/// this cursor is within the region of interest.
370///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000371/// \returns true if the visitation should be aborted, false if it
372/// should continue.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000373bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
Douglas Gregorb1373d02010-01-20 20:59:29 +0000374 if (clang_isInvalid(Cursor.kind))
375 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000376
Douglas Gregorb1373d02010-01-20 20:59:29 +0000377 if (clang_isDeclaration(Cursor.kind)) {
378 Decl *D = getCursorDecl(Cursor);
379 assert(D && "Invalid declaration cursor");
380 if (D->getPCHLevel() > MaxPCHLevel)
381 return false;
382
383 if (D->isImplicit())
384 return false;
385 }
386
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000387 // If we have a range of interest, and this cursor doesn't intersect with it,
388 // we're done.
389 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000390 SourceRange Range = getRawCursorExtent(Cursor);
Daniel Dunbarf408f322010-02-14 08:32:05 +0000391 if (Range.isInvalid() || CompareRegionOfInterest(Range))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000392 return false;
393 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000394
Douglas Gregorb1373d02010-01-20 20:59:29 +0000395 switch (Visitor(Cursor, Parent, ClientData)) {
396 case CXChildVisit_Break:
397 return true;
398
399 case CXChildVisit_Continue:
400 return false;
401
402 case CXChildVisit_Recurse:
403 return VisitChildren(Cursor);
404 }
405
Douglas Gregorfd643772010-01-25 16:45:46 +0000406 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000407}
408
Douglas Gregor788f5a12010-03-20 00:41:21 +0000409std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
410CursorVisitor::getPreprocessedEntities() {
411 PreprocessingRecord &PPRec
412 = *TU->getPreprocessor().getPreprocessingRecord();
413
414 bool OnlyLocalDecls
415 = !TU->isMainFileAST() && TU->getOnlyLocalDecls();
416
417 // There is no region of interest; we have to walk everything.
418 if (RegionOfInterest.isInvalid())
419 return std::make_pair(PPRec.begin(OnlyLocalDecls),
420 PPRec.end(OnlyLocalDecls));
421
422 // Find the file in which the region of interest lands.
423 SourceManager &SM = TU->getSourceManager();
424 std::pair<FileID, unsigned> Begin
425 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getBegin());
426 std::pair<FileID, unsigned> End
427 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getEnd());
428
429 // The region of interest spans files; we have to walk everything.
430 if (Begin.first != End.first)
431 return std::make_pair(PPRec.begin(OnlyLocalDecls),
432 PPRec.end(OnlyLocalDecls));
433
434 ASTUnit::PreprocessedEntitiesByFileMap &ByFileMap
435 = TU->getPreprocessedEntitiesByFile();
436 if (ByFileMap.empty()) {
437 // Build the mapping from files to sets of preprocessed entities.
438 for (PreprocessingRecord::iterator E = PPRec.begin(OnlyLocalDecls),
439 EEnd = PPRec.end(OnlyLocalDecls);
440 E != EEnd; ++E) {
441 std::pair<FileID, unsigned> P
442 = SM.getDecomposedInstantiationLoc((*E)->getSourceRange().getBegin());
443 ByFileMap[P.first].push_back(*E);
444 }
445 }
446
447 return std::make_pair(ByFileMap[Begin.first].begin(),
448 ByFileMap[Begin.first].end());
449}
450
Douglas Gregorb1373d02010-01-20 20:59:29 +0000451/// \brief Visit the children of the given cursor.
452///
453/// \returns true if the visitation should be aborted, false if it
454/// should continue.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000455bool CursorVisitor::VisitChildren(CXCursor Cursor) {
Douglas Gregora59e3902010-01-21 23:27:09 +0000456 if (clang_isReference(Cursor.kind)) {
457 // By definition, references have no children.
458 return false;
459 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000460
461 // Set the Parent field to Cursor, then back to its old value once we're
Douglas Gregorb1373d02010-01-20 20:59:29 +0000462 // done.
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000463 SetParentRAII SetParent(Parent, StmtParent, Cursor);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000464
Douglas Gregorb1373d02010-01-20 20:59:29 +0000465 if (clang_isDeclaration(Cursor.kind)) {
466 Decl *D = getCursorDecl(Cursor);
467 assert(D && "Invalid declaration cursor");
Ted Kremenek539311e2010-02-18 18:47:01 +0000468 return VisitAttributes(D) || Visit(D);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000469 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000470
Douglas Gregora59e3902010-01-21 23:27:09 +0000471 if (clang_isStatement(Cursor.kind))
472 return Visit(getCursorStmt(Cursor));
473 if (clang_isExpression(Cursor.kind))
474 return Visit(getCursorExpr(Cursor));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000475
Douglas Gregorb1373d02010-01-20 20:59:29 +0000476 if (clang_isTranslationUnit(Cursor.kind)) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000477 ASTUnit *CXXUnit = getCursorASTUnit(Cursor);
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000478 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
479 RegionOfInterest.isInvalid()) {
Douglas Gregor7b691f332010-01-20 21:13:59 +0000480 const std::vector<Decl*> &TLDs = CXXUnit->getTopLevelDecls();
481 for (std::vector<Decl*>::const_iterator it = TLDs.begin(),
482 ie = TLDs.end(); it != ie; ++it) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000483 if (Visit(MakeCXCursor(*it, CXXUnit), true))
Douglas Gregor7b691f332010-01-20 21:13:59 +0000484 return true;
485 }
Douglas Gregor0396f462010-03-19 05:22:59 +0000486 } else if (VisitDeclContext(
487 CXXUnit->getASTContext().getTranslationUnitDecl()))
488 return true;
Bob Wilson3178cb62010-03-19 03:57:57 +0000489
Douglas Gregor0396f462010-03-19 05:22:59 +0000490 // Walk the preprocessing record.
Daniel Dunbar8de30ff2010-03-20 01:11:56 +0000491 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000492 // FIXME: Once we have the ability to deserialize a preprocessing record,
493 // do so.
Douglas Gregor788f5a12010-03-20 00:41:21 +0000494 PreprocessingRecord::iterator E, EEnd;
495 for (llvm::tie(E, EEnd) = getPreprocessedEntities(); E != EEnd; ++E) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000496 if (MacroInstantiation *MI = dyn_cast<MacroInstantiation>(*E)) {
497 if (Visit(MakeMacroInstantiationCursor(MI, CXXUnit)))
498 return true;
Douglas Gregor788f5a12010-03-20 00:41:21 +0000499
Douglas Gregor0396f462010-03-19 05:22:59 +0000500 continue;
501 }
502
503 if (MacroDefinition *MD = dyn_cast<MacroDefinition>(*E)) {
504 if (Visit(MakeMacroDefinitionCursor(MD, CXXUnit)))
505 return true;
506
507 continue;
508 }
509 }
510 }
Douglas Gregor7b691f332010-01-20 21:13:59 +0000511 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000512 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000513
Douglas Gregorb1373d02010-01-20 20:59:29 +0000514 // Nothing to visit at the moment.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000515 return false;
516}
517
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000518bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
John McCallfc929202010-06-04 22:33:30 +0000519 if (Visit(B->getSignatureAsWritten()->getTypeLoc()))
520 return true;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000521
Ted Kremenek664cffd2010-07-22 11:30:19 +0000522 if (Stmt *Body = B->getBody())
523 return Visit(MakeCXCursor(Body, StmtParent, TU));
524
525 return false;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000526}
527
Douglas Gregorb1373d02010-01-20 20:59:29 +0000528bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000529 for (DeclContext::decl_iterator
Douglas Gregorb1373d02010-01-20 20:59:29 +0000530 I = DC->decls_begin(), E = DC->decls_end(); I != E; ++I) {
Ted Kremenek09dfa372010-02-18 05:46:33 +0000531
Ted Kremenek23173d72010-05-18 21:09:07 +0000532 Decl *D = *I;
533 if (D->getLexicalDeclContext() != DC)
534 continue;
535
536 CXCursor Cursor = MakeCXCursor(D, TU);
Daniel Dunbard52864b2010-02-14 10:02:57 +0000537
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000538 if (RegionOfInterest.isValid()) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000539 SourceRange Range = getRawCursorExtent(Cursor);
Daniel Dunbard52864b2010-02-14 10:02:57 +0000540 if (Range.isInvalid())
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000541 continue;
Daniel Dunbard52864b2010-02-14 10:02:57 +0000542
543 switch (CompareRegionOfInterest(Range)) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000544 case RangeBefore:
545 // This declaration comes before the region of interest; skip it.
546 continue;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000547
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000548 case RangeAfter:
549 // This declaration comes after the region of interest; we're done.
550 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000551
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000552 case RangeOverlap:
553 // This declaration overlaps the region of interest; visit it.
554 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000555 }
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000556 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000557
Daniel Dunbard52864b2010-02-14 10:02:57 +0000558 if (Visit(Cursor, true))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000559 return true;
560 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000561
Douglas Gregorb1373d02010-01-20 20:59:29 +0000562 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000563}
564
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000565bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
566 llvm_unreachable("Translation units are visited directly by Visit()");
567 return false;
568}
569
570bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
571 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
572 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000573
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000574 return false;
575}
576
577bool CursorVisitor::VisitTagDecl(TagDecl *D) {
578 return VisitDeclContext(D);
579}
580
581bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
582 if (Expr *Init = D->getInitExpr())
583 return Visit(MakeCXCursor(Init, StmtParent, TU));
584 return false;
585}
586
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000587bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
588 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
589 if (Visit(TSInfo->getTypeLoc()))
590 return true;
591
592 return false;
593}
594
Douglas Gregorb1373d02010-01-20 20:59:29 +0000595bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000596 if (VisitDeclaratorDecl(ND))
597 return true;
598
Douglas Gregora59e3902010-01-21 23:27:09 +0000599 if (ND->isThisDeclarationADefinition() &&
600 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
601 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000602
Douglas Gregorb1373d02010-01-20 20:59:29 +0000603 return false;
604}
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000605
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000606bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
607 if (VisitDeclaratorDecl(D))
608 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000609
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000610 if (Expr *BitWidth = D->getBitWidth())
611 return Visit(MakeCXCursor(BitWidth, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000612
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000613 return false;
614}
615
616bool CursorVisitor::VisitVarDecl(VarDecl *D) {
617 if (VisitDeclaratorDecl(D))
618 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000619
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000620 if (Expr *Init = D->getInit())
621 return Visit(MakeCXCursor(Init, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000622
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000623 return false;
624}
625
626bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
Douglas Gregor4bc1cb62010-03-08 14:59:44 +0000627 if (TypeSourceInfo *TSInfo = ND->getResultTypeSourceInfo())
628 if (Visit(TSInfo->getTypeLoc()))
629 return true;
630
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000631 for (ObjCMethodDecl::param_iterator P = ND->param_begin(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000632 PEnd = ND->param_end();
633 P != PEnd; ++P) {
634 if (Visit(MakeCXCursor(*P, TU)))
635 return true;
636 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000637
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000638 if (ND->isThisDeclarationADefinition() &&
639 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
640 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000641
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000642 return false;
643}
644
Douglas Gregora59e3902010-01-21 23:27:09 +0000645bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
646 return VisitDeclContext(D);
647}
648
Douglas Gregorb1373d02010-01-20 20:59:29 +0000649bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000650 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
651 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000652 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000653
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000654 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
655 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
656 E = ND->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000657 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000658 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000659
Douglas Gregora59e3902010-01-21 23:27:09 +0000660 return VisitObjCContainerDecl(ND);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000661}
662
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000663bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
664 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
665 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
666 E = PID->protocol_end(); I != E; ++I, ++PL)
667 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
668 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000669
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000670 return VisitObjCContainerDecl(PID);
671}
672
Ted Kremenek23173d72010-05-18 21:09:07 +0000673bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
John McCallfc929202010-06-04 22:33:30 +0000674 if (Visit(PD->getTypeSourceInfo()->getTypeLoc()))
675 return true;
676
Ted Kremenek23173d72010-05-18 21:09:07 +0000677 // FIXME: This implements a workaround with @property declarations also being
678 // installed in the DeclContext for the @interface. Eventually this code
679 // should be removed.
680 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
681 if (!CDecl || !CDecl->IsClassExtension())
682 return false;
683
684 ObjCInterfaceDecl *ID = CDecl->getClassInterface();
685 if (!ID)
686 return false;
687
688 IdentifierInfo *PropertyId = PD->getIdentifier();
689 ObjCPropertyDecl *prevDecl =
690 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId);
691
692 if (!prevDecl)
693 return false;
694
695 // Visit synthesized methods since they will be skipped when visiting
696 // the @interface.
697 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
698 if (MD->isSynthesized())
699 if (Visit(MakeCXCursor(MD, TU)))
700 return true;
701
702 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
703 if (MD->isSynthesized())
704 if (Visit(MakeCXCursor(MD, TU)))
705 return true;
706
707 return false;
708}
709
Douglas Gregorb1373d02010-01-20 20:59:29 +0000710bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000711 // Issue callbacks for super class.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000712 if (D->getSuperClass() &&
713 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000714 D->getSuperClassLoc(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000715 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000716 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000717
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000718 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
719 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
720 E = D->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000721 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000722 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000723
Douglas Gregora59e3902010-01-21 23:27:09 +0000724 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000725}
726
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000727bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
728 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000729}
730
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000731bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
Ted Kremenekebfa3392010-03-19 20:39:03 +0000732 // 'ID' could be null when dealing with invalid code.
733 if (ObjCInterfaceDecl *ID = D->getClassInterface())
734 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
735 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000736
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000737 return VisitObjCImplDecl(D);
738}
739
740bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
741#if 0
742 // Issue callbacks for super class.
743 // FIXME: No source location information!
744 if (D->getSuperClass() &&
745 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000746 D->getSuperClassLoc(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000747 TU)))
748 return true;
749#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000750
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000751 return VisitObjCImplDecl(D);
752}
753
754bool CursorVisitor::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D) {
755 ObjCForwardProtocolDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
756 for (ObjCForwardProtocolDecl::protocol_iterator I = D->protocol_begin(),
757 E = D->protocol_end();
758 I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000759 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000760 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000761
762 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000763}
764
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000765bool CursorVisitor::VisitObjCClassDecl(ObjCClassDecl *D) {
766 for (ObjCClassDecl::iterator C = D->begin(), CEnd = D->end(); C != CEnd; ++C)
767 if (Visit(MakeCursorObjCClassRef(C->getInterface(), C->getLocation(), TU)))
768 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000769
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000770 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000771}
772
Ted Kremenek8f06e0e2010-05-06 23:38:21 +0000773bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
774 return VisitDeclContext(D);
775}
776
Ted Kremeneka0536d82010-05-07 01:04:29 +0000777bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
778 return VisitDeclContext(D);
779}
780
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000781bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
782 ASTContext &Context = TU->getASTContext();
783
784 // Some builtin types (such as Objective-C's "id", "sel", and
785 // "Class") have associated declarations. Create cursors for those.
786 QualType VisitType;
787 switch (TL.getType()->getAs<BuiltinType>()->getKind()) {
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000788 case BuiltinType::Void:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000789 case BuiltinType::Bool:
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000790 case BuiltinType::Char_U:
791 case BuiltinType::UChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000792 case BuiltinType::Char16:
793 case BuiltinType::Char32:
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000794 case BuiltinType::UShort:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000795 case BuiltinType::UInt:
796 case BuiltinType::ULong:
797 case BuiltinType::ULongLong:
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000798 case BuiltinType::UInt128:
799 case BuiltinType::Char_S:
800 case BuiltinType::SChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000801 case BuiltinType::WChar:
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000802 case BuiltinType::Short:
803 case BuiltinType::Int:
804 case BuiltinType::Long:
805 case BuiltinType::LongLong:
806 case BuiltinType::Int128:
807 case BuiltinType::Float:
808 case BuiltinType::Double:
809 case BuiltinType::LongDouble:
810 case BuiltinType::NullPtr:
811 case BuiltinType::Overload:
812 case BuiltinType::Dependent:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000813 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000814
815 case BuiltinType::UndeducedAuto: // FIXME: Deserves a cursor?
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000816 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000817
Ted Kremenekc4174cc2010-02-18 18:52:18 +0000818 case BuiltinType::ObjCId:
819 VisitType = Context.getObjCIdType();
820 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000821
822 case BuiltinType::ObjCClass:
823 VisitType = Context.getObjCClassType();
824 break;
825
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000826 case BuiltinType::ObjCSel:
827 VisitType = Context.getObjCSelType();
828 break;
829 }
830
831 if (!VisitType.isNull()) {
832 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000833 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000834 TU));
835 }
836
837 return false;
838}
839
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000840bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
841 return Visit(MakeCursorTypeRef(TL.getTypedefDecl(), TL.getNameLoc(), TU));
842}
843
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000844bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
845 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
846}
847
848bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
849 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
850}
851
852bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
853 if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
854 return true;
855
John McCallc12c5bb2010-05-15 11:32:37 +0000856 return false;
857}
858
859bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
860 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
861 return true;
862
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000863 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
864 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
865 TU)))
866 return true;
867 }
868
869 return false;
870}
871
872bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
John McCallc12c5bb2010-05-15 11:32:37 +0000873 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000874}
875
876bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
877 return Visit(TL.getPointeeLoc());
878}
879
880bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
881 return Visit(TL.getPointeeLoc());
882}
883
884bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
885 return Visit(TL.getPointeeLoc());
886}
887
888bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000889 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000890}
891
892bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000893 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000894}
895
896bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
897 if (Visit(TL.getResultLoc()))
898 return true;
899
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000900 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
Ted Kremenek5dbacb42010-04-07 00:27:13 +0000901 if (Decl *D = TL.getArg(I))
902 if (Visit(MakeCXCursor(D, TU)))
903 return true;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000904
905 return false;
906}
907
908bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
909 if (Visit(TL.getElementLoc()))
910 return true;
911
912 if (Expr *Size = TL.getSizeExpr())
913 return Visit(MakeCXCursor(Size, StmtParent, TU));
914
915 return false;
916}
917
Douglas Gregor2332c112010-01-21 20:48:56 +0000918bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
919 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
920}
921
922bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
923 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
924 return Visit(TSInfo->getTypeLoc());
925
926 return false;
927}
928
Douglas Gregora59e3902010-01-21 23:27:09 +0000929bool CursorVisitor::VisitStmt(Stmt *S) {
930 for (Stmt::child_iterator Child = S->child_begin(), ChildEnd = S->child_end();
931 Child != ChildEnd; ++Child) {
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000932 if (Stmt *C = *Child)
933 if (Visit(MakeCXCursor(C, StmtParent, TU)))
934 return true;
Douglas Gregora59e3902010-01-21 23:27:09 +0000935 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000936
Douglas Gregora59e3902010-01-21 23:27:09 +0000937 return false;
938}
939
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000940bool CursorVisitor::VisitCaseStmt(CaseStmt *S) {
941 // Specially handle CaseStmts because they can be nested, e.g.:
942 //
943 // case 1:
944 // case 2:
945 //
946 // In this case the second CaseStmt is the child of the first. Walking
947 // these recursively can blow out the stack.
948 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU);
949 while (true) {
950 // Set the Parent field to Cursor, then back to its old value once we're
951 // done.
952 SetParentRAII SetParent(Parent, StmtParent, Cursor);
953
954 if (Stmt *LHS = S->getLHS())
955 if (Visit(MakeCXCursor(LHS, StmtParent, TU)))
956 return true;
957 if (Stmt *RHS = S->getRHS())
958 if (Visit(MakeCXCursor(RHS, StmtParent, TU)))
959 return true;
960 if (Stmt *SubStmt = S->getSubStmt()) {
961 if (!isa<CaseStmt>(SubStmt))
962 return Visit(MakeCXCursor(SubStmt, StmtParent, TU));
963
964 // Specially handle 'CaseStmt' so that we don't blow out the stack.
965 CaseStmt *CS = cast<CaseStmt>(SubStmt);
966 Cursor = MakeCXCursor(CS, StmtParent, TU);
967 if (RegionOfInterest.isValid()) {
968 SourceRange Range = CS->getSourceRange();
969 if (Range.isInvalid() || CompareRegionOfInterest(Range))
970 return false;
971 }
972
973 switch (Visitor(Cursor, Parent, ClientData)) {
974 case CXChildVisit_Break: return true;
975 case CXChildVisit_Continue: return false;
976 case CXChildVisit_Recurse:
977 // Perform tail-recursion manually.
978 S = CS;
979 continue;
980 }
981 }
982 return false;
983 }
984}
985
Douglas Gregora59e3902010-01-21 23:27:09 +0000986bool CursorVisitor::VisitDeclStmt(DeclStmt *S) {
987 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
988 D != DEnd; ++D) {
Douglas Gregor263b47b2010-01-25 16:12:32 +0000989 if (*D && Visit(MakeCXCursor(*D, TU)))
Douglas Gregora59e3902010-01-21 23:27:09 +0000990 return true;
991 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000992
Douglas Gregora59e3902010-01-21 23:27:09 +0000993 return false;
994}
995
Douglas Gregorf5bab412010-01-22 01:00:11 +0000996bool CursorVisitor::VisitIfStmt(IfStmt *S) {
997 if (VarDecl *Var = S->getConditionVariable()) {
998 if (Visit(MakeCXCursor(Var, TU)))
999 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001000 }
1001
Douglas Gregor263b47b2010-01-25 16:12:32 +00001002 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1003 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +00001004 if (S->getThen() && Visit(MakeCXCursor(S->getThen(), StmtParent, TU)))
1005 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +00001006 if (S->getElse() && Visit(MakeCXCursor(S->getElse(), StmtParent, TU)))
1007 return true;
1008
1009 return false;
1010}
1011
1012bool CursorVisitor::VisitSwitchStmt(SwitchStmt *S) {
1013 if (VarDecl *Var = S->getConditionVariable()) {
1014 if (Visit(MakeCXCursor(Var, TU)))
1015 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001016 }
1017
Douglas Gregor263b47b2010-01-25 16:12:32 +00001018 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1019 return true;
1020 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
1021 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001022
Douglas Gregor263b47b2010-01-25 16:12:32 +00001023 return false;
1024}
1025
1026bool CursorVisitor::VisitWhileStmt(WhileStmt *S) {
1027 if (VarDecl *Var = S->getConditionVariable()) {
1028 if (Visit(MakeCXCursor(Var, TU)))
1029 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001030 }
1031
Douglas Gregor263b47b2010-01-25 16:12:32 +00001032 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1033 return true;
1034 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
Douglas Gregorf5bab412010-01-22 01:00:11 +00001035 return true;
1036
Douglas Gregor263b47b2010-01-25 16:12:32 +00001037 return false;
1038}
1039
1040bool CursorVisitor::VisitForStmt(ForStmt *S) {
1041 if (S->getInit() && Visit(MakeCXCursor(S->getInit(), StmtParent, TU)))
1042 return true;
1043 if (VarDecl *Var = S->getConditionVariable()) {
1044 if (Visit(MakeCXCursor(Var, TU)))
1045 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001046 }
1047
Douglas Gregor263b47b2010-01-25 16:12:32 +00001048 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1049 return true;
1050 if (S->getInc() && Visit(MakeCXCursor(S->getInc(), StmtParent, TU)))
1051 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +00001052 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
1053 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001054
Douglas Gregorf5bab412010-01-22 01:00:11 +00001055 return false;
1056}
1057
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00001058bool CursorVisitor::VisitBlockExpr(BlockExpr *B) {
1059 return Visit(B->getBlockDecl());
1060}
1061
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001062bool CursorVisitor::VisitOffsetOfExpr(OffsetOfExpr *E) {
1063 // FIXME: Visit fields as well?
1064 if (Visit(E->getTypeSourceInfo()->getTypeLoc()))
1065 return true;
1066
1067 return VisitExpr(E);
1068}
1069
Douglas Gregor336fd812010-01-23 00:40:08 +00001070bool CursorVisitor::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E) {
1071 if (E->isArgumentType()) {
1072 if (TypeSourceInfo *TSInfo = E->getArgumentTypeInfo())
1073 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001074
Douglas Gregor336fd812010-01-23 00:40:08 +00001075 return false;
1076 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001077
Douglas Gregor336fd812010-01-23 00:40:08 +00001078 return VisitExpr(E);
1079}
1080
1081bool CursorVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
1082 if (TypeSourceInfo *TSInfo = E->getTypeInfoAsWritten())
1083 if (Visit(TSInfo->getTypeLoc()))
1084 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001085
Douglas Gregor336fd812010-01-23 00:40:08 +00001086 return VisitCastExpr(E);
1087}
1088
1089bool CursorVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
1090 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
1091 if (Visit(TSInfo->getTypeLoc()))
1092 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001093
Douglas Gregor336fd812010-01-23 00:40:08 +00001094 return VisitExpr(E);
1095}
1096
Douglas Gregorc2350e52010-03-08 16:40:19 +00001097bool CursorVisitor::VisitObjCMessageExpr(ObjCMessageExpr *E) {
Douglas Gregor04badcf2010-04-21 00:45:42 +00001098 if (TypeSourceInfo *TSInfo = E->getClassReceiverTypeInfo())
1099 if (Visit(TSInfo->getTypeLoc()))
1100 return true;
Douglas Gregorc2350e52010-03-08 16:40:19 +00001101
1102 return VisitExpr(E);
1103}
1104
Douglas Gregor81d34662010-04-20 15:39:42 +00001105bool CursorVisitor::VisitObjCEncodeExpr(ObjCEncodeExpr *E) {
1106 return Visit(E->getEncodedTypeSourceInfo()->getTypeLoc());
1107}
1108
1109
Ted Kremenek09dfa372010-02-18 05:46:33 +00001110bool CursorVisitor::VisitAttributes(Decl *D) {
1111 for (const Attr *A = D->getAttrs(); A; A = A->getNext())
1112 if (Visit(MakeCXCursor(A, D, TU)))
1113 return true;
1114
1115 return false;
1116}
1117
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00001118extern "C" {
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001119CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
1120 int displayDiagnostics) {
Douglas Gregora030b7c2010-01-22 20:35:53 +00001121 CIndexer *CIdxr = new CIndexer();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001122 if (excludeDeclarationsFromPCH)
1123 CIdxr->setOnlyLocalDecls();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001124 if (displayDiagnostics)
1125 CIdxr->setDisplayDiagnostics();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001126 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +00001127}
1128
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001129void clang_disposeIndex(CXIndex CIdx) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001130 if (CIdx)
1131 delete static_cast<CIndexer *>(CIdx);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00001132}
1133
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001134void clang_setUseExternalASTGeneration(CXIndex CIdx, int value) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001135 if (CIdx) {
1136 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
1137 CXXIdx->setUseExternalASTGeneration(value);
1138 }
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001139}
1140
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001141CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
Douglas Gregora88084b2010-02-18 18:08:43 +00001142 const char *ast_filename) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001143 if (!CIdx)
1144 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001145
Douglas Gregor7d1d49d2009-10-16 20:01:17 +00001146 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001147
Douglas Gregor28019772010-04-05 23:52:57 +00001148 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
1149 return ASTUnit::LoadFromPCHFile(ast_filename, Diags,
Douglas Gregora88084b2010-02-18 18:08:43 +00001150 CXXIdx->getOnlyLocalDecls(),
1151 0, 0, true);
Steve Naroff600866c2009-08-27 19:51:58 +00001152}
1153
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001154CXTranslationUnit
1155clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
1156 const char *source_filename,
1157 int num_command_line_args,
Douglas Gregor4db64a42010-01-23 00:14:00 +00001158 const char **command_line_args,
1159 unsigned num_unsaved_files,
Douglas Gregora88084b2010-02-18 18:08:43 +00001160 struct CXUnsavedFile *unsaved_files) {
Douglas Gregor5a430212010-07-21 18:52:53 +00001161 return clang_parseTranslationUnit(CIdx, source_filename,
1162 command_line_args, num_command_line_args,
1163 unsaved_files, num_unsaved_files,
1164 CXTranslationUnit_DetailedPreprocessingRecord);
1165}
1166
1167CXTranslationUnit clang_parseTranslationUnit(CXIndex CIdx,
1168 const char *source_filename,
1169 const char **command_line_args,
1170 int num_command_line_args,
1171 struct CXUnsavedFile *unsaved_files,
1172 unsigned num_unsaved_files,
1173 unsigned options) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001174 if (!CIdx)
1175 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001176
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001177 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
1178
Douglas Gregor44c181a2010-07-23 00:33:23 +00001179 // The "editing" option implies other options.
1180 if (options & CXTranslationUnit_Editing)
1181 options |= CXTranslationUnit_PrecompiledPreamble;
1182 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
1183
Douglas Gregor5352ac02010-01-28 00:27:43 +00001184 // Configure the diagnostics.
1185 DiagnosticOptions DiagOpts;
Douglas Gregor28019772010-04-05 23:52:57 +00001186 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
1187 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001188
Douglas Gregor4db64a42010-01-23 00:14:00 +00001189 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
1190 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattnera0a270c2010-04-05 22:42:27 +00001191 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001192 const llvm::MemoryBuffer *Buffer
Chris Lattnera0a270c2010-04-05 22:42:27 +00001193 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregor4db64a42010-01-23 00:14:00 +00001194 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
1195 Buffer));
1196 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001197
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001198 if (!CXXIdx->getUseExternalASTGeneration()) {
1199 llvm::SmallVector<const char *, 16> Args;
1200
1201 // The 'source_filename' argument is optional. If the caller does not
1202 // specify it then it is assumed that the source file is specified
1203 // in the actual argument list.
1204 if (source_filename)
1205 Args.push_back(source_filename);
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00001206
1207 // Since the Clang C library is primarily used by batch tools dealing with
1208 // (often very broken) source code, where spell-checking can have a
1209 // significant negative impact on performance (particularly when
1210 // precompiled headers are involved), we disable it by default.
1211 // Note that we place this argument early in the list, so that it can be
1212 // overridden by the caller with "-fspell-checking".
Douglas Gregora0068fc2010-07-09 17:35:33 +00001213 Args.push_back("-fno-spell-checking");
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00001214
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001215 Args.insert(Args.end(), command_line_args,
1216 command_line_args + num_command_line_args);
Douglas Gregor5a430212010-07-21 18:52:53 +00001217
Douglas Gregor44c181a2010-07-23 00:33:23 +00001218 // Do we need the detailed preprocessing record?
Douglas Gregor5a430212010-07-21 18:52:53 +00001219 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
1220 Args.push_back("-Xclang");
1221 Args.push_back("-detailed-preprocessing-record");
1222 }
Douglas Gregor44c181a2010-07-23 00:33:23 +00001223
Douglas Gregor5352ac02010-01-28 00:27:43 +00001224 unsigned NumErrors = Diags->getNumErrors();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001225
Ted Kremenek29b72842010-01-07 22:49:05 +00001226#ifdef USE_CRASHTRACER
1227 ArgsCrashTracerInfo ACTI(Args);
Ted Kremenek8a8da7d2010-01-06 03:42:32 +00001228#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001229
Daniel Dunbar94220972009-12-05 02:17:18 +00001230 llvm::OwningPtr<ASTUnit> Unit(
1231 ASTUnit::LoadFromCommandLine(Args.data(), Args.data() + Args.size(),
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001232 Diags,
Daniel Dunbar869824e2009-12-13 03:46:13 +00001233 CXXIdx->getClangResourcesPath(),
Daniel Dunbar94220972009-12-05 02:17:18 +00001234 CXXIdx->getOnlyLocalDecls(),
Douglas Gregor4db64a42010-01-23 00:14:00 +00001235 RemappedFiles.data(),
Douglas Gregora88084b2010-02-18 18:08:43 +00001236 RemappedFiles.size(),
Douglas Gregor44c181a2010-07-23 00:33:23 +00001237 /*CaptureDiagnostics=*/true,
1238 PrecompilePreamble));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001239
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001240 if (NumErrors != Diags->getNumErrors()) {
Ted Kremenek34f6a322010-03-05 22:43:29 +00001241 // Make sure to check that 'Unit' is non-NULL.
1242 if (CXXIdx->getDisplayDiagnostics() && Unit.get()) {
Douglas Gregor405634b2010-04-05 18:10:21 +00001243 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
1244 DEnd = Unit->stored_diag_end();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001245 D != DEnd; ++D) {
1246 CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOptions());
Douglas Gregor274f1902010-02-22 23:17:23 +00001247 CXString Msg = clang_formatDiagnostic(&Diag,
1248 clang_defaultDiagnosticDisplayOptions());
1249 fprintf(stderr, "%s\n", clang_getCString(Msg));
1250 clang_disposeString(Msg);
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001251 }
Douglas Gregor274f1902010-02-22 23:17:23 +00001252#ifdef LLVM_ON_WIN32
1253 // On Windows, force a flush, since there may be multiple copies of
1254 // stderr and stdout in the file system, all with different buffers
1255 // but writing to the same device.
1256 fflush(stderr);
Ted Kremenek83c51842010-03-26 01:34:51 +00001257#endif
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001258 }
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001259 }
Daniel Dunbar94220972009-12-05 02:17:18 +00001260
1261 return Unit.take();
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001262 }
1263
Ted Kremenek139ba862009-10-22 00:03:57 +00001264 // Build up the arguments for invoking 'clang'.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001265 std::vector<const char *> argv;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001266
Ted Kremenek139ba862009-10-22 00:03:57 +00001267 // First add the complete path to the 'clang' executable.
1268 llvm::sys::Path ClangPath = static_cast<CIndexer *>(CIdx)->getClangPath();
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00001269 argv.push_back(ClangPath.c_str());
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001270
Ted Kremenek139ba862009-10-22 00:03:57 +00001271 // Add the '-emit-ast' option as our execution mode for 'clang'.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001272 argv.push_back("-emit-ast");
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001273
Ted Kremenek139ba862009-10-22 00:03:57 +00001274 // The 'source_filename' argument is optional. If the caller does not
1275 // specify it then it is assumed that the source file is specified
1276 // in the actual argument list.
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001277 if (source_filename)
1278 argv.push_back(source_filename);
Ted Kremenek139ba862009-10-22 00:03:57 +00001279
Steve Naroff37b5ac22009-10-15 20:50:09 +00001280 // Generate a temporary name for the AST file.
Ted Kremenek139ba862009-10-22 00:03:57 +00001281 argv.push_back("-o");
Benjamin Kramerc2a98162010-03-13 21:22:49 +00001282 char astTmpFile[L_tmpnam];
1283 argv.push_back(tmpnam(astTmpFile));
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00001284
1285 // Since the Clang C library is primarily used by batch tools dealing with
1286 // (often very broken) source code, where spell-checking can have a
1287 // significant negative impact on performance (particularly when
1288 // precompiled headers are involved), we disable it by default.
1289 // Note that we place this argument early in the list, so that it can be
1290 // overridden by the caller with "-fspell-checking".
Douglas Gregora0068fc2010-07-09 17:35:33 +00001291 argv.push_back("-fno-spell-checking");
Ted Kremenek139ba862009-10-22 00:03:57 +00001292
Douglas Gregor4db64a42010-01-23 00:14:00 +00001293 // Remap any unsaved files to temporary files.
1294 std::vector<llvm::sys::Path> TemporaryFiles;
1295 std::vector<std::string> RemapArgs;
1296 if (RemapFiles(num_unsaved_files, unsaved_files, RemapArgs, TemporaryFiles))
1297 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001298
Douglas Gregor4db64a42010-01-23 00:14:00 +00001299 // The pointers into the elements of RemapArgs are stable because we
1300 // won't be adding anything to RemapArgs after this point.
1301 for (unsigned i = 0, e = RemapArgs.size(); i != e; ++i)
1302 argv.push_back(RemapArgs[i].c_str());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001303
Ted Kremenek139ba862009-10-22 00:03:57 +00001304 // Process the compiler options, stripping off '-o', '-c', '-fsyntax-only'.
1305 for (int i = 0; i < num_command_line_args; ++i)
1306 if (const char *arg = command_line_args[i]) {
1307 if (strcmp(arg, "-o") == 0) {
1308 ++i; // Also skip the matching argument.
1309 continue;
1310 }
1311 if (strcmp(arg, "-emit-ast") == 0 ||
1312 strcmp(arg, "-c") == 0 ||
1313 strcmp(arg, "-fsyntax-only") == 0) {
1314 continue;
1315 }
1316
1317 // Keep the argument.
1318 argv.push_back(arg);
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001319 }
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001320
Douglas Gregord93256e2010-01-28 06:00:51 +00001321 // Generate a temporary name for the diagnostics file.
Benjamin Kramerc2a98162010-03-13 21:22:49 +00001322 char tmpFileResults[L_tmpnam];
1323 char *tmpResultsFileName = tmpnam(tmpFileResults);
1324 llvm::sys::Path DiagnosticsFile(tmpResultsFileName);
Douglas Gregord93256e2010-01-28 06:00:51 +00001325 TemporaryFiles.push_back(DiagnosticsFile);
1326 argv.push_back("-fdiagnostics-binary");
1327
Douglas Gregor44c181a2010-07-23 00:33:23 +00001328 // Do we need the detailed preprocessing record?
1329 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
1330 argv.push_back("-Xclang");
1331 argv.push_back("-detailed-preprocessing-record");
1332 }
1333
Ted Kremenek139ba862009-10-22 00:03:57 +00001334 // Add the null terminator.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001335 argv.push_back(NULL);
1336
Ted Kremenekfeb15e32009-10-26 22:14:08 +00001337 // Invoke 'clang'.
1338 llvm::sys::Path DevNull; // leave empty, causes redirection to /dev/null
1339 // on Unix or NUL (Windows).
Ted Kremenek379afec2009-10-22 03:24:01 +00001340 std::string ErrMsg;
Douglas Gregord93256e2010-01-28 06:00:51 +00001341 const llvm::sys::Path *Redirects[] = { &DevNull, &DevNull, &DiagnosticsFile,
1342 NULL };
Ted Kremenek379afec2009-10-22 03:24:01 +00001343 llvm::sys::Program::ExecuteAndWait(ClangPath, &argv[0], /* env */ NULL,
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001344 /* redirects */ &Redirects[0],
Ted Kremenek379afec2009-10-22 03:24:01 +00001345 /* secondsToWait */ 0, /* memoryLimits */ 0, &ErrMsg);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001346
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001347 if (!ErrMsg.empty()) {
1348 std::string AllArgs;
Ted Kremenek379afec2009-10-22 03:24:01 +00001349 for (std::vector<const char*>::iterator I = argv.begin(), E = argv.end();
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001350 I != E; ++I) {
1351 AllArgs += ' ';
Ted Kremenek779e5f42009-10-26 22:08:39 +00001352 if (*I)
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001353 AllArgs += *I;
Ted Kremenek779e5f42009-10-26 22:08:39 +00001354 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001355
Daniel Dunbar32141c82010-02-23 20:23:45 +00001356 Diags->Report(diag::err_fe_invoking) << AllArgs << ErrMsg;
Ted Kremenek379afec2009-10-22 03:24:01 +00001357 }
Benjamin Kramer0829a832009-10-18 11:19:36 +00001358
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001359 ASTUnit *ATU = ASTUnit::LoadFromPCHFile(astTmpFile, Diags,
Douglas Gregor4db64a42010-01-23 00:14:00 +00001360 CXXIdx->getOnlyLocalDecls(),
Douglas Gregor4db64a42010-01-23 00:14:00 +00001361 RemappedFiles.data(),
Douglas Gregora88084b2010-02-18 18:08:43 +00001362 RemappedFiles.size(),
1363 /*CaptureDiagnostics=*/true);
Douglas Gregora88084b2010-02-18 18:08:43 +00001364 if (ATU) {
1365 LoadSerializedDiagnostics(DiagnosticsFile,
1366 num_unsaved_files, unsaved_files,
1367 ATU->getFileManager(),
1368 ATU->getSourceManager(),
Douglas Gregor405634b2010-04-05 18:10:21 +00001369 ATU->getStoredDiagnostics());
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001370 } else if (CXXIdx->getDisplayDiagnostics()) {
1371 // We failed to load the ASTUnit, but we can still deserialize the
1372 // diagnostics and emit them.
1373 FileManager FileMgr;
Douglas Gregorf715ca12010-03-16 00:06:06 +00001374 Diagnostic Diag;
1375 SourceManager SourceMgr(Diag);
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001376 // FIXME: Faked LangOpts!
1377 LangOptions LangOpts;
1378 llvm::SmallVector<StoredDiagnostic, 4> Diags;
1379 LoadSerializedDiagnostics(DiagnosticsFile,
1380 num_unsaved_files, unsaved_files,
1381 FileMgr, SourceMgr, Diags);
1382 for (llvm::SmallVector<StoredDiagnostic, 4>::iterator D = Diags.begin(),
1383 DEnd = Diags.end();
1384 D != DEnd; ++D) {
1385 CXStoredDiagnostic Diag(*D, LangOpts);
Douglas Gregor274f1902010-02-22 23:17:23 +00001386 CXString Msg = clang_formatDiagnostic(&Diag,
1387 clang_defaultDiagnosticDisplayOptions());
1388 fprintf(stderr, "%s\n", clang_getCString(Msg));
1389 clang_disposeString(Msg);
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001390 }
Douglas Gregor274f1902010-02-22 23:17:23 +00001391
1392#ifdef LLVM_ON_WIN32
1393 // On Windows, force a flush, since there may be multiple copies of
1394 // stderr and stdout in the file system, all with different buffers
1395 // but writing to the same device.
1396 fflush(stderr);
1397#endif
Douglas Gregora88084b2010-02-18 18:08:43 +00001398 }
Douglas Gregord93256e2010-01-28 06:00:51 +00001399
Douglas Gregor313e26c2010-02-18 23:35:40 +00001400 if (ATU) {
1401 // Make the translation unit responsible for destroying all temporary files.
1402 for (unsigned i = 0, e = TemporaryFiles.size(); i != e; ++i)
1403 ATU->addTemporaryFile(TemporaryFiles[i]);
1404 ATU->addTemporaryFile(llvm::sys::Path(ATU->getPCHFileName()));
1405 } else {
1406 // Destroy all of the temporary files now; they can't be referenced any
1407 // longer.
1408 llvm::sys::Path(astTmpFile).eraseFromDisk();
1409 for (unsigned i = 0, e = TemporaryFiles.size(); i != e; ++i)
1410 TemporaryFiles[i].eraseFromDisk();
1411 }
1412
Steve Naroffe19944c2009-10-15 22:23:48 +00001413 return ATU;
Steve Naroff5b7d8e22009-10-15 20:04:39 +00001414}
1415
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001416void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001417 if (CTUnit)
1418 delete static_cast<ASTUnit *>(CTUnit);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00001419}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001420
Douglas Gregorabc563f2010-07-19 21:46:24 +00001421int clang_reparseTranslationUnit(CXTranslationUnit TU,
1422 unsigned num_unsaved_files,
1423 struct CXUnsavedFile *unsaved_files) {
1424 if (!TU)
1425 return 1;
1426
1427 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
1428 for (unsigned I = 0; I != num_unsaved_files; ++I) {
1429 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
1430 const llvm::MemoryBuffer *Buffer
1431 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
1432 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
1433 Buffer));
1434 }
1435
1436 return static_cast<ASTUnit *>(TU)->Reparse(RemappedFiles.data(),
1437 RemappedFiles.size())? 1 : 0;
1438}
1439
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001440CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001441 if (!CTUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001442 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001443
Steve Naroff77accc12009-09-03 18:19:54 +00001444 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001445 return createCXString(CXXUnit->getOriginalSourceFileName(), true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +00001446}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +00001447
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001448CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001449 CXCursor Result = { CXCursor_TranslationUnit, { 0, 0, TU } };
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001450 return Result;
1451}
1452
Ted Kremenekfb480492010-01-13 21:46:36 +00001453} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +00001454
Ted Kremenekfb480492010-01-13 21:46:36 +00001455//===----------------------------------------------------------------------===//
Douglas Gregor1db19de2010-01-19 21:36:55 +00001456// CXSourceLocation and CXSourceRange Operations.
1457//===----------------------------------------------------------------------===//
1458
Douglas Gregorb9790342010-01-22 21:44:22 +00001459extern "C" {
1460CXSourceLocation clang_getNullLocation() {
Douglas Gregor5352ac02010-01-28 00:27:43 +00001461 CXSourceLocation Result = { { 0, 0 }, 0 };
Douglas Gregorb9790342010-01-22 21:44:22 +00001462 return Result;
1463}
1464
1465unsigned clang_equalLocations(CXSourceLocation loc1, CXSourceLocation loc2) {
Daniel Dunbar90a6b9e2010-01-30 23:58:27 +00001466 return (loc1.ptr_data[0] == loc2.ptr_data[0] &&
1467 loc1.ptr_data[1] == loc2.ptr_data[1] &&
1468 loc1.int_data == loc2.int_data);
Douglas Gregorb9790342010-01-22 21:44:22 +00001469}
1470
1471CXSourceLocation clang_getLocation(CXTranslationUnit tu,
1472 CXFile file,
1473 unsigned line,
1474 unsigned column) {
Douglas Gregor42748ec2010-04-30 19:45:53 +00001475 if (!tu || !file)
Douglas Gregorb9790342010-01-22 21:44:22 +00001476 return clang_getNullLocation();
Douglas Gregor42748ec2010-04-30 19:45:53 +00001477
Douglas Gregorb9790342010-01-22 21:44:22 +00001478 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
1479 SourceLocation SLoc
1480 = CXXUnit->getSourceManager().getLocation(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001481 static_cast<const FileEntry *>(file),
Douglas Gregorb9790342010-01-22 21:44:22 +00001482 line, column);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001483
Ted Kremenek1a9a0bc2010-06-28 23:54:17 +00001484 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
Douglas Gregorb9790342010-01-22 21:44:22 +00001485}
1486
Douglas Gregor5352ac02010-01-28 00:27:43 +00001487CXSourceRange clang_getNullRange() {
1488 CXSourceRange Result = { { 0, 0 }, 0, 0 };
1489 return Result;
1490}
Daniel Dunbard52864b2010-02-14 10:02:57 +00001491
Douglas Gregor5352ac02010-01-28 00:27:43 +00001492CXSourceRange clang_getRange(CXSourceLocation begin, CXSourceLocation end) {
1493 if (begin.ptr_data[0] != end.ptr_data[0] ||
1494 begin.ptr_data[1] != end.ptr_data[1])
1495 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001496
1497 CXSourceRange Result = { { begin.ptr_data[0], begin.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00001498 begin.int_data, end.int_data };
Douglas Gregorb9790342010-01-22 21:44:22 +00001499 return Result;
1500}
1501
Douglas Gregor46766dc2010-01-26 19:19:08 +00001502void clang_getInstantiationLocation(CXSourceLocation location,
1503 CXFile *file,
1504 unsigned *line,
1505 unsigned *column,
1506 unsigned *offset) {
Douglas Gregor1db19de2010-01-19 21:36:55 +00001507 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
1508
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00001509 if (!location.ptr_data[0] || Loc.isInvalid()) {
Douglas Gregor46766dc2010-01-26 19:19:08 +00001510 if (file)
1511 *file = 0;
1512 if (line)
1513 *line = 0;
1514 if (column)
1515 *column = 0;
1516 if (offset)
1517 *offset = 0;
1518 return;
1519 }
1520
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00001521 const SourceManager &SM =
1522 *static_cast<const SourceManager*>(location.ptr_data[0]);
Douglas Gregor1db19de2010-01-19 21:36:55 +00001523 SourceLocation InstLoc = SM.getInstantiationLoc(Loc);
Douglas Gregor1db19de2010-01-19 21:36:55 +00001524
1525 if (file)
1526 *file = (void *)SM.getFileEntryForID(SM.getFileID(InstLoc));
1527 if (line)
1528 *line = SM.getInstantiationLineNumber(InstLoc);
1529 if (column)
1530 *column = SM.getInstantiationColumnNumber(InstLoc);
Douglas Gregore69517c2010-01-26 03:07:15 +00001531 if (offset)
Douglas Gregor46766dc2010-01-26 19:19:08 +00001532 *offset = SM.getDecomposedLoc(InstLoc).second;
Douglas Gregore69517c2010-01-26 03:07:15 +00001533}
1534
Douglas Gregor1db19de2010-01-19 21:36:55 +00001535CXSourceLocation clang_getRangeStart(CXSourceRange range) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001536 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00001537 range.begin_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00001538 return Result;
1539}
1540
1541CXSourceLocation clang_getRangeEnd(CXSourceRange range) {
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00001542 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00001543 range.end_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00001544 return Result;
1545}
1546
Douglas Gregorb9790342010-01-22 21:44:22 +00001547} // end: extern "C"
1548
Douglas Gregor1db19de2010-01-19 21:36:55 +00001549//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00001550// CXFile Operations.
1551//===----------------------------------------------------------------------===//
1552
1553extern "C" {
Ted Kremenek74844072010-02-17 00:41:20 +00001554CXString clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00001555 if (!SFile)
Ted Kremenek74844072010-02-17 00:41:20 +00001556 return createCXString(NULL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001557
Steve Naroff88145032009-10-27 14:35:18 +00001558 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Ted Kremenek74844072010-02-17 00:41:20 +00001559 return createCXString(FEnt->getName());
Steve Naroff88145032009-10-27 14:35:18 +00001560}
1561
1562time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00001563 if (!SFile)
1564 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001565
Steve Naroff88145032009-10-27 14:35:18 +00001566 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
1567 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +00001568}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001569
Douglas Gregorb9790342010-01-22 21:44:22 +00001570CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
1571 if (!tu)
1572 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001573
Douglas Gregorb9790342010-01-22 21:44:22 +00001574 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001575
Douglas Gregorb9790342010-01-22 21:44:22 +00001576 FileManager &FMgr = CXXUnit->getFileManager();
1577 const FileEntry *File = FMgr.getFile(file_name, file_name+strlen(file_name));
1578 return const_cast<FileEntry *>(File);
1579}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001580
Ted Kremenekfb480492010-01-13 21:46:36 +00001581} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +00001582
Ted Kremenekfb480492010-01-13 21:46:36 +00001583//===----------------------------------------------------------------------===//
1584// CXCursor Operations.
1585//===----------------------------------------------------------------------===//
1586
Ted Kremenekfb480492010-01-13 21:46:36 +00001587static Decl *getDeclFromExpr(Stmt *E) {
1588 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
1589 return RefExpr->getDecl();
1590 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
1591 return ME->getMemberDecl();
1592 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
1593 return RE->getDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001594
Ted Kremenekfb480492010-01-13 21:46:36 +00001595 if (CallExpr *CE = dyn_cast<CallExpr>(E))
1596 return getDeclFromExpr(CE->getCallee());
1597 if (CastExpr *CE = dyn_cast<CastExpr>(E))
1598 return getDeclFromExpr(CE->getSubExpr());
1599 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
1600 return OME->getMethodDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001601
Ted Kremenekfb480492010-01-13 21:46:36 +00001602 return 0;
1603}
1604
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00001605static SourceLocation getLocationFromExpr(Expr *E) {
1606 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
1607 return /*FIXME:*/Msg->getLeftLoc();
1608 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
1609 return DRE->getLocation();
1610 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
1611 return Member->getMemberLoc();
1612 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
1613 return Ivar->getLocation();
1614 return E->getLocStart();
1615}
1616
Ted Kremenekfb480492010-01-13 21:46:36 +00001617extern "C" {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001618
1619unsigned clang_visitChildren(CXCursor parent,
Douglas Gregorb1373d02010-01-20 20:59:29 +00001620 CXCursorVisitor visitor,
1621 CXClientData client_data) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001622 ASTUnit *CXXUnit = getCursorASTUnit(parent);
Douglas Gregorb1373d02010-01-20 20:59:29 +00001623
1624 unsigned PCHLevel = Decl::MaxPCHLevel;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001625
Douglas Gregorb1373d02010-01-20 20:59:29 +00001626 // Set the PCHLevel to filter out unwanted decls if requested.
1627 if (CXXUnit->getOnlyLocalDecls()) {
1628 PCHLevel = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001629
Douglas Gregorb1373d02010-01-20 20:59:29 +00001630 // If the main input was an AST, bump the level.
1631 if (CXXUnit->isMainFileAST())
1632 ++PCHLevel;
1633 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001634
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001635 CursorVisitor CursorVis(CXXUnit, visitor, client_data, PCHLevel);
Douglas Gregorb1373d02010-01-20 20:59:29 +00001636 return CursorVis.VisitChildren(parent);
1637}
1638
Douglas Gregor78205d42010-01-20 21:45:58 +00001639static CXString getDeclSpelling(Decl *D) {
1640 NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
1641 if (!ND)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001642 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001643
Douglas Gregor78205d42010-01-20 21:45:58 +00001644 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001645 return createCXString(OMD->getSelector().getAsString());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001646
Douglas Gregor78205d42010-01-20 21:45:58 +00001647 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
1648 // No, this isn't the same as the code below. getIdentifier() is non-virtual
1649 // and returns different names. NamedDecl returns the class name and
1650 // ObjCCategoryImplDecl returns the category name.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001651 return createCXString(CIMP->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001652
Ted Kremenek50aa6ac2010-05-19 21:51:10 +00001653 llvm::SmallString<1024> S;
1654 llvm::raw_svector_ostream os(S);
1655 ND->printName(os);
1656
1657 return createCXString(os.str());
Douglas Gregor78205d42010-01-20 21:45:58 +00001658}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001659
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001660CXString clang_getCursorSpelling(CXCursor C) {
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001661 if (clang_isTranslationUnit(C.kind))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001662 return clang_getTranslationUnitSpelling(C.data[2]);
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001663
Steve Narofff334b4e2009-09-02 18:26:48 +00001664 if (clang_isReference(C.kind)) {
1665 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00001666 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +00001667 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001668 return createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00001669 }
1670 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +00001671 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001672 return createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00001673 }
1674 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +00001675 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +00001676 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001677 return createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00001678 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001679 case CXCursor_TypeRef: {
1680 TypeDecl *Type = getCursorTypeRef(C).first;
1681 assert(Type && "Missing type decl");
1682
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001683 return createCXString(getCursorContext(C).getTypeDeclType(Type).
1684 getAsString());
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001685 }
1686
Daniel Dunbaracca7252009-11-30 20:42:49 +00001687 default:
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001688 return createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +00001689 }
1690 }
Douglas Gregor97b98722010-01-19 23:20:36 +00001691
1692 if (clang_isExpression(C.kind)) {
1693 Decl *D = getDeclFromExpr(getCursorExpr(C));
1694 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +00001695 return getDeclSpelling(D);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001696 return createCXString("");
Douglas Gregor97b98722010-01-19 23:20:36 +00001697 }
1698
Douglas Gregor4ae8f292010-03-18 17:52:52 +00001699 if (C.kind == CXCursor_MacroInstantiation)
1700 return createCXString(getCursorMacroInstantiation(C)->getName()
1701 ->getNameStart());
1702
Douglas Gregor572feb22010-03-18 18:04:21 +00001703 if (C.kind == CXCursor_MacroDefinition)
1704 return createCXString(getCursorMacroDefinition(C)->getName()
1705 ->getNameStart());
1706
Douglas Gregor60cbfac2010-01-25 16:56:17 +00001707 if (clang_isDeclaration(C.kind))
1708 return getDeclSpelling(getCursorDecl(C));
Ted Kremeneke68fff62010-02-17 00:41:32 +00001709
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001710 return createCXString("");
Steve Narofff334b4e2009-09-02 18:26:48 +00001711}
1712
Ted Kremeneke68fff62010-02-17 00:41:32 +00001713CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00001714 switch (Kind) {
Ted Kremeneke68fff62010-02-17 00:41:32 +00001715 case CXCursor_FunctionDecl:
1716 return createCXString("FunctionDecl");
1717 case CXCursor_TypedefDecl:
1718 return createCXString("TypedefDecl");
1719 case CXCursor_EnumDecl:
1720 return createCXString("EnumDecl");
1721 case CXCursor_EnumConstantDecl:
1722 return createCXString("EnumConstantDecl");
1723 case CXCursor_StructDecl:
1724 return createCXString("StructDecl");
1725 case CXCursor_UnionDecl:
1726 return createCXString("UnionDecl");
1727 case CXCursor_ClassDecl:
1728 return createCXString("ClassDecl");
1729 case CXCursor_FieldDecl:
1730 return createCXString("FieldDecl");
1731 case CXCursor_VarDecl:
1732 return createCXString("VarDecl");
1733 case CXCursor_ParmDecl:
1734 return createCXString("ParmDecl");
1735 case CXCursor_ObjCInterfaceDecl:
1736 return createCXString("ObjCInterfaceDecl");
1737 case CXCursor_ObjCCategoryDecl:
1738 return createCXString("ObjCCategoryDecl");
1739 case CXCursor_ObjCProtocolDecl:
1740 return createCXString("ObjCProtocolDecl");
1741 case CXCursor_ObjCPropertyDecl:
1742 return createCXString("ObjCPropertyDecl");
1743 case CXCursor_ObjCIvarDecl:
1744 return createCXString("ObjCIvarDecl");
1745 case CXCursor_ObjCInstanceMethodDecl:
1746 return createCXString("ObjCInstanceMethodDecl");
1747 case CXCursor_ObjCClassMethodDecl:
1748 return createCXString("ObjCClassMethodDecl");
1749 case CXCursor_ObjCImplementationDecl:
1750 return createCXString("ObjCImplementationDecl");
1751 case CXCursor_ObjCCategoryImplDecl:
1752 return createCXString("ObjCCategoryImplDecl");
Ted Kremenek8bd5a692010-04-13 23:39:06 +00001753 case CXCursor_CXXMethod:
1754 return createCXString("CXXMethod");
Ted Kremeneke68fff62010-02-17 00:41:32 +00001755 case CXCursor_UnexposedDecl:
1756 return createCXString("UnexposedDecl");
1757 case CXCursor_ObjCSuperClassRef:
1758 return createCXString("ObjCSuperClassRef");
1759 case CXCursor_ObjCProtocolRef:
1760 return createCXString("ObjCProtocolRef");
1761 case CXCursor_ObjCClassRef:
1762 return createCXString("ObjCClassRef");
1763 case CXCursor_TypeRef:
1764 return createCXString("TypeRef");
1765 case CXCursor_UnexposedExpr:
1766 return createCXString("UnexposedExpr");
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00001767 case CXCursor_BlockExpr:
1768 return createCXString("BlockExpr");
Ted Kremeneke68fff62010-02-17 00:41:32 +00001769 case CXCursor_DeclRefExpr:
1770 return createCXString("DeclRefExpr");
1771 case CXCursor_MemberRefExpr:
1772 return createCXString("MemberRefExpr");
1773 case CXCursor_CallExpr:
1774 return createCXString("CallExpr");
1775 case CXCursor_ObjCMessageExpr:
1776 return createCXString("ObjCMessageExpr");
1777 case CXCursor_UnexposedStmt:
1778 return createCXString("UnexposedStmt");
1779 case CXCursor_InvalidFile:
1780 return createCXString("InvalidFile");
Ted Kremenek292db642010-03-19 20:39:05 +00001781 case CXCursor_InvalidCode:
1782 return createCXString("InvalidCode");
Ted Kremeneke68fff62010-02-17 00:41:32 +00001783 case CXCursor_NoDeclFound:
1784 return createCXString("NoDeclFound");
1785 case CXCursor_NotImplemented:
1786 return createCXString("NotImplemented");
1787 case CXCursor_TranslationUnit:
1788 return createCXString("TranslationUnit");
Ted Kremeneke77f4432010-02-18 03:09:07 +00001789 case CXCursor_UnexposedAttr:
1790 return createCXString("UnexposedAttr");
1791 case CXCursor_IBActionAttr:
1792 return createCXString("attribute(ibaction)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00001793 case CXCursor_IBOutletAttr:
1794 return createCXString("attribute(iboutlet)");
Ted Kremenek857e9182010-05-19 17:38:06 +00001795 case CXCursor_IBOutletCollectionAttr:
1796 return createCXString("attribute(iboutletcollection)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00001797 case CXCursor_PreprocessingDirective:
1798 return createCXString("preprocessing directive");
Douglas Gregor572feb22010-03-18 18:04:21 +00001799 case CXCursor_MacroDefinition:
1800 return createCXString("macro definition");
Douglas Gregor48072312010-03-18 15:23:44 +00001801 case CXCursor_MacroInstantiation:
1802 return createCXString("macro instantiation");
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00001803 case CXCursor_Namespace:
1804 return createCXString("Namespace");
Ted Kremeneka0536d82010-05-07 01:04:29 +00001805 case CXCursor_LinkageSpec:
1806 return createCXString("LinkageSpec");
Steve Naroff89922f82009-08-31 00:59:03 +00001807 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00001808
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00001809 llvm_unreachable("Unhandled CXCursorKind");
Ted Kremeneke68fff62010-02-17 00:41:32 +00001810 return createCXString(NULL);
Steve Naroff600866c2009-08-27 19:51:58 +00001811}
Steve Naroff89922f82009-08-31 00:59:03 +00001812
Ted Kremeneke68fff62010-02-17 00:41:32 +00001813enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
1814 CXCursor parent,
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001815 CXClientData client_data) {
1816 CXCursor *BestCursor = static_cast<CXCursor *>(client_data);
1817 *BestCursor = cursor;
1818 return CXChildVisit_Recurse;
1819}
Ted Kremeneke68fff62010-02-17 00:41:32 +00001820
Douglas Gregorb9790342010-01-22 21:44:22 +00001821CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
1822 if (!TU)
Ted Kremenekf4629892010-01-14 01:51:23 +00001823 return clang_getNullCursor();
Ted Kremeneke68fff62010-02-17 00:41:32 +00001824
Douglas Gregorb9790342010-01-22 21:44:22 +00001825 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
1826
Douglas Gregorbdf60622010-03-05 21:16:25 +00001827 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
1828
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00001829 // Translate the given source location to make it point at the beginning of
1830 // the token under the cursor.
Ted Kremeneka297de22010-01-25 22:34:44 +00001831 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00001832 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
1833 CXXUnit->getASTContext().getLangOptions());
1834
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001835 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
1836 if (SLoc.isValid()) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001837 // FIXME: Would be great to have a "hint" cursor, then walk from that
1838 // hint cursor upward until we find a cursor whose source range encloses
1839 // the region of interest, rather than starting from the translation unit.
1840 CXCursor Parent = clang_getTranslationUnitCursor(CXXUnit);
Ted Kremeneke68fff62010-02-17 00:41:32 +00001841 CursorVisitor CursorVis(CXXUnit, GetCursorVisitor, &Result,
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00001842 Decl::MaxPCHLevel, SourceLocation(SLoc));
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001843 CursorVis.VisitChildren(Parent);
Steve Naroff77128dd2009-09-15 20:25:34 +00001844 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00001845 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00001846}
1847
Ted Kremenek73885552009-11-17 19:28:59 +00001848CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00001849 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00001850}
1851
1852unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00001853 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00001854}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001855
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001856unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00001857 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
1858}
1859
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001860unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +00001861 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
1862}
Steve Naroff2d4d6292009-08-31 14:26:51 +00001863
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001864unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00001865 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
1866}
1867
Douglas Gregor97b98722010-01-19 23:20:36 +00001868unsigned clang_isExpression(enum CXCursorKind K) {
1869 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
1870}
1871
1872unsigned clang_isStatement(enum CXCursorKind K) {
1873 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
1874}
1875
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001876unsigned clang_isTranslationUnit(enum CXCursorKind K) {
1877 return K == CXCursor_TranslationUnit;
1878}
1879
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00001880unsigned clang_isPreprocessing(enum CXCursorKind K) {
1881 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
1882}
1883
Ted Kremenekad6eff62010-03-08 21:17:29 +00001884unsigned clang_isUnexposed(enum CXCursorKind K) {
1885 switch (K) {
1886 case CXCursor_UnexposedDecl:
1887 case CXCursor_UnexposedExpr:
1888 case CXCursor_UnexposedStmt:
1889 case CXCursor_UnexposedAttr:
1890 return true;
1891 default:
1892 return false;
1893 }
1894}
1895
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001896CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00001897 return C.kind;
1898}
1899
Douglas Gregor98258af2010-01-18 22:46:11 +00001900CXSourceLocation clang_getCursorLocation(CXCursor C) {
1901 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00001902 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001903 case CXCursor_ObjCSuperClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00001904 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1905 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001906 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001907 }
1908
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001909 case CXCursor_ObjCProtocolRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00001910 std::pair<ObjCProtocolDecl *, SourceLocation> P
1911 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001912 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001913 }
1914
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001915 case CXCursor_ObjCClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00001916 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1917 = getCursorObjCClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001918 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001919 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001920
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001921 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001922 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001923 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001924 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001925
Douglas Gregorf46034a2010-01-18 23:41:10 +00001926 default:
1927 // FIXME: Need a way to enumerate all non-reference cases.
1928 llvm_unreachable("Missed a reference kind");
1929 }
Douglas Gregor98258af2010-01-18 22:46:11 +00001930 }
Douglas Gregor97b98722010-01-19 23:20:36 +00001931
1932 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001933 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00001934 getLocationFromExpr(getCursorExpr(C)));
1935
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00001936 if (C.kind == CXCursor_PreprocessingDirective) {
1937 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
1938 return cxloc::translateSourceLocation(getCursorContext(C), L);
1939 }
Douglas Gregor48072312010-03-18 15:23:44 +00001940
1941 if (C.kind == CXCursor_MacroInstantiation) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00001942 SourceLocation L
1943 = cxcursor::getCursorMacroInstantiation(C)->getSourceRange().getBegin();
Douglas Gregor48072312010-03-18 15:23:44 +00001944 return cxloc::translateSourceLocation(getCursorContext(C), L);
1945 }
Douglas Gregor572feb22010-03-18 18:04:21 +00001946
1947 if (C.kind == CXCursor_MacroDefinition) {
1948 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
1949 return cxloc::translateSourceLocation(getCursorContext(C), L);
1950 }
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00001951
Ted Kremenek9a700d22010-05-12 06:16:13 +00001952 if (C.kind < CXCursor_FirstDecl || C.kind > CXCursor_LastDecl)
Douglas Gregor5352ac02010-01-28 00:27:43 +00001953 return clang_getNullLocation();
Douglas Gregor98258af2010-01-18 22:46:11 +00001954
Douglas Gregorf46034a2010-01-18 23:41:10 +00001955 Decl *D = getCursorDecl(C);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001956 SourceLocation Loc = D->getLocation();
1957 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
1958 Loc = Class->getClassLoc();
Douglas Gregor2ca54fe2010-03-22 15:53:50 +00001959 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00001960}
Douglas Gregora7bde202010-01-19 00:34:46 +00001961
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00001962} // end extern "C"
1963
1964static SourceRange getRawCursorExtent(CXCursor C) {
Douglas Gregora7bde202010-01-19 00:34:46 +00001965 if (clang_isReference(C.kind)) {
1966 switch (C.kind) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00001967 case CXCursor_ObjCSuperClassRef:
1968 return getCursorObjCSuperClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001969
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00001970 case CXCursor_ObjCProtocolRef:
1971 return getCursorObjCProtocolRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001972
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00001973 case CXCursor_ObjCClassRef:
1974 return getCursorObjCClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001975
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00001976 case CXCursor_TypeRef:
1977 return getCursorTypeRef(C).second;
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001978
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00001979 default:
1980 // FIXME: Need a way to enumerate all non-reference cases.
1981 llvm_unreachable("Missed a reference kind");
Douglas Gregora7bde202010-01-19 00:34:46 +00001982 }
1983 }
Douglas Gregor97b98722010-01-19 23:20:36 +00001984
1985 if (clang_isExpression(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00001986 return getCursorExpr(C)->getSourceRange();
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001987
1988 if (clang_isStatement(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00001989 return getCursorStmt(C)->getSourceRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001990
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00001991 if (C.kind == CXCursor_PreprocessingDirective)
1992 return cxcursor::getCursorPreprocessingDirective(C);
Douglas Gregor48072312010-03-18 15:23:44 +00001993
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00001994 if (C.kind == CXCursor_MacroInstantiation)
1995 return cxcursor::getCursorMacroInstantiation(C)->getSourceRange();
Douglas Gregor572feb22010-03-18 18:04:21 +00001996
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00001997 if (C.kind == CXCursor_MacroDefinition)
1998 return cxcursor::getCursorMacroDefinition(C)->getSourceRange();
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00001999
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002000 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl)
2001 return getCursorDecl(C)->getSourceRange();
2002
2003 return SourceRange();
2004}
2005
2006extern "C" {
2007
2008CXSourceRange clang_getCursorExtent(CXCursor C) {
2009 SourceRange R = getRawCursorExtent(C);
2010 if (R.isInvalid())
Douglas Gregor5352ac02010-01-28 00:27:43 +00002011 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002012
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002013 return cxloc::translateSourceRange(getCursorContext(C), R);
Douglas Gregora7bde202010-01-19 00:34:46 +00002014}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002015
2016CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002017 if (clang_isInvalid(C.kind))
2018 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002019
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002020 ASTUnit *CXXUnit = getCursorASTUnit(C);
Douglas Gregorb6998662010-01-19 19:34:47 +00002021 if (clang_isDeclaration(C.kind))
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002022 return C;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002023
Douglas Gregor97b98722010-01-19 23:20:36 +00002024 if (clang_isExpression(C.kind)) {
2025 Decl *D = getDeclFromExpr(getCursorExpr(C));
2026 if (D)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002027 return MakeCXCursor(D, CXXUnit);
Douglas Gregor97b98722010-01-19 23:20:36 +00002028 return clang_getNullCursor();
2029 }
2030
Douglas Gregorbf7efa22010-03-18 18:23:03 +00002031 if (C.kind == CXCursor_MacroInstantiation) {
2032 if (MacroDefinition *Def = getCursorMacroInstantiation(C)->getDefinition())
2033 return MakeMacroDefinitionCursor(Def, CXXUnit);
2034 }
2035
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002036 if (!clang_isReference(C.kind))
2037 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002038
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002039 switch (C.kind) {
2040 case CXCursor_ObjCSuperClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002041 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002042
2043 case CXCursor_ObjCProtocolRef: {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002044 return MakeCXCursor(getCursorObjCProtocolRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002045
2046 case CXCursor_ObjCClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002047 return MakeCXCursor(getCursorObjCClassRef(C).first, CXXUnit);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002048
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002049 case CXCursor_TypeRef:
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002050 return MakeCXCursor(getCursorTypeRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002051
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002052 default:
2053 // We would prefer to enumerate all non-reference cursor kinds here.
2054 llvm_unreachable("Unhandled reference cursor kind");
2055 break;
2056 }
2057 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002058
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002059 return clang_getNullCursor();
2060}
2061
Douglas Gregorb6998662010-01-19 19:34:47 +00002062CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002063 if (clang_isInvalid(C.kind))
2064 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002065
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002066 ASTUnit *CXXUnit = getCursorASTUnit(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002067
Douglas Gregorb6998662010-01-19 19:34:47 +00002068 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00002069 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00002070 C = clang_getCursorReferenced(C);
2071 WasReference = true;
2072 }
2073
Douglas Gregorbf7efa22010-03-18 18:23:03 +00002074 if (C.kind == CXCursor_MacroInstantiation)
2075 return clang_getCursorReferenced(C);
2076
Douglas Gregorb6998662010-01-19 19:34:47 +00002077 if (!clang_isDeclaration(C.kind))
2078 return clang_getNullCursor();
2079
2080 Decl *D = getCursorDecl(C);
2081 if (!D)
2082 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002083
Douglas Gregorb6998662010-01-19 19:34:47 +00002084 switch (D->getKind()) {
2085 // Declaration kinds that don't really separate the notions of
2086 // declaration and definition.
2087 case Decl::Namespace:
2088 case Decl::Typedef:
2089 case Decl::TemplateTypeParm:
2090 case Decl::EnumConstant:
2091 case Decl::Field:
2092 case Decl::ObjCIvar:
2093 case Decl::ObjCAtDefsField:
2094 case Decl::ImplicitParam:
2095 case Decl::ParmVar:
2096 case Decl::NonTypeTemplateParm:
2097 case Decl::TemplateTemplateParm:
2098 case Decl::ObjCCategoryImpl:
2099 case Decl::ObjCImplementation:
Abramo Bagnara6206d532010-06-05 05:09:32 +00002100 case Decl::AccessSpec:
Douglas Gregorb6998662010-01-19 19:34:47 +00002101 case Decl::LinkageSpec:
2102 case Decl::ObjCPropertyImpl:
2103 case Decl::FileScopeAsm:
2104 case Decl::StaticAssert:
2105 case Decl::Block:
2106 return C;
2107
2108 // Declaration kinds that don't make any sense here, but are
2109 // nonetheless harmless.
2110 case Decl::TranslationUnit:
Douglas Gregorb6998662010-01-19 19:34:47 +00002111 break;
2112
2113 // Declaration kinds for which the definition is not resolvable.
2114 case Decl::UnresolvedUsingTypename:
2115 case Decl::UnresolvedUsingValue:
2116 break;
2117
2118 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002119 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
2120 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002121
2122 case Decl::NamespaceAlias:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002123 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002124
2125 case Decl::Enum:
2126 case Decl::Record:
2127 case Decl::CXXRecord:
2128 case Decl::ClassTemplateSpecialization:
2129 case Decl::ClassTemplatePartialSpecialization:
Douglas Gregor952b0172010-02-11 01:04:33 +00002130 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002131 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002132 return clang_getNullCursor();
2133
2134 case Decl::Function:
2135 case Decl::CXXMethod:
2136 case Decl::CXXConstructor:
2137 case Decl::CXXDestructor:
2138 case Decl::CXXConversion: {
2139 const FunctionDecl *Def = 0;
2140 if (cast<FunctionDecl>(D)->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002141 return MakeCXCursor(const_cast<FunctionDecl *>(Def), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002142 return clang_getNullCursor();
2143 }
2144
2145 case Decl::Var: {
Sebastian Redl31310a22010-02-01 20:16:42 +00002146 // Ask the variable if it has a definition.
2147 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
2148 return MakeCXCursor(Def, CXXUnit);
2149 return clang_getNullCursor();
Douglas Gregorb6998662010-01-19 19:34:47 +00002150 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002151
Douglas Gregorb6998662010-01-19 19:34:47 +00002152 case Decl::FunctionTemplate: {
2153 const FunctionDecl *Def = 0;
2154 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002155 return MakeCXCursor(Def->getDescribedFunctionTemplate(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002156 return clang_getNullCursor();
2157 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002158
Douglas Gregorb6998662010-01-19 19:34:47 +00002159 case Decl::ClassTemplate: {
2160 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
Douglas Gregor952b0172010-02-11 01:04:33 +00002161 ->getDefinition())
Douglas Gregorb6998662010-01-19 19:34:47 +00002162 return MakeCXCursor(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002163 cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002164 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002165 return clang_getNullCursor();
2166 }
2167
2168 case Decl::Using: {
2169 UsingDecl *Using = cast<UsingDecl>(D);
2170 CXCursor Def = clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002171 for (UsingDecl::shadow_iterator S = Using->shadow_begin(),
2172 SEnd = Using->shadow_end();
Douglas Gregorb6998662010-01-19 19:34:47 +00002173 S != SEnd; ++S) {
2174 if (Def != clang_getNullCursor()) {
2175 // FIXME: We have no way to return multiple results.
2176 return clang_getNullCursor();
2177 }
2178
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002179 Def = clang_getCursorDefinition(MakeCXCursor((*S)->getTargetDecl(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002180 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002181 }
2182
2183 return Def;
2184 }
2185
2186 case Decl::UsingShadow:
2187 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002188 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002189 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002190
2191 case Decl::ObjCMethod: {
2192 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
2193 if (Method->isThisDeclarationADefinition())
2194 return C;
2195
2196 // Dig out the method definition in the associated
2197 // @implementation, if we have it.
2198 // FIXME: The ASTs should make finding the definition easier.
2199 if (ObjCInterfaceDecl *Class
2200 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
2201 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
2202 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
2203 Method->isInstanceMethod()))
2204 if (Def->isThisDeclarationADefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002205 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002206
2207 return clang_getNullCursor();
2208 }
2209
2210 case Decl::ObjCCategory:
2211 if (ObjCCategoryImplDecl *Impl
2212 = cast<ObjCCategoryDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002213 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002214 return clang_getNullCursor();
2215
2216 case Decl::ObjCProtocol:
2217 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
2218 return C;
2219 return clang_getNullCursor();
2220
2221 case Decl::ObjCInterface:
2222 // There are two notions of a "definition" for an Objective-C
2223 // class: the interface and its implementation. When we resolved a
2224 // reference to an Objective-C class, produce the @interface as
2225 // the definition; when we were provided with the interface,
2226 // produce the @implementation as the definition.
2227 if (WasReference) {
2228 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
2229 return C;
2230 } else if (ObjCImplementationDecl *Impl
2231 = cast<ObjCInterfaceDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002232 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002233 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002234
Douglas Gregorb6998662010-01-19 19:34:47 +00002235 case Decl::ObjCProperty:
2236 // FIXME: We don't really know where to find the
2237 // ObjCPropertyImplDecls that implement this property.
2238 return clang_getNullCursor();
2239
2240 case Decl::ObjCCompatibleAlias:
2241 if (ObjCInterfaceDecl *Class
2242 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
2243 if (!Class->isForwardDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002244 return MakeCXCursor(Class, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002245
Douglas Gregorb6998662010-01-19 19:34:47 +00002246 return clang_getNullCursor();
2247
2248 case Decl::ObjCForwardProtocol: {
2249 ObjCForwardProtocolDecl *Forward = cast<ObjCForwardProtocolDecl>(D);
2250 if (Forward->protocol_size() == 1)
2251 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002252 MakeCXCursor(*Forward->protocol_begin(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002253 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002254
2255 // FIXME: Cannot return multiple definitions.
2256 return clang_getNullCursor();
2257 }
2258
2259 case Decl::ObjCClass: {
2260 ObjCClassDecl *Class = cast<ObjCClassDecl>(D);
2261 if (Class->size() == 1) {
2262 ObjCInterfaceDecl *IFace = Class->begin()->getInterface();
2263 if (!IFace->isForwardDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002264 return MakeCXCursor(IFace, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002265 return clang_getNullCursor();
2266 }
2267
2268 // FIXME: Cannot return multiple definitions.
2269 return clang_getNullCursor();
2270 }
2271
2272 case Decl::Friend:
2273 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002274 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002275 return clang_getNullCursor();
2276
2277 case Decl::FriendTemplate:
2278 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002279 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002280 return clang_getNullCursor();
2281 }
2282
2283 return clang_getNullCursor();
2284}
2285
2286unsigned clang_isCursorDefinition(CXCursor C) {
2287 if (!clang_isDeclaration(C.kind))
2288 return 0;
2289
2290 return clang_getCursorDefinition(C) == C;
2291}
2292
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002293void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00002294 const char **startBuf,
2295 const char **endBuf,
2296 unsigned *startLine,
2297 unsigned *startColumn,
2298 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002299 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00002300 assert(getCursorDecl(C) && "CXCursor has null decl");
2301 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00002302 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
2303 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002304
Steve Naroff4ade6d62009-09-23 17:52:52 +00002305 SourceManager &SM = FD->getASTContext().getSourceManager();
2306 *startBuf = SM.getCharacterData(Body->getLBracLoc());
2307 *endBuf = SM.getCharacterData(Body->getRBracLoc());
2308 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
2309 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
2310 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
2311 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
2312}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002313
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002314void clang_enableStackTraces(void) {
2315 llvm::sys::PrintStackTraceOnErrorSignal();
2316}
2317
Ted Kremenekfb480492010-01-13 21:46:36 +00002318} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00002319
Ted Kremenekfb480492010-01-13 21:46:36 +00002320//===----------------------------------------------------------------------===//
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002321// Token-based Operations.
2322//===----------------------------------------------------------------------===//
2323
2324/* CXToken layout:
2325 * int_data[0]: a CXTokenKind
2326 * int_data[1]: starting token location
2327 * int_data[2]: token length
2328 * int_data[3]: reserved
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002329 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002330 * otherwise unused.
2331 */
2332extern "C" {
2333
2334CXTokenKind clang_getTokenKind(CXToken CXTok) {
2335 return static_cast<CXTokenKind>(CXTok.int_data[0]);
2336}
2337
2338CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
2339 switch (clang_getTokenKind(CXTok)) {
2340 case CXToken_Identifier:
2341 case CXToken_Keyword:
2342 // We know we have an IdentifierInfo*, so use that.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002343 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
2344 ->getNameStart());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002345
2346 case CXToken_Literal: {
2347 // We have stashed the starting pointer in the ptr_data field. Use it.
2348 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002349 return createCXString(llvm::StringRef(Text, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002350 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002351
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002352 case CXToken_Punctuation:
2353 case CXToken_Comment:
2354 break;
2355 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002356
2357 // We have to find the starting buffer pointer the hard way, by
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002358 // deconstructing the source location.
2359 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2360 if (!CXXUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002361 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002362
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002363 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
2364 std::pair<FileID, unsigned> LocInfo
2365 = CXXUnit->getSourceManager().getDecomposedLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +00002366 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002367 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00002368 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
2369 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00002370 return createCXString("");
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002371
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002372 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002373}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002374
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002375CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
2376 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2377 if (!CXXUnit)
2378 return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002379
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002380 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
2381 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
2382}
2383
2384CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
2385 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregor5352ac02010-01-28 00:27:43 +00002386 if (!CXXUnit)
2387 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002388
2389 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002390 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
2391}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002392
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002393void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
2394 CXToken **Tokens, unsigned *NumTokens) {
2395 if (Tokens)
2396 *Tokens = 0;
2397 if (NumTokens)
2398 *NumTokens = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002399
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002400 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2401 if (!CXXUnit || !Tokens || !NumTokens)
2402 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002403
Douglas Gregorbdf60622010-03-05 21:16:25 +00002404 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
2405
Daniel Dunbar85b988f2010-02-14 08:31:57 +00002406 SourceRange R = cxloc::translateCXSourceRange(Range);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002407 if (R.isInvalid())
2408 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002409
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002410 SourceManager &SourceMgr = CXXUnit->getSourceManager();
2411 std::pair<FileID, unsigned> BeginLocInfo
2412 = SourceMgr.getDecomposedLoc(R.getBegin());
2413 std::pair<FileID, unsigned> EndLocInfo
2414 = SourceMgr.getDecomposedLoc(R.getEnd());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002415
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002416 // Cannot tokenize across files.
2417 if (BeginLocInfo.first != EndLocInfo.first)
2418 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002419
2420 // Create a lexer
Douglas Gregorf715ca12010-03-16 00:06:06 +00002421 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002422 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00002423 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
Douglas Gregor47a3fcd2010-03-16 20:26:15 +00002424 if (Invalid)
2425 return;
Douglas Gregoraea67db2010-03-15 22:54:52 +00002426
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002427 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
2428 CXXUnit->getASTContext().getLangOptions(),
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002429 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002430 Lex.SetCommentRetentionState(true);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002431
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002432 // Lex tokens until we hit the end of the range.
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002433 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002434 llvm::SmallVector<CXToken, 32> CXTokens;
2435 Token Tok;
2436 do {
2437 // Lex the next token
2438 Lex.LexFromRawLexer(Tok);
2439 if (Tok.is(tok::eof))
2440 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002441
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002442 // Initialize the CXToken.
2443 CXToken CXTok;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002444
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002445 // - Common fields
2446 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
2447 CXTok.int_data[2] = Tok.getLength();
2448 CXTok.int_data[3] = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002449
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002450 // - Kind-specific fields
2451 if (Tok.isLiteral()) {
2452 CXTok.int_data[0] = CXToken_Literal;
2453 CXTok.ptr_data = (void *)Tok.getLiteralData();
2454 } else if (Tok.is(tok::identifier)) {
Douglas Gregoraea67db2010-03-15 22:54:52 +00002455 // Lookup the identifier to determine whether we have a keyword.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002456 std::pair<FileID, unsigned> LocInfo
2457 = SourceMgr.getDecomposedLoc(Tok.getLocation());
Douglas Gregorf715ca12010-03-16 00:06:06 +00002458 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002459 llvm::StringRef Buf
Douglas Gregorf715ca12010-03-16 00:06:06 +00002460 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
2461 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00002462 return;
2463
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002464 const char *StartPos = Buf.data() + LocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002465 IdentifierInfo *II
2466 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok, StartPos);
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00002467
2468 if (II->getObjCKeywordID() != tok::objc_not_keyword) {
2469 CXTok.int_data[0] = CXToken_Keyword;
2470 }
2471 else {
2472 CXTok.int_data[0] = II->getTokenID() == tok::identifier?
2473 CXToken_Identifier
2474 : CXToken_Keyword;
2475 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002476 CXTok.ptr_data = II;
2477 } else if (Tok.is(tok::comment)) {
2478 CXTok.int_data[0] = CXToken_Comment;
2479 CXTok.ptr_data = 0;
2480 } else {
2481 CXTok.int_data[0] = CXToken_Punctuation;
2482 CXTok.ptr_data = 0;
2483 }
2484 CXTokens.push_back(CXTok);
2485 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002486
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002487 if (CXTokens.empty())
2488 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002489
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002490 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
2491 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
2492 *NumTokens = CXTokens.size();
2493}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002494
Ted Kremenek6db61092010-05-05 00:55:15 +00002495void clang_disposeTokens(CXTranslationUnit TU,
2496 CXToken *Tokens, unsigned NumTokens) {
2497 free(Tokens);
2498}
2499
2500} // end: extern "C"
2501
2502//===----------------------------------------------------------------------===//
2503// Token annotation APIs.
2504//===----------------------------------------------------------------------===//
2505
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002506typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002507static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
2508 CXCursor parent,
2509 CXClientData client_data);
Ted Kremenek6db61092010-05-05 00:55:15 +00002510namespace {
2511class AnnotateTokensWorker {
2512 AnnotateTokensData &Annotated;
Ted Kremenek11949cb2010-05-05 00:55:17 +00002513 CXToken *Tokens;
2514 CXCursor *Cursors;
2515 unsigned NumTokens;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002516 unsigned TokIdx;
2517 CursorVisitor AnnotateVis;
2518 SourceManager &SrcMgr;
2519
2520 bool MoreTokens() const { return TokIdx < NumTokens; }
2521 unsigned NextToken() const { return TokIdx; }
2522 void AdvanceToken() { ++TokIdx; }
2523 SourceLocation GetTokenLoc(unsigned tokI) {
2524 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
2525 }
2526
Ted Kremenek6db61092010-05-05 00:55:15 +00002527public:
Ted Kremenek11949cb2010-05-05 00:55:17 +00002528 AnnotateTokensWorker(AnnotateTokensData &annotated,
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002529 CXToken *tokens, CXCursor *cursors, unsigned numTokens,
2530 ASTUnit *CXXUnit, SourceRange RegionOfInterest)
Ted Kremenek11949cb2010-05-05 00:55:17 +00002531 : Annotated(annotated), Tokens(tokens), Cursors(cursors),
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002532 NumTokens(numTokens), TokIdx(0),
2533 AnnotateVis(CXXUnit, AnnotateTokensVisitor, this,
2534 Decl::MaxPCHLevel, RegionOfInterest),
2535 SrcMgr(CXXUnit->getSourceManager()) {}
Ted Kremenek11949cb2010-05-05 00:55:17 +00002536
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002537 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
Ted Kremenek6db61092010-05-05 00:55:15 +00002538 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002539 void AnnotateTokens(CXCursor parent);
Ted Kremenek6db61092010-05-05 00:55:15 +00002540};
2541}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002542
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002543void AnnotateTokensWorker::AnnotateTokens(CXCursor parent) {
2544 // Walk the AST within the region of interest, annotating tokens
2545 // along the way.
2546 VisitChildren(parent);
Ted Kremenek11949cb2010-05-05 00:55:17 +00002547
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002548 for (unsigned I = 0 ; I < TokIdx ; ++I) {
2549 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
2550 if (Pos != Annotated.end())
2551 Cursors[I] = Pos->second;
2552 }
2553
2554 // Finish up annotating any tokens left.
2555 if (!MoreTokens())
2556 return;
2557
2558 const CXCursor &C = clang_getNullCursor();
2559 for (unsigned I = TokIdx ; I < NumTokens ; ++I) {
2560 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
2561 Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second;
Ted Kremenek11949cb2010-05-05 00:55:17 +00002562 }
2563}
2564
Ted Kremenek6db61092010-05-05 00:55:15 +00002565enum CXChildVisitResult
2566AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002567 CXSourceLocation Loc = clang_getCursorLocation(cursor);
2568 // We can always annotate a preprocessing directive/macro instantiation.
2569 if (clang_isPreprocessing(cursor.kind)) {
2570 Annotated[Loc.int_data] = cursor;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002571 return CXChildVisit_Recurse;
2572 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002573
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002574 SourceRange cursorRange = getRawCursorExtent(cursor);
Ted Kremeneka333c662010-05-12 05:29:33 +00002575
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002576 if (cursorRange.isInvalid())
2577 return CXChildVisit_Continue;
Ted Kremeneka333c662010-05-12 05:29:33 +00002578
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002579 SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data);
2580
Ted Kremeneka333c662010-05-12 05:29:33 +00002581 // Adjust the annotated range based specific declarations.
2582 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
2583 if (cursorK >= CXCursor_FirstDecl && cursorK <= CXCursor_LastDecl) {
Ted Kremenek23173d72010-05-18 21:09:07 +00002584 Decl *D = cxcursor::getCursorDecl(cursor);
2585 // Don't visit synthesized ObjC methods, since they have no syntatic
2586 // representation in the source.
2587 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
2588 if (MD->isSynthesized())
2589 return CXChildVisit_Continue;
2590 }
2591 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
Ted Kremeneka333c662010-05-12 05:29:33 +00002592 if (TypeSourceInfo *TI = DD->getTypeSourceInfo()) {
2593 TypeLoc TL = TI->getTypeLoc();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00002594 SourceLocation TLoc = TL.getSourceRange().getBegin();
Ted Kremenek6bfd5332010-05-13 15:38:38 +00002595 if (TLoc.isValid() &&
2596 SrcMgr.isBeforeInTranslationUnit(TLoc, L))
Ted Kremeneka333c662010-05-12 05:29:33 +00002597 cursorRange.setBegin(TLoc);
Ted Kremeneka333c662010-05-12 05:29:33 +00002598 }
2599 }
2600 }
2601
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002602 const enum CXCursorKind K = clang_getCursorKind(parent);
2603 const CXCursor updateC =
2604 (clang_isInvalid(K) || K == CXCursor_TranslationUnit ||
2605 L.isMacroID())
2606 ? clang_getNullCursor() : parent;
2607
2608 while (MoreTokens()) {
2609 const unsigned I = NextToken();
2610 SourceLocation TokLoc = GetTokenLoc(I);
2611 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
2612 case RangeBefore:
2613 Cursors[I] = updateC;
2614 AdvanceToken();
2615 continue;
2616 case RangeAfter:
2617 return CXChildVisit_Continue;
2618 case RangeOverlap:
2619 break;
2620 }
2621 break;
2622 }
2623
2624 // Visit children to get their cursor information.
2625 const unsigned BeforeChildren = NextToken();
2626 VisitChildren(cursor);
2627 const unsigned AfterChildren = NextToken();
2628
2629 // Adjust 'Last' to the last token within the extent of the cursor.
2630 while (MoreTokens()) {
2631 const unsigned I = NextToken();
2632 SourceLocation TokLoc = GetTokenLoc(I);
2633 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
2634 case RangeBefore:
2635 assert(0 && "Infeasible");
2636 case RangeAfter:
2637 break;
2638 case RangeOverlap:
2639 Cursors[I] = updateC;
2640 AdvanceToken();
2641 continue;
2642 }
2643 break;
2644 }
2645 const unsigned Last = NextToken();
Ted Kremenek6db61092010-05-05 00:55:15 +00002646
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002647 // Scan the tokens that are at the beginning of the cursor, but are not
2648 // capture by the child cursors.
2649
2650 // For AST elements within macros, rely on a post-annotate pass to
2651 // to correctly annotate the tokens with cursors. Otherwise we can
2652 // get confusing results of having tokens that map to cursors that really
2653 // are expanded by an instantiation.
2654 if (L.isMacroID())
2655 cursor = clang_getNullCursor();
2656
2657 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
2658 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
2659 break;
2660 Cursors[I] = cursor;
2661 }
2662 // Scan the tokens that are at the end of the cursor, but are not captured
2663 // but the child cursors.
2664 for (unsigned I = AfterChildren; I != Last; ++I)
2665 Cursors[I] = cursor;
2666
2667 TokIdx = Last;
2668 return CXChildVisit_Continue;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002669}
2670
Ted Kremenek6db61092010-05-05 00:55:15 +00002671static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
2672 CXCursor parent,
2673 CXClientData client_data) {
2674 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
2675}
2676
2677extern "C" {
2678
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002679void clang_annotateTokens(CXTranslationUnit TU,
2680 CXToken *Tokens, unsigned NumTokens,
2681 CXCursor *Cursors) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002682
2683 if (NumTokens == 0 || !Tokens || !Cursors)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002684 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002685
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002686 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002687 if (!CXXUnit) {
2688 // Any token we don't specifically annotate will have a NULL cursor.
2689 const CXCursor &C = clang_getNullCursor();
2690 for (unsigned I = 0; I != NumTokens; ++I)
2691 Cursors[I] = C;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002692 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002693 }
2694
Douglas Gregorbdf60622010-03-05 21:16:25 +00002695 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002696
Douglas Gregor0396f462010-03-19 05:22:59 +00002697 // Determine the region of interest, which contains all of the tokens.
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002698 SourceRange RegionOfInterest;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002699 RegionOfInterest.setBegin(cxloc::translateSourceLocation(
2700 clang_getTokenLocation(TU, Tokens[0])));
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002701 RegionOfInterest.setEnd(cxloc::translateSourceLocation(
2702 clang_getTokenLocation(TU,
2703 Tokens[NumTokens - 1])));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002704
Douglas Gregor0396f462010-03-19 05:22:59 +00002705 // A mapping from the source locations found when re-lexing or traversing the
2706 // region of interest to the corresponding cursors.
2707 AnnotateTokensData Annotated;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002708
2709 // Relex the tokens within the source range to look for preprocessing
Douglas Gregor0396f462010-03-19 05:22:59 +00002710 // directives.
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002711 SourceManager &SourceMgr = CXXUnit->getSourceManager();
2712 std::pair<FileID, unsigned> BeginLocInfo
2713 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
2714 std::pair<FileID, unsigned> EndLocInfo
2715 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002716
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002717 llvm::StringRef Buffer;
Douglas Gregor0396f462010-03-19 05:22:59 +00002718 bool Invalid = false;
2719 if (BeginLocInfo.first == EndLocInfo.first &&
2720 ((Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid)),true) &&
2721 !Invalid) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002722 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
2723 CXXUnit->getASTContext().getLangOptions(),
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002724 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002725 Buffer.end());
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002726 Lex.SetCommentRetentionState(true);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002727
2728 // Lex tokens in raw mode until we hit the end of the range, to avoid
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002729 // entering #includes or expanding macros.
Douglas Gregor48072312010-03-18 15:23:44 +00002730 while (true) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002731 Token Tok;
2732 Lex.LexFromRawLexer(Tok);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002733
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002734 reprocess:
2735 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
2736 // We have found a preprocessing directive. Gobble it up so that we
2737 // don't see it while preprocessing these tokens later, but keep track of
2738 // all of the token locations inside this preprocessing directive so that
2739 // we can annotate them appropriately.
2740 //
2741 // FIXME: Some simple tests here could identify macro definitions and
2742 // #undefs, to provide specific cursor kinds for those.
2743 std::vector<SourceLocation> Locations;
2744 do {
2745 Locations.push_back(Tok.getLocation());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002746 Lex.LexFromRawLexer(Tok);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002747 } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002748
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002749 using namespace cxcursor;
2750 CXCursor Cursor
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002751 = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
2752 Locations.back()),
Ted Kremenek6db61092010-05-05 00:55:15 +00002753 CXXUnit);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002754 for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
2755 Annotated[Locations[I].getRawEncoding()] = Cursor;
2756 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002757
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002758 if (Tok.isAtStartOfLine())
2759 goto reprocess;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002760
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002761 continue;
2762 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002763
Douglas Gregor48072312010-03-18 15:23:44 +00002764 if (Tok.is(tok::eof))
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002765 break;
2766 }
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002767 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002768
Douglas Gregor0396f462010-03-19 05:22:59 +00002769 // Annotate all of the source locations in the region of interest that map to
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002770 // a specific cursor.
2771 AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens,
2772 CXXUnit, RegionOfInterest);
2773 W.AnnotateTokens(clang_getTranslationUnitCursor(CXXUnit));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002774}
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002775} // end: extern "C"
2776
2777//===----------------------------------------------------------------------===//
Ted Kremenek16b42592010-03-03 06:36:57 +00002778// Operations for querying linkage of a cursor.
2779//===----------------------------------------------------------------------===//
2780
2781extern "C" {
2782CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
Douglas Gregor0396f462010-03-19 05:22:59 +00002783 if (!clang_isDeclaration(cursor.kind))
2784 return CXLinkage_Invalid;
2785
Ted Kremenek16b42592010-03-03 06:36:57 +00002786 Decl *D = cxcursor::getCursorDecl(cursor);
2787 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
2788 switch (ND->getLinkage()) {
2789 case NoLinkage: return CXLinkage_NoLinkage;
2790 case InternalLinkage: return CXLinkage_Internal;
2791 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
2792 case ExternalLinkage: return CXLinkage_External;
2793 };
2794
2795 return CXLinkage_Invalid;
2796}
2797} // end: extern "C"
2798
2799//===----------------------------------------------------------------------===//
Ted Kremenek45e1dae2010-04-12 21:22:16 +00002800// Operations for querying language of a cursor.
2801//===----------------------------------------------------------------------===//
2802
2803static CXLanguageKind getDeclLanguage(const Decl *D) {
2804 switch (D->getKind()) {
2805 default:
2806 break;
2807 case Decl::ImplicitParam:
2808 case Decl::ObjCAtDefsField:
2809 case Decl::ObjCCategory:
2810 case Decl::ObjCCategoryImpl:
2811 case Decl::ObjCClass:
2812 case Decl::ObjCCompatibleAlias:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00002813 case Decl::ObjCForwardProtocol:
2814 case Decl::ObjCImplementation:
2815 case Decl::ObjCInterface:
2816 case Decl::ObjCIvar:
2817 case Decl::ObjCMethod:
2818 case Decl::ObjCProperty:
2819 case Decl::ObjCPropertyImpl:
2820 case Decl::ObjCProtocol:
2821 return CXLanguage_ObjC;
2822 case Decl::CXXConstructor:
2823 case Decl::CXXConversion:
2824 case Decl::CXXDestructor:
2825 case Decl::CXXMethod:
2826 case Decl::CXXRecord:
2827 case Decl::ClassTemplate:
2828 case Decl::ClassTemplatePartialSpecialization:
2829 case Decl::ClassTemplateSpecialization:
2830 case Decl::Friend:
2831 case Decl::FriendTemplate:
2832 case Decl::FunctionTemplate:
2833 case Decl::LinkageSpec:
2834 case Decl::Namespace:
2835 case Decl::NamespaceAlias:
2836 case Decl::NonTypeTemplateParm:
2837 case Decl::StaticAssert:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00002838 case Decl::TemplateTemplateParm:
2839 case Decl::TemplateTypeParm:
2840 case Decl::UnresolvedUsingTypename:
2841 case Decl::UnresolvedUsingValue:
2842 case Decl::Using:
2843 case Decl::UsingDirective:
2844 case Decl::UsingShadow:
2845 return CXLanguage_CPlusPlus;
2846 }
2847
2848 return CXLanguage_C;
2849}
2850
2851extern "C" {
2852CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
2853 if (clang_isDeclaration(cursor.kind))
2854 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
2855
2856 return CXLanguage_Invalid;
2857}
2858} // end: extern "C"
2859
Ted Kremenek9ada39a2010-05-17 20:06:56 +00002860
2861//===----------------------------------------------------------------------===//
2862// C++ AST instrospection.
2863//===----------------------------------------------------------------------===//
2864
2865extern "C" {
2866unsigned clang_CXXMethod_isStatic(CXCursor C) {
2867 if (!clang_isDeclaration(C.kind))
2868 return 0;
2869 CXXMethodDecl *D = dyn_cast<CXXMethodDecl>(cxcursor::getCursorDecl(C));
2870 return (D && D->isStatic()) ? 1 : 0;
Ted Kremenek40b492a2010-05-17 20:12:45 +00002871}
Ted Kremenekb12903e2010-05-18 22:32:15 +00002872
Ted Kremenek9ada39a2010-05-17 20:06:56 +00002873} // end: extern "C"
2874
Ted Kremenek45e1dae2010-04-12 21:22:16 +00002875//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00002876// CXString Operations.
2877//===----------------------------------------------------------------------===//
2878
2879extern "C" {
2880const char *clang_getCString(CXString string) {
2881 return string.Spelling;
2882}
2883
2884void clang_disposeString(CXString string) {
2885 if (string.MustFreeString && string.Spelling)
2886 free((void*)string.Spelling);
2887}
Ted Kremenek04bb7162010-01-22 22:44:15 +00002888
Ted Kremenekfb480492010-01-13 21:46:36 +00002889} // end: extern "C"
Ted Kremenek04bb7162010-01-22 22:44:15 +00002890
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002891namespace clang { namespace cxstring {
2892CXString createCXString(const char *String, bool DupString){
2893 CXString Str;
2894 if (DupString) {
2895 Str.Spelling = strdup(String);
2896 Str.MustFreeString = 1;
2897 } else {
2898 Str.Spelling = String;
2899 Str.MustFreeString = 0;
2900 }
2901 return Str;
2902}
2903
2904CXString createCXString(llvm::StringRef String, bool DupString) {
2905 CXString Result;
2906 if (DupString || (!String.empty() && String.data()[String.size()] != 0)) {
2907 char *Spelling = (char *)malloc(String.size() + 1);
2908 memmove(Spelling, String.data(), String.size());
2909 Spelling[String.size()] = 0;
2910 Result.Spelling = Spelling;
2911 Result.MustFreeString = 1;
2912 } else {
2913 Result.Spelling = String.data();
2914 Result.MustFreeString = 0;
2915 }
2916 return Result;
2917}
2918}}
2919
Ted Kremenek04bb7162010-01-22 22:44:15 +00002920//===----------------------------------------------------------------------===//
2921// Misc. utility functions.
2922//===----------------------------------------------------------------------===//
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002923
Ted Kremenek04bb7162010-01-22 22:44:15 +00002924extern "C" {
2925
Ted Kremeneka2a9d6e2010-02-12 22:54:40 +00002926CXString clang_getClangVersion() {
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002927 return createCXString(getClangFullVersion());
Ted Kremenek04bb7162010-01-22 22:44:15 +00002928}
2929
2930} // end: extern "C"