blob: a98f064e6f90baca1ed8e41a97c6932ac66252fe [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"
Daniel Dunbarc7df4f32010-08-18 18:43:14 +000032#include "llvm/Support/CrashRecoveryContext.h"
Douglas Gregor02465752009-10-16 21:24:31 +000033#include "llvm/Support/MemoryBuffer.h"
Douglas Gregor7a07fcb2010-08-09 21:00:09 +000034#include "llvm/Support/Timer.h"
Benjamin Kramer0829a832009-10-18 11:19:36 +000035#include "llvm/System/Program.h"
Douglas Gregor0a812cf2010-02-18 23:07:20 +000036#include "llvm/System/Signals.h"
Ted Kremenekfc062212009-10-19 21:44:57 +000037
Benjamin Kramerc2a98162010-03-13 21:22:49 +000038// Needed to define L_TMPNAM on some systems.
39#include <cstdio>
40
Steve Naroff50398192009-08-28 15:28:48 +000041using namespace clang;
Ted Kremenek16c440a2010-01-15 20:35:54 +000042using namespace clang::cxcursor;
Ted Kremenekee4db4f2010-02-17 00:41:08 +000043using namespace clang::cxstring;
Steve Naroff50398192009-08-28 15:28:48 +000044
Ted Kremenek8a8da7d2010-01-06 03:42:32 +000045//===----------------------------------------------------------------------===//
46// Crash Reporting.
47//===----------------------------------------------------------------------===//
48
Ted Kremenekd7ffd082010-05-22 00:06:46 +000049#ifdef USE_CRASHTRACER
Ted Kremenek8a8da7d2010-01-06 03:42:32 +000050#include "clang/Analysis/Support/SaveAndRestore.h"
51// Integrate with crash reporter.
Daniel Dunbar439794e2010-05-20 23:50:23 +000052static const char *__crashreporter_info__ = 0;
53asm(".desc ___crashreporter_info__, 0x10");
Ted Kremenek6b569992010-02-17 21:12:23 +000054#define NUM_CRASH_STRINGS 32
Ted Kremenek29b72842010-01-07 22:49:05 +000055static unsigned crashtracer_counter = 0;
Ted Kremenek254ba7c2010-01-07 23:13:53 +000056static unsigned crashtracer_counter_id[NUM_CRASH_STRINGS] = { 0 };
Ted Kremenek29b72842010-01-07 22:49:05 +000057static const char *crashtracer_strings[NUM_CRASH_STRINGS] = { 0 };
58static const char *agg_crashtracer_strings[NUM_CRASH_STRINGS] = { 0 };
59
60static unsigned SetCrashTracerInfo(const char *str,
61 llvm::SmallString<1024> &AggStr) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +000062
Ted Kremenek254ba7c2010-01-07 23:13:53 +000063 unsigned slot = 0;
Ted Kremenek29b72842010-01-07 22:49:05 +000064 while (crashtracer_strings[slot]) {
65 if (++slot == NUM_CRASH_STRINGS)
66 slot = 0;
67 }
68 crashtracer_strings[slot] = str;
Ted Kremenek254ba7c2010-01-07 23:13:53 +000069 crashtracer_counter_id[slot] = ++crashtracer_counter;
Ted Kremenek29b72842010-01-07 22:49:05 +000070
71 // We need to create an aggregate string because multiple threads
72 // may be in this method at one time. The crash reporter string
73 // will attempt to overapproximate the set of in-flight invocations
74 // of this function. Race conditions can still cause this goal
75 // to not be achieved.
76 {
Ted Kremenekf0e23e82010-02-17 00:41:40 +000077 llvm::raw_svector_ostream Out(AggStr);
Ted Kremenek29b72842010-01-07 22:49:05 +000078 for (unsigned i = 0; i < NUM_CRASH_STRINGS; ++i)
79 if (crashtracer_strings[i]) Out << crashtracer_strings[i] << '\n';
80 }
81 __crashreporter_info__ = agg_crashtracer_strings[slot] = AggStr.c_str();
82 return slot;
83}
84
85static void ResetCrashTracerInfo(unsigned slot) {
Ted Kremenek254ba7c2010-01-07 23:13:53 +000086 unsigned max_slot = 0;
87 unsigned max_value = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +000088
Ted Kremenek254ba7c2010-01-07 23:13:53 +000089 crashtracer_strings[slot] = agg_crashtracer_strings[slot] = 0;
90
91 for (unsigned i = 0 ; i < NUM_CRASH_STRINGS; ++i)
92 if (agg_crashtracer_strings[i] &&
93 crashtracer_counter_id[i] > max_value) {
94 max_slot = i;
95 max_value = crashtracer_counter_id[i];
Ted Kremenek29b72842010-01-07 22:49:05 +000096 }
Ted Kremenek254ba7c2010-01-07 23:13:53 +000097
98 __crashreporter_info__ = agg_crashtracer_strings[max_slot];
Ted Kremenek29b72842010-01-07 22:49:05 +000099}
100
101namespace {
102class ArgsCrashTracerInfo {
103 llvm::SmallString<1024> CrashString;
104 llvm::SmallString<1024> AggregateString;
105 unsigned crashtracerSlot;
106public:
107 ArgsCrashTracerInfo(llvm::SmallVectorImpl<const char*> &Args)
108 : crashtracerSlot(0)
109 {
110 {
111 llvm::raw_svector_ostream Out(CrashString);
Ted Kremenek0baa9522010-03-05 22:43:25 +0000112 Out << "ClangCIndex [" << getClangFullVersion() << "]"
113 << "[createTranslationUnitFromSourceFile]: clang";
Ted Kremenek29b72842010-01-07 22:49:05 +0000114 for (llvm::SmallVectorImpl<const char*>::iterator I=Args.begin(),
115 E=Args.end(); I!=E; ++I)
116 Out << ' ' << *I;
117 }
118 crashtracerSlot = SetCrashTracerInfo(CrashString.c_str(),
119 AggregateString);
120 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000121
Ted Kremenek29b72842010-01-07 22:49:05 +0000122 ~ArgsCrashTracerInfo() {
123 ResetCrashTracerInfo(crashtracerSlot);
124 }
125};
126}
127#endif
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000128
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000129/// \brief The result of comparing two source ranges.
130enum RangeComparisonResult {
131 /// \brief Either the ranges overlap or one of the ranges is invalid.
132 RangeOverlap,
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000133
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000134 /// \brief The first range ends before the second range starts.
135 RangeBefore,
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000136
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000137 /// \brief The first range starts after the second range ends.
138 RangeAfter
139};
140
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000141/// \brief Compare two source ranges to determine their relative position in
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000142/// the translation unit.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000143static RangeComparisonResult RangeCompare(SourceManager &SM,
144 SourceRange R1,
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000145 SourceRange R2) {
146 assert(R1.isValid() && "First range is invalid?");
147 assert(R2.isValid() && "Second range is invalid?");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000148 if (R1.getEnd() != R2.getBegin() &&
Daniel Dunbard52864b2010-02-14 10:02:57 +0000149 SM.isBeforeInTranslationUnit(R1.getEnd(), R2.getBegin()))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000150 return RangeBefore;
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000151 if (R2.getEnd() != R1.getBegin() &&
Daniel Dunbard52864b2010-02-14 10:02:57 +0000152 SM.isBeforeInTranslationUnit(R2.getEnd(), R1.getBegin()))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000153 return RangeAfter;
154 return RangeOverlap;
155}
156
Ted Kremenekfbd84ca2010-05-05 00:55:23 +0000157/// \brief Determine if a source location falls within, before, or after a
158/// a given source range.
159static RangeComparisonResult LocationCompare(SourceManager &SM,
160 SourceLocation L, SourceRange R) {
161 assert(R.isValid() && "First range is invalid?");
162 assert(L.isValid() && "Second range is invalid?");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000163 if (L == R.getBegin() || L == R.getEnd())
Ted Kremenekfbd84ca2010-05-05 00:55:23 +0000164 return RangeOverlap;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +0000165 if (SM.isBeforeInTranslationUnit(L, R.getBegin()))
166 return RangeBefore;
167 if (SM.isBeforeInTranslationUnit(R.getEnd(), L))
168 return RangeAfter;
169 return RangeOverlap;
170}
171
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000172/// \brief Translate a Clang source range into a CIndex source range.
173///
174/// Clang internally represents ranges where the end location points to the
175/// start of the token at the end. However, for external clients it is more
176/// useful to have a CXSourceRange be a proper half-open interval. This routine
177/// does the appropriate translation.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000178CXSourceRange cxloc::translateSourceRange(const SourceManager &SM,
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000179 const LangOptions &LangOpts,
Chris Lattner0a76aae2010-06-18 22:45:06 +0000180 const CharSourceRange &R) {
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000181 // We want the last character in this location, so we will adjust the
Douglas Gregor6a5a23f2010-03-19 21:51:54 +0000182 // location accordingly.
183 // FIXME: How do do this with a macro instantiation location?
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000184 SourceLocation EndLoc = R.getEnd();
Chris Lattner0a76aae2010-06-18 22:45:06 +0000185 if (R.isTokenRange() && !EndLoc.isInvalid() && EndLoc.isFileID()) {
Douglas Gregor6a5a23f2010-03-19 21:51:54 +0000186 unsigned Length = Lexer::MeasureTokenLength(EndLoc, SM, LangOpts);
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000187 EndLoc = EndLoc.getFileLocWithOffset(Length);
188 }
189
190 CXSourceRange Result = { { (void *)&SM, (void *)&LangOpts },
191 R.getBegin().getRawEncoding(),
192 EndLoc.getRawEncoding() };
193 return Result;
194}
Douglas Gregor1db19de2010-01-19 21:36:55 +0000195
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000196//===----------------------------------------------------------------------===//
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000197// Cursor visitor.
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000198//===----------------------------------------------------------------------===//
199
Steve Naroff89922f82009-08-31 00:59:03 +0000200namespace {
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000201
Douglas Gregorb1373d02010-01-20 20:59:29 +0000202// Cursor visitor.
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000203class CursorVisitor : public DeclVisitor<CursorVisitor, bool>,
Douglas Gregora59e3902010-01-21 23:27:09 +0000204 public TypeLocVisitor<CursorVisitor, bool>,
205 public StmtVisitor<CursorVisitor, bool>
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000206{
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000207 /// \brief The translation unit we are traversing.
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000208 ASTUnit *TU;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000209
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000210 /// \brief The parent cursor whose children we are traversing.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000211 CXCursor Parent;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000212
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000213 /// \brief The declaration that serves at the parent of any statement or
214 /// expression nodes.
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000215 Decl *StmtParent;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000216
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000217 /// \brief The visitor function.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000218 CXCursorVisitor Visitor;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000219
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000220 /// \brief The opaque client data, to be passed along to the visitor.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000221 CXClientData ClientData;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000222
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000223 // MaxPCHLevel - the maximum PCH level of declarations that we will pass on
224 // to the visitor. Declarations with a PCH level greater than this value will
225 // be suppressed.
226 unsigned MaxPCHLevel;
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000227
228 /// \brief When valid, a source range to which the cursor should restrict
229 /// its search.
230 SourceRange RegionOfInterest;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000231
Douglas Gregorb1373d02010-01-20 20:59:29 +0000232 using DeclVisitor<CursorVisitor, bool>::Visit;
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000233 using TypeLocVisitor<CursorVisitor, bool>::Visit;
Douglas Gregora59e3902010-01-21 23:27:09 +0000234 using StmtVisitor<CursorVisitor, bool>::Visit;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000235
236 /// \brief Determine whether this particular source range comes before, comes
237 /// after, or overlaps the region of interest.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000238 ///
Daniel Dunbard52864b2010-02-14 10:02:57 +0000239 /// \param R a half-open source range retrieved from the abstract syntax tree.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000240 RangeComparisonResult CompareRegionOfInterest(SourceRange R);
241
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000242 class SetParentRAII {
243 CXCursor &Parent;
244 Decl *&StmtParent;
245 CXCursor OldParent;
246
247 public:
248 SetParentRAII(CXCursor &Parent, Decl *&StmtParent, CXCursor NewParent)
249 : Parent(Parent), StmtParent(StmtParent), OldParent(Parent)
250 {
251 Parent = NewParent;
252 if (clang_isDeclaration(Parent.kind))
253 StmtParent = getCursorDecl(Parent);
254 }
255
256 ~SetParentRAII() {
257 Parent = OldParent;
258 if (clang_isDeclaration(Parent.kind))
259 StmtParent = getCursorDecl(Parent);
260 }
261 };
262
Steve Naroff89922f82009-08-31 00:59:03 +0000263public:
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000264 CursorVisitor(ASTUnit *TU, CXCursorVisitor Visitor, CXClientData ClientData,
265 unsigned MaxPCHLevel,
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000266 SourceRange RegionOfInterest = SourceRange())
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000267 : TU(TU), Visitor(Visitor), ClientData(ClientData),
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000268 MaxPCHLevel(MaxPCHLevel), RegionOfInterest(RegionOfInterest)
Douglas Gregorb1373d02010-01-20 20:59:29 +0000269 {
270 Parent.kind = CXCursor_NoDeclFound;
271 Parent.data[0] = 0;
272 Parent.data[1] = 0;
273 Parent.data[2] = 0;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000274 StmtParent = 0;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000275 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000276
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000277 bool Visit(CXCursor Cursor, bool CheckedRegionOfInterest = false);
Douglas Gregor788f5a12010-03-20 00:41:21 +0000278
279 std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
280 getPreprocessedEntities();
281
Douglas Gregorb1373d02010-01-20 20:59:29 +0000282 bool VisitChildren(CXCursor Parent);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000283
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000284 // Declaration visitors
Ted Kremenek09dfa372010-02-18 05:46:33 +0000285 bool VisitAttributes(Decl *D);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000286 bool VisitBlockDecl(BlockDecl *B);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000287 bool VisitDeclContext(DeclContext *DC);
Ted Kremenek4540c9c2010-02-18 18:47:08 +0000288 bool VisitTranslationUnitDecl(TranslationUnitDecl *D);
289 bool VisitTypedefDecl(TypedefDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000290 bool VisitTagDecl(TagDecl *D);
291 bool VisitEnumConstantDecl(EnumConstantDecl *D);
292 bool VisitDeclaratorDecl(DeclaratorDecl *DD);
293 bool VisitFunctionDecl(FunctionDecl *ND);
294 bool VisitFieldDecl(FieldDecl *D);
Ted Kremenek4540c9c2010-02-18 18:47:08 +0000295 bool VisitVarDecl(VarDecl *);
Ted Kremenek79758f62010-02-18 22:36:18 +0000296 bool VisitObjCMethodDecl(ObjCMethodDecl *ND);
297 bool VisitObjCContainerDecl(ObjCContainerDecl *D);
298 bool VisitObjCCategoryDecl(ObjCCategoryDecl *ND);
299 bool VisitObjCProtocolDecl(ObjCProtocolDecl *PID);
Ted Kremenek23173d72010-05-18 21:09:07 +0000300 bool VisitObjCPropertyDecl(ObjCPropertyDecl *PD);
Ted Kremenek79758f62010-02-18 22:36:18 +0000301 bool VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
302 bool VisitObjCImplDecl(ObjCImplDecl *D);
303 bool VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
304 bool VisitObjCImplementationDecl(ObjCImplementationDecl *D);
305 // FIXME: ObjCPropertyDecl requires TypeSourceInfo, getter/setter locations,
306 // etc.
307 // FIXME: ObjCCompatibleAliasDecl requires aliased-class locations.
308 bool VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D);
309 bool VisitObjCClassDecl(ObjCClassDecl *D);
Ted Kremeneka0536d82010-05-07 01:04:29 +0000310 bool VisitLinkageSpecDecl(LinkageSpecDecl *D);
Ted Kremenek8f06e0e2010-05-06 23:38:21 +0000311 bool VisitNamespaceDecl(NamespaceDecl *D);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000312
313 // Type visitors
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000314 // FIXME: QualifiedTypeLoc doesn't provide any location information
315 bool VisitBuiltinTypeLoc(BuiltinTypeLoc TL);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000316 bool VisitTypedefTypeLoc(TypedefTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000317 bool VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL);
318 bool VisitTagTypeLoc(TagTypeLoc TL);
319 // FIXME: TemplateTypeParmTypeLoc doesn't provide any location information
320 bool VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL);
John McCallc12c5bb2010-05-15 11:32:37 +0000321 bool VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000322 bool VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL);
323 bool VisitPointerTypeLoc(PointerTypeLoc TL);
324 bool VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL);
325 bool VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL);
326 bool VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL);
327 bool VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL);
328 bool VisitFunctionTypeLoc(FunctionTypeLoc TL);
329 bool VisitArrayTypeLoc(ArrayTypeLoc TL);
Douglas Gregor2332c112010-01-21 20:48:56 +0000330 // FIXME: Implement for TemplateSpecializationTypeLoc
331 // FIXME: Implement visitors here when the unimplemented TypeLocs get
332 // implemented
333 bool VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL);
334 bool VisitTypeOfTypeLoc(TypeOfTypeLoc TL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000335
Douglas Gregora59e3902010-01-21 23:27:09 +0000336 // Statement visitors
337 bool VisitStmt(Stmt *S);
338 bool VisitDeclStmt(DeclStmt *S);
Douglas Gregorf5bab412010-01-22 01:00:11 +0000339 // FIXME: LabelStmt label?
340 bool VisitIfStmt(IfStmt *S);
341 bool VisitSwitchStmt(SwitchStmt *S);
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000342 bool VisitCaseStmt(CaseStmt *S);
Douglas Gregor263b47b2010-01-25 16:12:32 +0000343 bool VisitWhileStmt(WhileStmt *S);
344 bool VisitForStmt(ForStmt *S);
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000345// bool VisitSwitchCase(SwitchCase *S);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000346
Douglas Gregor336fd812010-01-23 00:40:08 +0000347 // Expression visitors
Douglas Gregor648220e2010-08-10 15:02:34 +0000348 // FIXME: DeclRefExpr with template arguments, nested-name-specifier
349 // FIXME: MemberExpr with template arguments, nested-name-specifier
Douglas Gregor6cd24e22010-07-29 00:26:18 +0000350 bool VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000351 bool VisitBlockExpr(BlockExpr *B);
Douglas Gregor336fd812010-01-23 00:40:08 +0000352 bool VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000353 bool VisitExplicitCastExpr(ExplicitCastExpr *E);
Douglas Gregorc2350e52010-03-08 16:40:19 +0000354 bool VisitObjCMessageExpr(ObjCMessageExpr *E);
Douglas Gregor81d34662010-04-20 15:39:42 +0000355 bool VisitObjCEncodeExpr(ObjCEncodeExpr *E);
Douglas Gregor8ecdb652010-04-28 22:16:22 +0000356 bool VisitOffsetOfExpr(OffsetOfExpr *E);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000357 bool VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E);
Douglas Gregor648220e2010-08-10 15:02:34 +0000358 // FIXME: AddrLabelExpr (once we have cursors for labels)
359 bool VisitTypesCompatibleExpr(TypesCompatibleExpr *E);
360 bool VisitVAArgExpr(VAArgExpr *E);
361 // FIXME: InitListExpr (for the designators)
362 // FIXME: DesignatedInitExpr
Steve Naroff89922f82009-08-31 00:59:03 +0000363};
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000364
Ted Kremenekab188932010-01-05 19:32:54 +0000365} // end anonymous namespace
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000366
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000367static SourceRange getRawCursorExtent(CXCursor C);
368
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000369RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000370 return RangeCompare(TU->getSourceManager(), R, RegionOfInterest);
371}
372
Douglas Gregorb1373d02010-01-20 20:59:29 +0000373/// \brief Visit the given cursor and, if requested by the visitor,
374/// its children.
375///
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000376/// \param Cursor the cursor to visit.
377///
378/// \param CheckRegionOfInterest if true, then the caller already checked that
379/// this cursor is within the region of interest.
380///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000381/// \returns true if the visitation should be aborted, false if it
382/// should continue.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000383bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
Douglas Gregorb1373d02010-01-20 20:59:29 +0000384 if (clang_isInvalid(Cursor.kind))
385 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000386
Douglas Gregorb1373d02010-01-20 20:59:29 +0000387 if (clang_isDeclaration(Cursor.kind)) {
388 Decl *D = getCursorDecl(Cursor);
389 assert(D && "Invalid declaration cursor");
390 if (D->getPCHLevel() > MaxPCHLevel)
391 return false;
392
393 if (D->isImplicit())
394 return false;
395 }
396
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000397 // If we have a range of interest, and this cursor doesn't intersect with it,
398 // we're done.
399 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000400 SourceRange Range = getRawCursorExtent(Cursor);
Daniel Dunbarf408f322010-02-14 08:32:05 +0000401 if (Range.isInvalid() || CompareRegionOfInterest(Range))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000402 return false;
403 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000404
Douglas Gregorb1373d02010-01-20 20:59:29 +0000405 switch (Visitor(Cursor, Parent, ClientData)) {
406 case CXChildVisit_Break:
407 return true;
408
409 case CXChildVisit_Continue:
410 return false;
411
412 case CXChildVisit_Recurse:
413 return VisitChildren(Cursor);
414 }
415
Douglas Gregorfd643772010-01-25 16:45:46 +0000416 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000417}
418
Douglas Gregor788f5a12010-03-20 00:41:21 +0000419std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
420CursorVisitor::getPreprocessedEntities() {
421 PreprocessingRecord &PPRec
422 = *TU->getPreprocessor().getPreprocessingRecord();
423
424 bool OnlyLocalDecls
425 = !TU->isMainFileAST() && TU->getOnlyLocalDecls();
426
427 // There is no region of interest; we have to walk everything.
428 if (RegionOfInterest.isInvalid())
429 return std::make_pair(PPRec.begin(OnlyLocalDecls),
430 PPRec.end(OnlyLocalDecls));
431
432 // Find the file in which the region of interest lands.
433 SourceManager &SM = TU->getSourceManager();
434 std::pair<FileID, unsigned> Begin
435 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getBegin());
436 std::pair<FileID, unsigned> End
437 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getEnd());
438
439 // The region of interest spans files; we have to walk everything.
440 if (Begin.first != End.first)
441 return std::make_pair(PPRec.begin(OnlyLocalDecls),
442 PPRec.end(OnlyLocalDecls));
443
444 ASTUnit::PreprocessedEntitiesByFileMap &ByFileMap
445 = TU->getPreprocessedEntitiesByFile();
446 if (ByFileMap.empty()) {
447 // Build the mapping from files to sets of preprocessed entities.
448 for (PreprocessingRecord::iterator E = PPRec.begin(OnlyLocalDecls),
449 EEnd = PPRec.end(OnlyLocalDecls);
450 E != EEnd; ++E) {
451 std::pair<FileID, unsigned> P
452 = SM.getDecomposedInstantiationLoc((*E)->getSourceRange().getBegin());
453 ByFileMap[P.first].push_back(*E);
454 }
455 }
456
457 return std::make_pair(ByFileMap[Begin.first].begin(),
458 ByFileMap[Begin.first].end());
459}
460
Douglas Gregorb1373d02010-01-20 20:59:29 +0000461/// \brief Visit the children of the given cursor.
462///
463/// \returns true if the visitation should be aborted, false if it
464/// should continue.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000465bool CursorVisitor::VisitChildren(CXCursor Cursor) {
Douglas Gregora59e3902010-01-21 23:27:09 +0000466 if (clang_isReference(Cursor.kind)) {
467 // By definition, references have no children.
468 return false;
469 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000470
471 // Set the Parent field to Cursor, then back to its old value once we're
Douglas Gregorb1373d02010-01-20 20:59:29 +0000472 // done.
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000473 SetParentRAII SetParent(Parent, StmtParent, Cursor);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000474
Douglas Gregorb1373d02010-01-20 20:59:29 +0000475 if (clang_isDeclaration(Cursor.kind)) {
476 Decl *D = getCursorDecl(Cursor);
477 assert(D && "Invalid declaration cursor");
Ted Kremenek539311e2010-02-18 18:47:01 +0000478 return VisitAttributes(D) || Visit(D);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000479 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000480
Douglas Gregora59e3902010-01-21 23:27:09 +0000481 if (clang_isStatement(Cursor.kind))
482 return Visit(getCursorStmt(Cursor));
483 if (clang_isExpression(Cursor.kind))
484 return Visit(getCursorExpr(Cursor));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000485
Douglas Gregorb1373d02010-01-20 20:59:29 +0000486 if (clang_isTranslationUnit(Cursor.kind)) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000487 ASTUnit *CXXUnit = getCursorASTUnit(Cursor);
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000488 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
489 RegionOfInterest.isInvalid()) {
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000490 for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(),
491 TLEnd = CXXUnit->top_level_end();
492 TL != TLEnd; ++TL) {
493 if (Visit(MakeCXCursor(*TL, CXXUnit), true))
Douglas Gregor7b691f332010-01-20 21:13:59 +0000494 return true;
495 }
Douglas Gregor0396f462010-03-19 05:22:59 +0000496 } else if (VisitDeclContext(
497 CXXUnit->getASTContext().getTranslationUnitDecl()))
498 return true;
Bob Wilson3178cb62010-03-19 03:57:57 +0000499
Douglas Gregor0396f462010-03-19 05:22:59 +0000500 // Walk the preprocessing record.
Daniel Dunbar8de30ff2010-03-20 01:11:56 +0000501 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000502 // FIXME: Once we have the ability to deserialize a preprocessing record,
503 // do so.
Douglas Gregor788f5a12010-03-20 00:41:21 +0000504 PreprocessingRecord::iterator E, EEnd;
505 for (llvm::tie(E, EEnd) = getPreprocessedEntities(); E != EEnd; ++E) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000506 if (MacroInstantiation *MI = dyn_cast<MacroInstantiation>(*E)) {
507 if (Visit(MakeMacroInstantiationCursor(MI, CXXUnit)))
508 return true;
Douglas Gregor788f5a12010-03-20 00:41:21 +0000509
Douglas Gregor0396f462010-03-19 05:22:59 +0000510 continue;
511 }
512
513 if (MacroDefinition *MD = dyn_cast<MacroDefinition>(*E)) {
514 if (Visit(MakeMacroDefinitionCursor(MD, CXXUnit)))
515 return true;
516
517 continue;
518 }
519 }
520 }
Douglas Gregor7b691f332010-01-20 21:13:59 +0000521 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000522 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000523
Douglas Gregorb1373d02010-01-20 20:59:29 +0000524 // Nothing to visit at the moment.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000525 return false;
526}
527
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000528bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
John McCallfc929202010-06-04 22:33:30 +0000529 if (Visit(B->getSignatureAsWritten()->getTypeLoc()))
530 return true;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000531
Ted Kremenek664cffd2010-07-22 11:30:19 +0000532 if (Stmt *Body = B->getBody())
533 return Visit(MakeCXCursor(Body, StmtParent, TU));
534
535 return false;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000536}
537
Douglas Gregorb1373d02010-01-20 20:59:29 +0000538bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000539 for (DeclContext::decl_iterator
Douglas Gregorb1373d02010-01-20 20:59:29 +0000540 I = DC->decls_begin(), E = DC->decls_end(); I != E; ++I) {
Ted Kremenek09dfa372010-02-18 05:46:33 +0000541
Ted Kremenek23173d72010-05-18 21:09:07 +0000542 Decl *D = *I;
543 if (D->getLexicalDeclContext() != DC)
544 continue;
545
546 CXCursor Cursor = MakeCXCursor(D, TU);
Daniel Dunbard52864b2010-02-14 10:02:57 +0000547
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000548 if (RegionOfInterest.isValid()) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000549 SourceRange Range = getRawCursorExtent(Cursor);
Daniel Dunbard52864b2010-02-14 10:02:57 +0000550 if (Range.isInvalid())
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000551 continue;
Daniel Dunbard52864b2010-02-14 10:02:57 +0000552
553 switch (CompareRegionOfInterest(Range)) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000554 case RangeBefore:
555 // This declaration comes before the region of interest; skip it.
556 continue;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000557
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000558 case RangeAfter:
559 // This declaration comes after the region of interest; we're done.
560 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000561
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000562 case RangeOverlap:
563 // This declaration overlaps the region of interest; visit it.
564 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000565 }
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000566 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000567
Daniel Dunbard52864b2010-02-14 10:02:57 +0000568 if (Visit(Cursor, true))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000569 return true;
570 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000571
Douglas Gregorb1373d02010-01-20 20:59:29 +0000572 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000573}
574
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000575bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
576 llvm_unreachable("Translation units are visited directly by Visit()");
577 return false;
578}
579
580bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
581 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
582 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000583
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000584 return false;
585}
586
587bool CursorVisitor::VisitTagDecl(TagDecl *D) {
588 return VisitDeclContext(D);
589}
590
591bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
592 if (Expr *Init = D->getInitExpr())
593 return Visit(MakeCXCursor(Init, StmtParent, TU));
594 return false;
595}
596
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000597bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
598 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
599 if (Visit(TSInfo->getTypeLoc()))
600 return true;
601
602 return false;
603}
604
Douglas Gregorb1373d02010-01-20 20:59:29 +0000605bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000606 if (VisitDeclaratorDecl(ND))
607 return true;
608
Douglas Gregora59e3902010-01-21 23:27:09 +0000609 if (ND->isThisDeclarationADefinition() &&
610 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
611 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000612
Douglas Gregorb1373d02010-01-20 20:59:29 +0000613 return false;
614}
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000615
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000616bool CursorVisitor::VisitFieldDecl(FieldDecl *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 *BitWidth = D->getBitWidth())
621 return Visit(MakeCXCursor(BitWidth, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000622
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000623 return false;
624}
625
626bool CursorVisitor::VisitVarDecl(VarDecl *D) {
627 if (VisitDeclaratorDecl(D))
628 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000629
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000630 if (Expr *Init = D->getInit())
631 return Visit(MakeCXCursor(Init, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000632
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000633 return false;
634}
635
636bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
Douglas Gregor4bc1cb62010-03-08 14:59:44 +0000637 if (TypeSourceInfo *TSInfo = ND->getResultTypeSourceInfo())
638 if (Visit(TSInfo->getTypeLoc()))
639 return true;
640
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000641 for (ObjCMethodDecl::param_iterator P = ND->param_begin(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000642 PEnd = ND->param_end();
643 P != PEnd; ++P) {
644 if (Visit(MakeCXCursor(*P, TU)))
645 return true;
646 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000647
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000648 if (ND->isThisDeclarationADefinition() &&
649 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
650 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000651
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000652 return false;
653}
654
Douglas Gregora59e3902010-01-21 23:27:09 +0000655bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
656 return VisitDeclContext(D);
657}
658
Douglas Gregorb1373d02010-01-20 20:59:29 +0000659bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000660 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
661 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000662 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000663
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000664 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
665 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
666 E = ND->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000667 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000668 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000669
Douglas Gregora59e3902010-01-21 23:27:09 +0000670 return VisitObjCContainerDecl(ND);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000671}
672
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000673bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
674 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
675 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
676 E = PID->protocol_end(); I != E; ++I, ++PL)
677 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
678 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000679
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000680 return VisitObjCContainerDecl(PID);
681}
682
Ted Kremenek23173d72010-05-18 21:09:07 +0000683bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
John McCallfc929202010-06-04 22:33:30 +0000684 if (Visit(PD->getTypeSourceInfo()->getTypeLoc()))
685 return true;
686
Ted Kremenek23173d72010-05-18 21:09:07 +0000687 // FIXME: This implements a workaround with @property declarations also being
688 // installed in the DeclContext for the @interface. Eventually this code
689 // should be removed.
690 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
691 if (!CDecl || !CDecl->IsClassExtension())
692 return false;
693
694 ObjCInterfaceDecl *ID = CDecl->getClassInterface();
695 if (!ID)
696 return false;
697
698 IdentifierInfo *PropertyId = PD->getIdentifier();
699 ObjCPropertyDecl *prevDecl =
700 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId);
701
702 if (!prevDecl)
703 return false;
704
705 // Visit synthesized methods since they will be skipped when visiting
706 // the @interface.
707 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
708 if (MD->isSynthesized())
709 if (Visit(MakeCXCursor(MD, TU)))
710 return true;
711
712 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
713 if (MD->isSynthesized())
714 if (Visit(MakeCXCursor(MD, TU)))
715 return true;
716
717 return false;
718}
719
Douglas Gregorb1373d02010-01-20 20:59:29 +0000720bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000721 // Issue callbacks for super class.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000722 if (D->getSuperClass() &&
723 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000724 D->getSuperClassLoc(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000725 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000726 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000727
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000728 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
729 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
730 E = D->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000731 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000732 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000733
Douglas Gregora59e3902010-01-21 23:27:09 +0000734 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000735}
736
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000737bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
738 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000739}
740
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000741bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
Ted Kremenekebfa3392010-03-19 20:39:03 +0000742 // 'ID' could be null when dealing with invalid code.
743 if (ObjCInterfaceDecl *ID = D->getClassInterface())
744 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
745 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000746
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000747 return VisitObjCImplDecl(D);
748}
749
750bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
751#if 0
752 // Issue callbacks for super class.
753 // FIXME: No source location information!
754 if (D->getSuperClass() &&
755 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000756 D->getSuperClassLoc(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000757 TU)))
758 return true;
759#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000760
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000761 return VisitObjCImplDecl(D);
762}
763
764bool CursorVisitor::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D) {
765 ObjCForwardProtocolDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
766 for (ObjCForwardProtocolDecl::protocol_iterator I = D->protocol_begin(),
767 E = D->protocol_end();
768 I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000769 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000770 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000771
772 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000773}
774
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000775bool CursorVisitor::VisitObjCClassDecl(ObjCClassDecl *D) {
776 for (ObjCClassDecl::iterator C = D->begin(), CEnd = D->end(); C != CEnd; ++C)
777 if (Visit(MakeCursorObjCClassRef(C->getInterface(), C->getLocation(), TU)))
778 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000779
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000780 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000781}
782
Ted Kremenek8f06e0e2010-05-06 23:38:21 +0000783bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
784 return VisitDeclContext(D);
785}
786
Ted Kremeneka0536d82010-05-07 01:04:29 +0000787bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
788 return VisitDeclContext(D);
789}
790
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000791bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
792 ASTContext &Context = TU->getASTContext();
793
794 // Some builtin types (such as Objective-C's "id", "sel", and
795 // "Class") have associated declarations. Create cursors for those.
796 QualType VisitType;
797 switch (TL.getType()->getAs<BuiltinType>()->getKind()) {
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000798 case BuiltinType::Void:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000799 case BuiltinType::Bool:
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000800 case BuiltinType::Char_U:
801 case BuiltinType::UChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000802 case BuiltinType::Char16:
803 case BuiltinType::Char32:
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000804 case BuiltinType::UShort:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000805 case BuiltinType::UInt:
806 case BuiltinType::ULong:
807 case BuiltinType::ULongLong:
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000808 case BuiltinType::UInt128:
809 case BuiltinType::Char_S:
810 case BuiltinType::SChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000811 case BuiltinType::WChar:
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000812 case BuiltinType::Short:
813 case BuiltinType::Int:
814 case BuiltinType::Long:
815 case BuiltinType::LongLong:
816 case BuiltinType::Int128:
817 case BuiltinType::Float:
818 case BuiltinType::Double:
819 case BuiltinType::LongDouble:
820 case BuiltinType::NullPtr:
821 case BuiltinType::Overload:
822 case BuiltinType::Dependent:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000823 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000824
825 case BuiltinType::UndeducedAuto: // FIXME: Deserves a cursor?
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000826 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000827
Ted Kremenekc4174cc2010-02-18 18:52:18 +0000828 case BuiltinType::ObjCId:
829 VisitType = Context.getObjCIdType();
830 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000831
832 case BuiltinType::ObjCClass:
833 VisitType = Context.getObjCClassType();
834 break;
835
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000836 case BuiltinType::ObjCSel:
837 VisitType = Context.getObjCSelType();
838 break;
839 }
840
841 if (!VisitType.isNull()) {
842 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000843 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000844 TU));
845 }
846
847 return false;
848}
849
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000850bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
851 return Visit(MakeCursorTypeRef(TL.getTypedefDecl(), TL.getNameLoc(), TU));
852}
853
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000854bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
855 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
856}
857
858bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
859 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
860}
861
862bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
863 if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
864 return true;
865
John McCallc12c5bb2010-05-15 11:32:37 +0000866 return false;
867}
868
869bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
870 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
871 return true;
872
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000873 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
874 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
875 TU)))
876 return true;
877 }
878
879 return false;
880}
881
882bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
John McCallc12c5bb2010-05-15 11:32:37 +0000883 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000884}
885
886bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
887 return Visit(TL.getPointeeLoc());
888}
889
890bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
891 return Visit(TL.getPointeeLoc());
892}
893
894bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
895 return Visit(TL.getPointeeLoc());
896}
897
898bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000899 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000900}
901
902bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000903 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000904}
905
906bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
907 if (Visit(TL.getResultLoc()))
908 return true;
909
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000910 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
Ted Kremenek5dbacb42010-04-07 00:27:13 +0000911 if (Decl *D = TL.getArg(I))
912 if (Visit(MakeCXCursor(D, TU)))
913 return true;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000914
915 return false;
916}
917
918bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
919 if (Visit(TL.getElementLoc()))
920 return true;
921
922 if (Expr *Size = TL.getSizeExpr())
923 return Visit(MakeCXCursor(Size, StmtParent, TU));
924
925 return false;
926}
927
Douglas Gregor2332c112010-01-21 20:48:56 +0000928bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
929 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
930}
931
932bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
933 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
934 return Visit(TSInfo->getTypeLoc());
935
936 return false;
937}
938
Douglas Gregora59e3902010-01-21 23:27:09 +0000939bool CursorVisitor::VisitStmt(Stmt *S) {
940 for (Stmt::child_iterator Child = S->child_begin(), ChildEnd = S->child_end();
941 Child != ChildEnd; ++Child) {
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000942 if (Stmt *C = *Child)
943 if (Visit(MakeCXCursor(C, StmtParent, TU)))
944 return true;
Douglas Gregora59e3902010-01-21 23:27:09 +0000945 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000946
Douglas Gregora59e3902010-01-21 23:27:09 +0000947 return false;
948}
949
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000950bool CursorVisitor::VisitCaseStmt(CaseStmt *S) {
951 // Specially handle CaseStmts because they can be nested, e.g.:
952 //
953 // case 1:
954 // case 2:
955 //
956 // In this case the second CaseStmt is the child of the first. Walking
957 // these recursively can blow out the stack.
958 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU);
959 while (true) {
960 // Set the Parent field to Cursor, then back to its old value once we're
961 // done.
962 SetParentRAII SetParent(Parent, StmtParent, Cursor);
963
964 if (Stmt *LHS = S->getLHS())
965 if (Visit(MakeCXCursor(LHS, StmtParent, TU)))
966 return true;
967 if (Stmt *RHS = S->getRHS())
968 if (Visit(MakeCXCursor(RHS, StmtParent, TU)))
969 return true;
970 if (Stmt *SubStmt = S->getSubStmt()) {
971 if (!isa<CaseStmt>(SubStmt))
972 return Visit(MakeCXCursor(SubStmt, StmtParent, TU));
973
974 // Specially handle 'CaseStmt' so that we don't blow out the stack.
975 CaseStmt *CS = cast<CaseStmt>(SubStmt);
976 Cursor = MakeCXCursor(CS, StmtParent, TU);
977 if (RegionOfInterest.isValid()) {
978 SourceRange Range = CS->getSourceRange();
979 if (Range.isInvalid() || CompareRegionOfInterest(Range))
980 return false;
981 }
982
983 switch (Visitor(Cursor, Parent, ClientData)) {
984 case CXChildVisit_Break: return true;
985 case CXChildVisit_Continue: return false;
986 case CXChildVisit_Recurse:
987 // Perform tail-recursion manually.
988 S = CS;
989 continue;
990 }
991 }
992 return false;
993 }
994}
995
Douglas Gregora59e3902010-01-21 23:27:09 +0000996bool CursorVisitor::VisitDeclStmt(DeclStmt *S) {
997 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
998 D != DEnd; ++D) {
Douglas Gregor263b47b2010-01-25 16:12:32 +0000999 if (*D && Visit(MakeCXCursor(*D, TU)))
Douglas Gregora59e3902010-01-21 23:27:09 +00001000 return true;
1001 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001002
Douglas Gregora59e3902010-01-21 23:27:09 +00001003 return false;
1004}
1005
Douglas Gregorf5bab412010-01-22 01:00:11 +00001006bool CursorVisitor::VisitIfStmt(IfStmt *S) {
1007 if (VarDecl *Var = S->getConditionVariable()) {
1008 if (Visit(MakeCXCursor(Var, TU)))
1009 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001010 }
1011
Douglas Gregor263b47b2010-01-25 16:12:32 +00001012 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1013 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +00001014 if (S->getThen() && Visit(MakeCXCursor(S->getThen(), StmtParent, TU)))
1015 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +00001016 if (S->getElse() && Visit(MakeCXCursor(S->getElse(), StmtParent, TU)))
1017 return true;
1018
1019 return false;
1020}
1021
1022bool CursorVisitor::VisitSwitchStmt(SwitchStmt *S) {
1023 if (VarDecl *Var = S->getConditionVariable()) {
1024 if (Visit(MakeCXCursor(Var, TU)))
1025 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001026 }
1027
Douglas Gregor263b47b2010-01-25 16:12:32 +00001028 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1029 return true;
1030 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
1031 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001032
Douglas Gregor263b47b2010-01-25 16:12:32 +00001033 return false;
1034}
1035
1036bool CursorVisitor::VisitWhileStmt(WhileStmt *S) {
1037 if (VarDecl *Var = S->getConditionVariable()) {
1038 if (Visit(MakeCXCursor(Var, TU)))
1039 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001040 }
1041
Douglas Gregor263b47b2010-01-25 16:12:32 +00001042 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1043 return true;
1044 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
Douglas Gregorf5bab412010-01-22 01:00:11 +00001045 return true;
1046
Douglas Gregor263b47b2010-01-25 16:12:32 +00001047 return false;
1048}
1049
1050bool CursorVisitor::VisitForStmt(ForStmt *S) {
1051 if (S->getInit() && Visit(MakeCXCursor(S->getInit(), StmtParent, TU)))
1052 return true;
1053 if (VarDecl *Var = S->getConditionVariable()) {
1054 if (Visit(MakeCXCursor(Var, TU)))
1055 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001056 }
1057
Douglas Gregor263b47b2010-01-25 16:12:32 +00001058 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1059 return true;
1060 if (S->getInc() && Visit(MakeCXCursor(S->getInc(), StmtParent, TU)))
1061 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +00001062 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
1063 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001064
Douglas Gregorf5bab412010-01-22 01:00:11 +00001065 return false;
1066}
1067
Douglas Gregor6cd24e22010-07-29 00:26:18 +00001068bool CursorVisitor::VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
1069 if (Visit(MakeCXCursor(E->getArg(0), StmtParent, TU)))
1070 return true;
1071
1072 if (Visit(MakeCXCursor(E->getCallee(), StmtParent, TU)))
1073 return true;
1074
1075 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I)
1076 if (Visit(MakeCXCursor(E->getArg(I), StmtParent, TU)))
1077 return true;
1078
1079 return false;
1080}
1081
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00001082bool CursorVisitor::VisitBlockExpr(BlockExpr *B) {
1083 return Visit(B->getBlockDecl());
1084}
1085
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001086bool CursorVisitor::VisitOffsetOfExpr(OffsetOfExpr *E) {
1087 // FIXME: Visit fields as well?
1088 if (Visit(E->getTypeSourceInfo()->getTypeLoc()))
1089 return true;
1090
1091 return VisitExpr(E);
1092}
1093
Douglas Gregor336fd812010-01-23 00:40:08 +00001094bool CursorVisitor::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E) {
1095 if (E->isArgumentType()) {
1096 if (TypeSourceInfo *TSInfo = E->getArgumentTypeInfo())
1097 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001098
Douglas Gregor336fd812010-01-23 00:40:08 +00001099 return false;
1100 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001101
Douglas Gregor336fd812010-01-23 00:40:08 +00001102 return VisitExpr(E);
1103}
1104
1105bool CursorVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
1106 if (TypeSourceInfo *TSInfo = E->getTypeInfoAsWritten())
1107 if (Visit(TSInfo->getTypeLoc()))
1108 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001109
Douglas Gregor336fd812010-01-23 00:40:08 +00001110 return VisitCastExpr(E);
1111}
1112
1113bool CursorVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
1114 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
1115 if (Visit(TSInfo->getTypeLoc()))
1116 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001117
Douglas Gregor336fd812010-01-23 00:40:08 +00001118 return VisitExpr(E);
1119}
1120
Douglas Gregor648220e2010-08-10 15:02:34 +00001121bool CursorVisitor::VisitTypesCompatibleExpr(TypesCompatibleExpr *E) {
1122 return Visit(E->getArgTInfo1()->getTypeLoc()) ||
1123 Visit(E->getArgTInfo2()->getTypeLoc());
1124}
1125
1126bool CursorVisitor::VisitVAArgExpr(VAArgExpr *E) {
1127 if (Visit(E->getWrittenTypeInfo()->getTypeLoc()))
1128 return true;
1129
1130 return Visit(MakeCXCursor(E->getSubExpr(), StmtParent, TU));
1131}
1132
Douglas Gregorc2350e52010-03-08 16:40:19 +00001133bool CursorVisitor::VisitObjCMessageExpr(ObjCMessageExpr *E) {
Douglas Gregor04badcf2010-04-21 00:45:42 +00001134 if (TypeSourceInfo *TSInfo = E->getClassReceiverTypeInfo())
1135 if (Visit(TSInfo->getTypeLoc()))
1136 return true;
Douglas Gregorc2350e52010-03-08 16:40:19 +00001137
1138 return VisitExpr(E);
1139}
1140
Douglas Gregor81d34662010-04-20 15:39:42 +00001141bool CursorVisitor::VisitObjCEncodeExpr(ObjCEncodeExpr *E) {
1142 return Visit(E->getEncodedTypeSourceInfo()->getTypeLoc());
1143}
1144
1145
Ted Kremenek09dfa372010-02-18 05:46:33 +00001146bool CursorVisitor::VisitAttributes(Decl *D) {
Sean Huntcf807c42010-08-18 23:23:40 +00001147 for (AttrVec::const_iterator i = D->attr_begin(), e = D->attr_end();
1148 i != e; ++i)
1149 if (Visit(MakeCXCursor(*i, D, TU)))
Ted Kremenek09dfa372010-02-18 05:46:33 +00001150 return true;
1151
1152 return false;
1153}
1154
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00001155extern "C" {
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001156CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
1157 int displayDiagnostics) {
Daniel Dunbarc7df4f32010-08-18 18:43:14 +00001158 // We use crash recovery to make some of our APIs more reliable, implicitly
1159 // enable it.
1160 llvm::CrashRecoveryContext::Enable();
1161
Douglas Gregora030b7c2010-01-22 20:35:53 +00001162 CIndexer *CIdxr = new CIndexer();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001163 if (excludeDeclarationsFromPCH)
1164 CIdxr->setOnlyLocalDecls();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001165 if (displayDiagnostics)
1166 CIdxr->setDisplayDiagnostics();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001167 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +00001168}
1169
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001170void clang_disposeIndex(CXIndex CIdx) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001171 if (CIdx)
1172 delete static_cast<CIndexer *>(CIdx);
Douglas Gregor7a07fcb2010-08-09 21:00:09 +00001173 if (getenv("LIBCLANG_TIMING"))
1174 llvm::TimerGroup::printAll(llvm::errs());
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00001175}
1176
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001177void clang_setUseExternalASTGeneration(CXIndex CIdx, int value) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001178 if (CIdx) {
1179 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
1180 CXXIdx->setUseExternalASTGeneration(value);
1181 }
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001182}
1183
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001184CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
Douglas Gregora88084b2010-02-18 18:08:43 +00001185 const char *ast_filename) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001186 if (!CIdx)
1187 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001188
Douglas Gregor7d1d49d2009-10-16 20:01:17 +00001189 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001190
Douglas Gregor28019772010-04-05 23:52:57 +00001191 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
Sebastian Redl3c7f4132010-08-18 23:57:06 +00001192 return ASTUnit::LoadFromASTFile(ast_filename, Diags,
Douglas Gregora88084b2010-02-18 18:08:43 +00001193 CXXIdx->getOnlyLocalDecls(),
1194 0, 0, true);
Steve Naroff600866c2009-08-27 19:51:58 +00001195}
1196
Douglas Gregorb1c031b2010-08-09 22:28:58 +00001197unsigned clang_defaultEditingTranslationUnitOptions() {
1198 return CXTranslationUnit_PrecompiledPreamble;
1199}
1200
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001201CXTranslationUnit
1202clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
1203 const char *source_filename,
1204 int num_command_line_args,
Douglas Gregor4db64a42010-01-23 00:14:00 +00001205 const char **command_line_args,
1206 unsigned num_unsaved_files,
Douglas Gregora88084b2010-02-18 18:08:43 +00001207 struct CXUnsavedFile *unsaved_files) {
Douglas Gregor5a430212010-07-21 18:52:53 +00001208 return clang_parseTranslationUnit(CIdx, source_filename,
1209 command_line_args, num_command_line_args,
1210 unsaved_files, num_unsaved_files,
1211 CXTranslationUnit_DetailedPreprocessingRecord);
1212}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001213
1214struct ParseTranslationUnitInfo {
1215 CXIndex CIdx;
1216 const char *source_filename;
1217 const char **command_line_args;
1218 int num_command_line_args;
1219 struct CXUnsavedFile *unsaved_files;
1220 unsigned num_unsaved_files;
1221 unsigned options;
1222 CXTranslationUnit result;
1223};
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00001224static void clang_parseTranslationUnit_Impl(void *UserData) {
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001225 ParseTranslationUnitInfo *PTUI =
1226 static_cast<ParseTranslationUnitInfo*>(UserData);
1227 CXIndex CIdx = PTUI->CIdx;
1228 const char *source_filename = PTUI->source_filename;
1229 const char **command_line_args = PTUI->command_line_args;
1230 int num_command_line_args = PTUI->num_command_line_args;
1231 struct CXUnsavedFile *unsaved_files = PTUI->unsaved_files;
1232 unsigned num_unsaved_files = PTUI->num_unsaved_files;
1233 unsigned options = PTUI->options;
1234 PTUI->result = 0;
Douglas Gregor5a430212010-07-21 18:52:53 +00001235
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001236 if (!CIdx)
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001237 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001238
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001239 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
1240
Douglas Gregor44c181a2010-07-23 00:33:23 +00001241 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Douglas Gregordf95a132010-08-09 20:45:32 +00001242 bool CompleteTranslationUnit
1243 = ((options & CXTranslationUnit_Incomplete) == 0);
Douglas Gregor87c08a52010-08-13 22:48:40 +00001244 bool CacheCodeCompetionResults
1245 = options & CXTranslationUnit_CacheCompletionResults;
1246
Douglas Gregor5352ac02010-01-28 00:27:43 +00001247 // Configure the diagnostics.
1248 DiagnosticOptions DiagOpts;
Douglas Gregor28019772010-04-05 23:52:57 +00001249 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
1250 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001251
Douglas Gregor4db64a42010-01-23 00:14:00 +00001252 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
1253 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattnera0a270c2010-04-05 22:42:27 +00001254 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001255 const llvm::MemoryBuffer *Buffer
Chris Lattnera0a270c2010-04-05 22:42:27 +00001256 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregor4db64a42010-01-23 00:14:00 +00001257 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
1258 Buffer));
1259 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001260
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001261 if (!CXXIdx->getUseExternalASTGeneration()) {
1262 llvm::SmallVector<const char *, 16> Args;
1263
1264 // The 'source_filename' argument is optional. If the caller does not
1265 // specify it then it is assumed that the source file is specified
1266 // in the actual argument list.
1267 if (source_filename)
1268 Args.push_back(source_filename);
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00001269
1270 // Since the Clang C library is primarily used by batch tools dealing with
1271 // (often very broken) source code, where spell-checking can have a
1272 // significant negative impact on performance (particularly when
1273 // precompiled headers are involved), we disable it by default.
1274 // Note that we place this argument early in the list, so that it can be
1275 // overridden by the caller with "-fspell-checking".
Douglas Gregora0068fc2010-07-09 17:35:33 +00001276 Args.push_back("-fno-spell-checking");
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00001277
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001278 Args.insert(Args.end(), command_line_args,
1279 command_line_args + num_command_line_args);
Douglas Gregor5a430212010-07-21 18:52:53 +00001280
Douglas Gregor44c181a2010-07-23 00:33:23 +00001281 // Do we need the detailed preprocessing record?
Douglas Gregor5a430212010-07-21 18:52:53 +00001282 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
1283 Args.push_back("-Xclang");
1284 Args.push_back("-detailed-preprocessing-record");
1285 }
Douglas Gregor44c181a2010-07-23 00:33:23 +00001286
Douglas Gregor5352ac02010-01-28 00:27:43 +00001287 unsigned NumErrors = Diags->getNumErrors();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001288
Ted Kremenek29b72842010-01-07 22:49:05 +00001289#ifdef USE_CRASHTRACER
1290 ArgsCrashTracerInfo ACTI(Args);
Ted Kremenek8a8da7d2010-01-06 03:42:32 +00001291#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001292
Daniel Dunbar94220972009-12-05 02:17:18 +00001293 llvm::OwningPtr<ASTUnit> Unit(
1294 ASTUnit::LoadFromCommandLine(Args.data(), Args.data() + Args.size(),
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001295 Diags,
Daniel Dunbar869824e2009-12-13 03:46:13 +00001296 CXXIdx->getClangResourcesPath(),
Daniel Dunbar94220972009-12-05 02:17:18 +00001297 CXXIdx->getOnlyLocalDecls(),
Douglas Gregor4db64a42010-01-23 00:14:00 +00001298 RemappedFiles.data(),
Douglas Gregora88084b2010-02-18 18:08:43 +00001299 RemappedFiles.size(),
Douglas Gregor44c181a2010-07-23 00:33:23 +00001300 /*CaptureDiagnostics=*/true,
Douglas Gregordf95a132010-08-09 20:45:32 +00001301 PrecompilePreamble,
Douglas Gregor87c08a52010-08-13 22:48:40 +00001302 CompleteTranslationUnit,
1303 CacheCodeCompetionResults));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001304
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001305 if (NumErrors != Diags->getNumErrors()) {
Ted Kremenek34f6a322010-03-05 22:43:29 +00001306 // Make sure to check that 'Unit' is non-NULL.
1307 if (CXXIdx->getDisplayDiagnostics() && Unit.get()) {
Douglas Gregor405634b2010-04-05 18:10:21 +00001308 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
1309 DEnd = Unit->stored_diag_end();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001310 D != DEnd; ++D) {
1311 CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOptions());
Douglas Gregor274f1902010-02-22 23:17:23 +00001312 CXString Msg = clang_formatDiagnostic(&Diag,
1313 clang_defaultDiagnosticDisplayOptions());
1314 fprintf(stderr, "%s\n", clang_getCString(Msg));
1315 clang_disposeString(Msg);
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001316 }
Douglas Gregor274f1902010-02-22 23:17:23 +00001317#ifdef LLVM_ON_WIN32
1318 // On Windows, force a flush, since there may be multiple copies of
1319 // stderr and stdout in the file system, all with different buffers
1320 // but writing to the same device.
1321 fflush(stderr);
Ted Kremenek83c51842010-03-26 01:34:51 +00001322#endif
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001323 }
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001324 }
Daniel Dunbar94220972009-12-05 02:17:18 +00001325
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001326 PTUI->result = Unit.take();
1327 return;
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001328 }
1329
Ted Kremenek139ba862009-10-22 00:03:57 +00001330 // Build up the arguments for invoking 'clang'.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001331 std::vector<const char *> argv;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001332
Ted Kremenek139ba862009-10-22 00:03:57 +00001333 // First add the complete path to the 'clang' executable.
1334 llvm::sys::Path ClangPath = static_cast<CIndexer *>(CIdx)->getClangPath();
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00001335 argv.push_back(ClangPath.c_str());
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001336
Ted Kremenek139ba862009-10-22 00:03:57 +00001337 // Add the '-emit-ast' option as our execution mode for 'clang'.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001338 argv.push_back("-emit-ast");
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001339
Ted Kremenek139ba862009-10-22 00:03:57 +00001340 // The 'source_filename' argument is optional. If the caller does not
1341 // specify it then it is assumed that the source file is specified
1342 // in the actual argument list.
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001343 if (source_filename)
1344 argv.push_back(source_filename);
Ted Kremenek139ba862009-10-22 00:03:57 +00001345
Steve Naroff37b5ac22009-10-15 20:50:09 +00001346 // Generate a temporary name for the AST file.
Ted Kremenek139ba862009-10-22 00:03:57 +00001347 argv.push_back("-o");
Benjamin Kramerc2a98162010-03-13 21:22:49 +00001348 char astTmpFile[L_tmpnam];
1349 argv.push_back(tmpnam(astTmpFile));
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00001350
1351 // Since the Clang C library is primarily used by batch tools dealing with
1352 // (often very broken) source code, where spell-checking can have a
1353 // significant negative impact on performance (particularly when
1354 // precompiled headers are involved), we disable it by default.
1355 // Note that we place this argument early in the list, so that it can be
1356 // overridden by the caller with "-fspell-checking".
Douglas Gregora0068fc2010-07-09 17:35:33 +00001357 argv.push_back("-fno-spell-checking");
Ted Kremenek139ba862009-10-22 00:03:57 +00001358
Douglas Gregor4db64a42010-01-23 00:14:00 +00001359 // Remap any unsaved files to temporary files.
1360 std::vector<llvm::sys::Path> TemporaryFiles;
1361 std::vector<std::string> RemapArgs;
1362 if (RemapFiles(num_unsaved_files, unsaved_files, RemapArgs, TemporaryFiles))
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001363 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001364
Douglas Gregor4db64a42010-01-23 00:14:00 +00001365 // The pointers into the elements of RemapArgs are stable because we
1366 // won't be adding anything to RemapArgs after this point.
1367 for (unsigned i = 0, e = RemapArgs.size(); i != e; ++i)
1368 argv.push_back(RemapArgs[i].c_str());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001369
Ted Kremenek139ba862009-10-22 00:03:57 +00001370 // Process the compiler options, stripping off '-o', '-c', '-fsyntax-only'.
1371 for (int i = 0; i < num_command_line_args; ++i)
1372 if (const char *arg = command_line_args[i]) {
1373 if (strcmp(arg, "-o") == 0) {
1374 ++i; // Also skip the matching argument.
1375 continue;
1376 }
1377 if (strcmp(arg, "-emit-ast") == 0 ||
1378 strcmp(arg, "-c") == 0 ||
1379 strcmp(arg, "-fsyntax-only") == 0) {
1380 continue;
1381 }
1382
1383 // Keep the argument.
1384 argv.push_back(arg);
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001385 }
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001386
Douglas Gregord93256e2010-01-28 06:00:51 +00001387 // Generate a temporary name for the diagnostics file.
Benjamin Kramerc2a98162010-03-13 21:22:49 +00001388 char tmpFileResults[L_tmpnam];
1389 char *tmpResultsFileName = tmpnam(tmpFileResults);
1390 llvm::sys::Path DiagnosticsFile(tmpResultsFileName);
Douglas Gregord93256e2010-01-28 06:00:51 +00001391 TemporaryFiles.push_back(DiagnosticsFile);
1392 argv.push_back("-fdiagnostics-binary");
1393
Douglas Gregor44c181a2010-07-23 00:33:23 +00001394 // Do we need the detailed preprocessing record?
1395 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
1396 argv.push_back("-Xclang");
1397 argv.push_back("-detailed-preprocessing-record");
1398 }
1399
Ted Kremenek139ba862009-10-22 00:03:57 +00001400 // Add the null terminator.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001401 argv.push_back(NULL);
1402
Ted Kremenekfeb15e32009-10-26 22:14:08 +00001403 // Invoke 'clang'.
1404 llvm::sys::Path DevNull; // leave empty, causes redirection to /dev/null
1405 // on Unix or NUL (Windows).
Ted Kremenek379afec2009-10-22 03:24:01 +00001406 std::string ErrMsg;
Douglas Gregord93256e2010-01-28 06:00:51 +00001407 const llvm::sys::Path *Redirects[] = { &DevNull, &DevNull, &DiagnosticsFile,
1408 NULL };
Ted Kremenek379afec2009-10-22 03:24:01 +00001409 llvm::sys::Program::ExecuteAndWait(ClangPath, &argv[0], /* env */ NULL,
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001410 /* redirects */ &Redirects[0],
Ted Kremenek379afec2009-10-22 03:24:01 +00001411 /* secondsToWait */ 0, /* memoryLimits */ 0, &ErrMsg);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001412
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001413 if (!ErrMsg.empty()) {
1414 std::string AllArgs;
Ted Kremenek379afec2009-10-22 03:24:01 +00001415 for (std::vector<const char*>::iterator I = argv.begin(), E = argv.end();
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001416 I != E; ++I) {
1417 AllArgs += ' ';
Ted Kremenek779e5f42009-10-26 22:08:39 +00001418 if (*I)
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001419 AllArgs += *I;
Ted Kremenek779e5f42009-10-26 22:08:39 +00001420 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001421
Daniel Dunbar32141c82010-02-23 20:23:45 +00001422 Diags->Report(diag::err_fe_invoking) << AllArgs << ErrMsg;
Ted Kremenek379afec2009-10-22 03:24:01 +00001423 }
Benjamin Kramer0829a832009-10-18 11:19:36 +00001424
Sebastian Redl3c7f4132010-08-18 23:57:06 +00001425 ASTUnit *ATU = ASTUnit::LoadFromASTFile(astTmpFile, Diags,
Douglas Gregor4db64a42010-01-23 00:14:00 +00001426 CXXIdx->getOnlyLocalDecls(),
Douglas Gregor4db64a42010-01-23 00:14:00 +00001427 RemappedFiles.data(),
Douglas Gregora88084b2010-02-18 18:08:43 +00001428 RemappedFiles.size(),
1429 /*CaptureDiagnostics=*/true);
Douglas Gregora88084b2010-02-18 18:08:43 +00001430 if (ATU) {
1431 LoadSerializedDiagnostics(DiagnosticsFile,
1432 num_unsaved_files, unsaved_files,
1433 ATU->getFileManager(),
1434 ATU->getSourceManager(),
Douglas Gregor405634b2010-04-05 18:10:21 +00001435 ATU->getStoredDiagnostics());
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001436 } else if (CXXIdx->getDisplayDiagnostics()) {
1437 // We failed to load the ASTUnit, but we can still deserialize the
1438 // diagnostics and emit them.
1439 FileManager FileMgr;
Douglas Gregorf715ca12010-03-16 00:06:06 +00001440 Diagnostic Diag;
1441 SourceManager SourceMgr(Diag);
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001442 // FIXME: Faked LangOpts!
1443 LangOptions LangOpts;
1444 llvm::SmallVector<StoredDiagnostic, 4> Diags;
1445 LoadSerializedDiagnostics(DiagnosticsFile,
1446 num_unsaved_files, unsaved_files,
1447 FileMgr, SourceMgr, Diags);
1448 for (llvm::SmallVector<StoredDiagnostic, 4>::iterator D = Diags.begin(),
1449 DEnd = Diags.end();
1450 D != DEnd; ++D) {
1451 CXStoredDiagnostic Diag(*D, LangOpts);
Douglas Gregor274f1902010-02-22 23:17:23 +00001452 CXString Msg = clang_formatDiagnostic(&Diag,
1453 clang_defaultDiagnosticDisplayOptions());
1454 fprintf(stderr, "%s\n", clang_getCString(Msg));
1455 clang_disposeString(Msg);
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001456 }
Douglas Gregor274f1902010-02-22 23:17:23 +00001457
1458#ifdef LLVM_ON_WIN32
1459 // On Windows, force a flush, since there may be multiple copies of
1460 // stderr and stdout in the file system, all with different buffers
1461 // but writing to the same device.
1462 fflush(stderr);
1463#endif
Douglas Gregora88084b2010-02-18 18:08:43 +00001464 }
Douglas Gregord93256e2010-01-28 06:00:51 +00001465
Douglas Gregor313e26c2010-02-18 23:35:40 +00001466 if (ATU) {
1467 // Make the translation unit responsible for destroying all temporary files.
1468 for (unsigned i = 0, e = TemporaryFiles.size(); i != e; ++i)
1469 ATU->addTemporaryFile(TemporaryFiles[i]);
Sebastian Redl3c7f4132010-08-18 23:57:06 +00001470 ATU->addTemporaryFile(llvm::sys::Path(ATU->getASTFileName()));
Douglas Gregor313e26c2010-02-18 23:35:40 +00001471 } else {
1472 // Destroy all of the temporary files now; they can't be referenced any
1473 // longer.
1474 llvm::sys::Path(astTmpFile).eraseFromDisk();
1475 for (unsigned i = 0, e = TemporaryFiles.size(); i != e; ++i)
1476 TemporaryFiles[i].eraseFromDisk();
1477 }
1478
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001479 PTUI->result = ATU;
1480}
1481CXTranslationUnit clang_parseTranslationUnit(CXIndex CIdx,
1482 const char *source_filename,
1483 const char **command_line_args,
1484 int num_command_line_args,
1485 struct CXUnsavedFile *unsaved_files,
1486 unsigned num_unsaved_files,
1487 unsigned options) {
1488 ParseTranslationUnitInfo PTUI = { CIdx, source_filename, command_line_args,
1489 num_command_line_args, unsaved_files, num_unsaved_files,
1490 options, 0 };
1491 llvm::CrashRecoveryContext CRC;
1492
1493 if (!CRC.RunSafely(clang_parseTranslationUnit_Impl, &PTUI)) {
Daniel Dunbar60a45432010-08-23 22:35:34 +00001494 fprintf(stderr, "libclang: crash detected during parsing: {\n");
1495 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
1496 fprintf(stderr, " 'command_line_args' : [");
1497 for (int i = 0; i != num_command_line_args; ++i) {
1498 if (i)
1499 fprintf(stderr, ", ");
1500 fprintf(stderr, "'%s'", command_line_args[i]);
1501 }
1502 fprintf(stderr, "],\n");
1503 fprintf(stderr, " 'unsaved_files' : [");
1504 for (unsigned i = 0; i != num_unsaved_files; ++i) {
1505 if (i)
1506 fprintf(stderr, ", ");
1507 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
1508 unsaved_files[i].Length);
1509 }
1510 fprintf(stderr, "],\n");
1511 fprintf(stderr, " 'options' : %d,\n", options);
1512 fprintf(stderr, "}\n");
1513
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001514 return 0;
1515 }
1516
1517 return PTUI.result;
Steve Naroff5b7d8e22009-10-15 20:04:39 +00001518}
1519
Douglas Gregor19998442010-08-13 15:35:05 +00001520unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
1521 return CXSaveTranslationUnit_None;
1522}
1523
1524int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
1525 unsigned options) {
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00001526 if (!TU)
1527 return 1;
1528
1529 return static_cast<ASTUnit *>(TU)->Save(FileName);
1530}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001531
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001532void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00001533 if (CTUnit) {
1534 // If the translation unit has been marked as unsafe to free, just discard
1535 // it.
1536 if (static_cast<ASTUnit *>(CTUnit)->isUnsafeToFree())
1537 return;
1538
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001539 delete static_cast<ASTUnit *>(CTUnit);
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00001540 }
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00001541}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001542
Douglas Gregore1e13bf2010-08-11 15:58:42 +00001543unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
1544 return CXReparse_None;
1545}
1546
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00001547struct ReparseTranslationUnitInfo {
1548 CXTranslationUnit TU;
1549 unsigned num_unsaved_files;
1550 struct CXUnsavedFile *unsaved_files;
1551 unsigned options;
1552 int result;
1553};
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00001554static void clang_reparseTranslationUnit_Impl(void *UserData) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00001555 ReparseTranslationUnitInfo *RTUI =
1556 static_cast<ReparseTranslationUnitInfo*>(UserData);
1557 CXTranslationUnit TU = RTUI->TU;
1558 unsigned num_unsaved_files = RTUI->num_unsaved_files;
1559 struct CXUnsavedFile *unsaved_files = RTUI->unsaved_files;
1560 unsigned options = RTUI->options;
1561 (void) options;
1562 RTUI->result = 1;
1563
Douglas Gregorabc563f2010-07-19 21:46:24 +00001564 if (!TU)
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00001565 return;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001566
1567 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
1568 for (unsigned I = 0; I != num_unsaved_files; ++I) {
1569 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
1570 const llvm::MemoryBuffer *Buffer
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001571 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregorabc563f2010-07-19 21:46:24 +00001572 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
1573 Buffer));
1574 }
1575
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00001576 if (!static_cast<ASTUnit *>(TU)->Reparse(RemappedFiles.data(),
1577 RemappedFiles.size()))
1578 RTUI->result = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001579}
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00001580int clang_reparseTranslationUnit(CXTranslationUnit TU,
1581 unsigned num_unsaved_files,
1582 struct CXUnsavedFile *unsaved_files,
1583 unsigned options) {
1584 ReparseTranslationUnitInfo RTUI = { TU, num_unsaved_files, unsaved_files,
1585 options, 0 };
1586 llvm::CrashRecoveryContext CRC;
1587
1588 if (!CRC.RunSafely(clang_reparseTranslationUnit_Impl, &RTUI)) {
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00001589 fprintf(stderr, "libclang: crash detected during reparsing\n");
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00001590 static_cast<ASTUnit *>(TU)->setUnsafeToFree(true);
1591 return 1;
1592 }
1593
1594 return RTUI.result;
1595}
1596
Douglas Gregordf95a132010-08-09 20:45:32 +00001597
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001598CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001599 if (!CTUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001600 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001601
Steve Naroff77accc12009-09-03 18:19:54 +00001602 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001603 return createCXString(CXXUnit->getOriginalSourceFileName(), true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +00001604}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +00001605
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001606CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001607 CXCursor Result = { CXCursor_TranslationUnit, { 0, 0, TU } };
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001608 return Result;
1609}
1610
Ted Kremenekfb480492010-01-13 21:46:36 +00001611} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +00001612
Ted Kremenekfb480492010-01-13 21:46:36 +00001613//===----------------------------------------------------------------------===//
Douglas Gregor1db19de2010-01-19 21:36:55 +00001614// CXSourceLocation and CXSourceRange Operations.
1615//===----------------------------------------------------------------------===//
1616
Douglas Gregorb9790342010-01-22 21:44:22 +00001617extern "C" {
1618CXSourceLocation clang_getNullLocation() {
Douglas Gregor5352ac02010-01-28 00:27:43 +00001619 CXSourceLocation Result = { { 0, 0 }, 0 };
Douglas Gregorb9790342010-01-22 21:44:22 +00001620 return Result;
1621}
1622
1623unsigned clang_equalLocations(CXSourceLocation loc1, CXSourceLocation loc2) {
Daniel Dunbar90a6b9e2010-01-30 23:58:27 +00001624 return (loc1.ptr_data[0] == loc2.ptr_data[0] &&
1625 loc1.ptr_data[1] == loc2.ptr_data[1] &&
1626 loc1.int_data == loc2.int_data);
Douglas Gregorb9790342010-01-22 21:44:22 +00001627}
1628
1629CXSourceLocation clang_getLocation(CXTranslationUnit tu,
1630 CXFile file,
1631 unsigned line,
1632 unsigned column) {
Douglas Gregor42748ec2010-04-30 19:45:53 +00001633 if (!tu || !file)
Douglas Gregorb9790342010-01-22 21:44:22 +00001634 return clang_getNullLocation();
Douglas Gregor42748ec2010-04-30 19:45:53 +00001635
Douglas Gregorb9790342010-01-22 21:44:22 +00001636 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
1637 SourceLocation SLoc
1638 = CXXUnit->getSourceManager().getLocation(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001639 static_cast<const FileEntry *>(file),
Douglas Gregorb9790342010-01-22 21:44:22 +00001640 line, column);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001641
Ted Kremenek1a9a0bc2010-06-28 23:54:17 +00001642 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
Douglas Gregorb9790342010-01-22 21:44:22 +00001643}
1644
Douglas Gregor5352ac02010-01-28 00:27:43 +00001645CXSourceRange clang_getNullRange() {
1646 CXSourceRange Result = { { 0, 0 }, 0, 0 };
1647 return Result;
1648}
Daniel Dunbard52864b2010-02-14 10:02:57 +00001649
Douglas Gregor5352ac02010-01-28 00:27:43 +00001650CXSourceRange clang_getRange(CXSourceLocation begin, CXSourceLocation end) {
1651 if (begin.ptr_data[0] != end.ptr_data[0] ||
1652 begin.ptr_data[1] != end.ptr_data[1])
1653 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001654
1655 CXSourceRange Result = { { begin.ptr_data[0], begin.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00001656 begin.int_data, end.int_data };
Douglas Gregorb9790342010-01-22 21:44:22 +00001657 return Result;
1658}
1659
Douglas Gregor46766dc2010-01-26 19:19:08 +00001660void clang_getInstantiationLocation(CXSourceLocation location,
1661 CXFile *file,
1662 unsigned *line,
1663 unsigned *column,
1664 unsigned *offset) {
Douglas Gregor1db19de2010-01-19 21:36:55 +00001665 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
1666
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00001667 if (!location.ptr_data[0] || Loc.isInvalid()) {
Douglas Gregor46766dc2010-01-26 19:19:08 +00001668 if (file)
1669 *file = 0;
1670 if (line)
1671 *line = 0;
1672 if (column)
1673 *column = 0;
1674 if (offset)
1675 *offset = 0;
1676 return;
1677 }
1678
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00001679 const SourceManager &SM =
1680 *static_cast<const SourceManager*>(location.ptr_data[0]);
Douglas Gregor1db19de2010-01-19 21:36:55 +00001681 SourceLocation InstLoc = SM.getInstantiationLoc(Loc);
Douglas Gregor1db19de2010-01-19 21:36:55 +00001682
1683 if (file)
1684 *file = (void *)SM.getFileEntryForID(SM.getFileID(InstLoc));
1685 if (line)
1686 *line = SM.getInstantiationLineNumber(InstLoc);
1687 if (column)
1688 *column = SM.getInstantiationColumnNumber(InstLoc);
Douglas Gregore69517c2010-01-26 03:07:15 +00001689 if (offset)
Douglas Gregor46766dc2010-01-26 19:19:08 +00001690 *offset = SM.getDecomposedLoc(InstLoc).second;
Douglas Gregore69517c2010-01-26 03:07:15 +00001691}
1692
Douglas Gregor1db19de2010-01-19 21:36:55 +00001693CXSourceLocation clang_getRangeStart(CXSourceRange range) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001694 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00001695 range.begin_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00001696 return Result;
1697}
1698
1699CXSourceLocation clang_getRangeEnd(CXSourceRange range) {
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00001700 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00001701 range.end_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00001702 return Result;
1703}
1704
Douglas Gregorb9790342010-01-22 21:44:22 +00001705} // end: extern "C"
1706
Douglas Gregor1db19de2010-01-19 21:36:55 +00001707//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00001708// CXFile Operations.
1709//===----------------------------------------------------------------------===//
1710
1711extern "C" {
Ted Kremenek74844072010-02-17 00:41:20 +00001712CXString clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00001713 if (!SFile)
Ted Kremenek74844072010-02-17 00:41:20 +00001714 return createCXString(NULL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001715
Steve Naroff88145032009-10-27 14:35:18 +00001716 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Ted Kremenek74844072010-02-17 00:41:20 +00001717 return createCXString(FEnt->getName());
Steve Naroff88145032009-10-27 14:35:18 +00001718}
1719
1720time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00001721 if (!SFile)
1722 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001723
Steve Naroff88145032009-10-27 14:35:18 +00001724 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
1725 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +00001726}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001727
Douglas Gregorb9790342010-01-22 21:44:22 +00001728CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
1729 if (!tu)
1730 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001731
Douglas Gregorb9790342010-01-22 21:44:22 +00001732 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001733
Douglas Gregorb9790342010-01-22 21:44:22 +00001734 FileManager &FMgr = CXXUnit->getFileManager();
1735 const FileEntry *File = FMgr.getFile(file_name, file_name+strlen(file_name));
1736 return const_cast<FileEntry *>(File);
1737}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001738
Ted Kremenekfb480492010-01-13 21:46:36 +00001739} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +00001740
Ted Kremenekfb480492010-01-13 21:46:36 +00001741//===----------------------------------------------------------------------===//
1742// CXCursor Operations.
1743//===----------------------------------------------------------------------===//
1744
Ted Kremenekfb480492010-01-13 21:46:36 +00001745static Decl *getDeclFromExpr(Stmt *E) {
1746 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
1747 return RefExpr->getDecl();
1748 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
1749 return ME->getMemberDecl();
1750 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
1751 return RE->getDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001752
Ted Kremenekfb480492010-01-13 21:46:36 +00001753 if (CallExpr *CE = dyn_cast<CallExpr>(E))
1754 return getDeclFromExpr(CE->getCallee());
1755 if (CastExpr *CE = dyn_cast<CastExpr>(E))
1756 return getDeclFromExpr(CE->getSubExpr());
1757 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
1758 return OME->getMethodDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001759
Ted Kremenekfb480492010-01-13 21:46:36 +00001760 return 0;
1761}
1762
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00001763static SourceLocation getLocationFromExpr(Expr *E) {
1764 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
1765 return /*FIXME:*/Msg->getLeftLoc();
1766 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
1767 return DRE->getLocation();
1768 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
1769 return Member->getMemberLoc();
1770 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
1771 return Ivar->getLocation();
1772 return E->getLocStart();
1773}
1774
Ted Kremenekfb480492010-01-13 21:46:36 +00001775extern "C" {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001776
1777unsigned clang_visitChildren(CXCursor parent,
Douglas Gregorb1373d02010-01-20 20:59:29 +00001778 CXCursorVisitor visitor,
1779 CXClientData client_data) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001780 ASTUnit *CXXUnit = getCursorASTUnit(parent);
Douglas Gregorb1373d02010-01-20 20:59:29 +00001781
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001782 CursorVisitor CursorVis(CXXUnit, visitor, client_data,
1783 CXXUnit->getMaxPCHLevel());
Douglas Gregorb1373d02010-01-20 20:59:29 +00001784 return CursorVis.VisitChildren(parent);
1785}
1786
Douglas Gregor78205d42010-01-20 21:45:58 +00001787static CXString getDeclSpelling(Decl *D) {
1788 NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
1789 if (!ND)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001790 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001791
Douglas Gregor78205d42010-01-20 21:45:58 +00001792 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001793 return createCXString(OMD->getSelector().getAsString());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001794
Douglas Gregor78205d42010-01-20 21:45:58 +00001795 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
1796 // No, this isn't the same as the code below. getIdentifier() is non-virtual
1797 // and returns different names. NamedDecl returns the class name and
1798 // ObjCCategoryImplDecl returns the category name.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001799 return createCXString(CIMP->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001800
Ted Kremenek50aa6ac2010-05-19 21:51:10 +00001801 llvm::SmallString<1024> S;
1802 llvm::raw_svector_ostream os(S);
1803 ND->printName(os);
1804
1805 return createCXString(os.str());
Douglas Gregor78205d42010-01-20 21:45:58 +00001806}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001807
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001808CXString clang_getCursorSpelling(CXCursor C) {
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001809 if (clang_isTranslationUnit(C.kind))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001810 return clang_getTranslationUnitSpelling(C.data[2]);
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001811
Steve Narofff334b4e2009-09-02 18:26:48 +00001812 if (clang_isReference(C.kind)) {
1813 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00001814 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +00001815 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001816 return createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00001817 }
1818 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +00001819 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001820 return createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00001821 }
1822 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +00001823 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +00001824 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001825 return createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00001826 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001827 case CXCursor_TypeRef: {
1828 TypeDecl *Type = getCursorTypeRef(C).first;
1829 assert(Type && "Missing type decl");
1830
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001831 return createCXString(getCursorContext(C).getTypeDeclType(Type).
1832 getAsString());
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001833 }
1834
Daniel Dunbaracca7252009-11-30 20:42:49 +00001835 default:
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001836 return createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +00001837 }
1838 }
Douglas Gregor97b98722010-01-19 23:20:36 +00001839
1840 if (clang_isExpression(C.kind)) {
1841 Decl *D = getDeclFromExpr(getCursorExpr(C));
1842 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +00001843 return getDeclSpelling(D);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001844 return createCXString("");
Douglas Gregor97b98722010-01-19 23:20:36 +00001845 }
1846
Douglas Gregor4ae8f292010-03-18 17:52:52 +00001847 if (C.kind == CXCursor_MacroInstantiation)
1848 return createCXString(getCursorMacroInstantiation(C)->getName()
1849 ->getNameStart());
1850
Douglas Gregor572feb22010-03-18 18:04:21 +00001851 if (C.kind == CXCursor_MacroDefinition)
1852 return createCXString(getCursorMacroDefinition(C)->getName()
1853 ->getNameStart());
1854
Douglas Gregor60cbfac2010-01-25 16:56:17 +00001855 if (clang_isDeclaration(C.kind))
1856 return getDeclSpelling(getCursorDecl(C));
Ted Kremeneke68fff62010-02-17 00:41:32 +00001857
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001858 return createCXString("");
Steve Narofff334b4e2009-09-02 18:26:48 +00001859}
1860
Ted Kremeneke68fff62010-02-17 00:41:32 +00001861CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00001862 switch (Kind) {
Ted Kremeneke68fff62010-02-17 00:41:32 +00001863 case CXCursor_FunctionDecl:
1864 return createCXString("FunctionDecl");
1865 case CXCursor_TypedefDecl:
1866 return createCXString("TypedefDecl");
1867 case CXCursor_EnumDecl:
1868 return createCXString("EnumDecl");
1869 case CXCursor_EnumConstantDecl:
1870 return createCXString("EnumConstantDecl");
1871 case CXCursor_StructDecl:
1872 return createCXString("StructDecl");
1873 case CXCursor_UnionDecl:
1874 return createCXString("UnionDecl");
1875 case CXCursor_ClassDecl:
1876 return createCXString("ClassDecl");
1877 case CXCursor_FieldDecl:
1878 return createCXString("FieldDecl");
1879 case CXCursor_VarDecl:
1880 return createCXString("VarDecl");
1881 case CXCursor_ParmDecl:
1882 return createCXString("ParmDecl");
1883 case CXCursor_ObjCInterfaceDecl:
1884 return createCXString("ObjCInterfaceDecl");
1885 case CXCursor_ObjCCategoryDecl:
1886 return createCXString("ObjCCategoryDecl");
1887 case CXCursor_ObjCProtocolDecl:
1888 return createCXString("ObjCProtocolDecl");
1889 case CXCursor_ObjCPropertyDecl:
1890 return createCXString("ObjCPropertyDecl");
1891 case CXCursor_ObjCIvarDecl:
1892 return createCXString("ObjCIvarDecl");
1893 case CXCursor_ObjCInstanceMethodDecl:
1894 return createCXString("ObjCInstanceMethodDecl");
1895 case CXCursor_ObjCClassMethodDecl:
1896 return createCXString("ObjCClassMethodDecl");
1897 case CXCursor_ObjCImplementationDecl:
1898 return createCXString("ObjCImplementationDecl");
1899 case CXCursor_ObjCCategoryImplDecl:
1900 return createCXString("ObjCCategoryImplDecl");
Ted Kremenek8bd5a692010-04-13 23:39:06 +00001901 case CXCursor_CXXMethod:
1902 return createCXString("CXXMethod");
Ted Kremeneke68fff62010-02-17 00:41:32 +00001903 case CXCursor_UnexposedDecl:
1904 return createCXString("UnexposedDecl");
1905 case CXCursor_ObjCSuperClassRef:
1906 return createCXString("ObjCSuperClassRef");
1907 case CXCursor_ObjCProtocolRef:
1908 return createCXString("ObjCProtocolRef");
1909 case CXCursor_ObjCClassRef:
1910 return createCXString("ObjCClassRef");
1911 case CXCursor_TypeRef:
1912 return createCXString("TypeRef");
1913 case CXCursor_UnexposedExpr:
1914 return createCXString("UnexposedExpr");
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00001915 case CXCursor_BlockExpr:
1916 return createCXString("BlockExpr");
Ted Kremeneke68fff62010-02-17 00:41:32 +00001917 case CXCursor_DeclRefExpr:
1918 return createCXString("DeclRefExpr");
1919 case CXCursor_MemberRefExpr:
1920 return createCXString("MemberRefExpr");
1921 case CXCursor_CallExpr:
1922 return createCXString("CallExpr");
1923 case CXCursor_ObjCMessageExpr:
1924 return createCXString("ObjCMessageExpr");
1925 case CXCursor_UnexposedStmt:
1926 return createCXString("UnexposedStmt");
1927 case CXCursor_InvalidFile:
1928 return createCXString("InvalidFile");
Ted Kremenek292db642010-03-19 20:39:05 +00001929 case CXCursor_InvalidCode:
1930 return createCXString("InvalidCode");
Ted Kremeneke68fff62010-02-17 00:41:32 +00001931 case CXCursor_NoDeclFound:
1932 return createCXString("NoDeclFound");
1933 case CXCursor_NotImplemented:
1934 return createCXString("NotImplemented");
1935 case CXCursor_TranslationUnit:
1936 return createCXString("TranslationUnit");
Ted Kremeneke77f4432010-02-18 03:09:07 +00001937 case CXCursor_UnexposedAttr:
1938 return createCXString("UnexposedAttr");
1939 case CXCursor_IBActionAttr:
1940 return createCXString("attribute(ibaction)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00001941 case CXCursor_IBOutletAttr:
1942 return createCXString("attribute(iboutlet)");
Ted Kremenek857e9182010-05-19 17:38:06 +00001943 case CXCursor_IBOutletCollectionAttr:
1944 return createCXString("attribute(iboutletcollection)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00001945 case CXCursor_PreprocessingDirective:
1946 return createCXString("preprocessing directive");
Douglas Gregor572feb22010-03-18 18:04:21 +00001947 case CXCursor_MacroDefinition:
1948 return createCXString("macro definition");
Douglas Gregor48072312010-03-18 15:23:44 +00001949 case CXCursor_MacroInstantiation:
1950 return createCXString("macro instantiation");
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00001951 case CXCursor_Namespace:
1952 return createCXString("Namespace");
Ted Kremeneka0536d82010-05-07 01:04:29 +00001953 case CXCursor_LinkageSpec:
1954 return createCXString("LinkageSpec");
Steve Naroff89922f82009-08-31 00:59:03 +00001955 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00001956
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00001957 llvm_unreachable("Unhandled CXCursorKind");
Ted Kremeneke68fff62010-02-17 00:41:32 +00001958 return createCXString(NULL);
Steve Naroff600866c2009-08-27 19:51:58 +00001959}
Steve Naroff89922f82009-08-31 00:59:03 +00001960
Ted Kremeneke68fff62010-02-17 00:41:32 +00001961enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
1962 CXCursor parent,
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001963 CXClientData client_data) {
1964 CXCursor *BestCursor = static_cast<CXCursor *>(client_data);
1965 *BestCursor = cursor;
1966 return CXChildVisit_Recurse;
1967}
Ted Kremeneke68fff62010-02-17 00:41:32 +00001968
Douglas Gregorb9790342010-01-22 21:44:22 +00001969CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
1970 if (!TU)
Ted Kremenekf4629892010-01-14 01:51:23 +00001971 return clang_getNullCursor();
Ted Kremeneke68fff62010-02-17 00:41:32 +00001972
Douglas Gregorb9790342010-01-22 21:44:22 +00001973 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregorbdf60622010-03-05 21:16:25 +00001974 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
1975
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00001976 // Translate the given source location to make it point at the beginning of
1977 // the token under the cursor.
Ted Kremeneka297de22010-01-25 22:34:44 +00001978 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
Ted Kremeneka629ea42010-07-29 00:52:07 +00001979
1980 // Guard against an invalid SourceLocation, or we may assert in one
1981 // of the following calls.
1982 if (SLoc.isInvalid())
1983 return clang_getNullCursor();
1984
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00001985 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
1986 CXXUnit->getASTContext().getLangOptions());
1987
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001988 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
1989 if (SLoc.isValid()) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001990 // FIXME: Would be great to have a "hint" cursor, then walk from that
1991 // hint cursor upward until we find a cursor whose source range encloses
1992 // the region of interest, rather than starting from the translation unit.
1993 CXCursor Parent = clang_getTranslationUnitCursor(CXXUnit);
Ted Kremeneke68fff62010-02-17 00:41:32 +00001994 CursorVisitor CursorVis(CXXUnit, GetCursorVisitor, &Result,
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00001995 Decl::MaxPCHLevel, SourceLocation(SLoc));
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001996 CursorVis.VisitChildren(Parent);
Steve Naroff77128dd2009-09-15 20:25:34 +00001997 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00001998 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00001999}
2000
Ted Kremenek73885552009-11-17 19:28:59 +00002001CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00002002 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00002003}
2004
2005unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00002006 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00002007}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002008
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002009unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00002010 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
2011}
2012
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002013unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +00002014 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
2015}
Steve Naroff2d4d6292009-08-31 14:26:51 +00002016
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002017unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00002018 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
2019}
2020
Douglas Gregor97b98722010-01-19 23:20:36 +00002021unsigned clang_isExpression(enum CXCursorKind K) {
2022 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
2023}
2024
2025unsigned clang_isStatement(enum CXCursorKind K) {
2026 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
2027}
2028
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002029unsigned clang_isTranslationUnit(enum CXCursorKind K) {
2030 return K == CXCursor_TranslationUnit;
2031}
2032
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002033unsigned clang_isPreprocessing(enum CXCursorKind K) {
2034 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
2035}
2036
Ted Kremenekad6eff62010-03-08 21:17:29 +00002037unsigned clang_isUnexposed(enum CXCursorKind K) {
2038 switch (K) {
2039 case CXCursor_UnexposedDecl:
2040 case CXCursor_UnexposedExpr:
2041 case CXCursor_UnexposedStmt:
2042 case CXCursor_UnexposedAttr:
2043 return true;
2044 default:
2045 return false;
2046 }
2047}
2048
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002049CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00002050 return C.kind;
2051}
2052
Douglas Gregor98258af2010-01-18 22:46:11 +00002053CXSourceLocation clang_getCursorLocation(CXCursor C) {
2054 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00002055 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002056 case CXCursor_ObjCSuperClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00002057 std::pair<ObjCInterfaceDecl *, SourceLocation> P
2058 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00002059 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00002060 }
2061
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002062 case CXCursor_ObjCProtocolRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00002063 std::pair<ObjCProtocolDecl *, SourceLocation> P
2064 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00002065 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00002066 }
2067
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002068 case CXCursor_ObjCClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00002069 std::pair<ObjCInterfaceDecl *, SourceLocation> P
2070 = getCursorObjCClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00002071 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00002072 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002073
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002074 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002075 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00002076 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002077 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002078
Douglas Gregorf46034a2010-01-18 23:41:10 +00002079 default:
2080 // FIXME: Need a way to enumerate all non-reference cases.
2081 llvm_unreachable("Missed a reference kind");
2082 }
Douglas Gregor98258af2010-01-18 22:46:11 +00002083 }
Douglas Gregor97b98722010-01-19 23:20:36 +00002084
2085 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002086 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00002087 getLocationFromExpr(getCursorExpr(C)));
2088
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002089 if (C.kind == CXCursor_PreprocessingDirective) {
2090 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
2091 return cxloc::translateSourceLocation(getCursorContext(C), L);
2092 }
Douglas Gregor48072312010-03-18 15:23:44 +00002093
2094 if (C.kind == CXCursor_MacroInstantiation) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002095 SourceLocation L
2096 = cxcursor::getCursorMacroInstantiation(C)->getSourceRange().getBegin();
Douglas Gregor48072312010-03-18 15:23:44 +00002097 return cxloc::translateSourceLocation(getCursorContext(C), L);
2098 }
Douglas Gregor572feb22010-03-18 18:04:21 +00002099
2100 if (C.kind == CXCursor_MacroDefinition) {
2101 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
2102 return cxloc::translateSourceLocation(getCursorContext(C), L);
2103 }
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002104
Ted Kremenek9a700d22010-05-12 06:16:13 +00002105 if (C.kind < CXCursor_FirstDecl || C.kind > CXCursor_LastDecl)
Douglas Gregor5352ac02010-01-28 00:27:43 +00002106 return clang_getNullLocation();
Douglas Gregor98258af2010-01-18 22:46:11 +00002107
Douglas Gregorf46034a2010-01-18 23:41:10 +00002108 Decl *D = getCursorDecl(C);
Douglas Gregorf46034a2010-01-18 23:41:10 +00002109 SourceLocation Loc = D->getLocation();
2110 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
2111 Loc = Class->getClassLoc();
Douglas Gregor2ca54fe2010-03-22 15:53:50 +00002112 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00002113}
Douglas Gregora7bde202010-01-19 00:34:46 +00002114
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002115} // end extern "C"
2116
2117static SourceRange getRawCursorExtent(CXCursor C) {
Douglas Gregora7bde202010-01-19 00:34:46 +00002118 if (clang_isReference(C.kind)) {
2119 switch (C.kind) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002120 case CXCursor_ObjCSuperClassRef:
2121 return getCursorObjCSuperClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002122
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002123 case CXCursor_ObjCProtocolRef:
2124 return getCursorObjCProtocolRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002125
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002126 case CXCursor_ObjCClassRef:
2127 return getCursorObjCClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002128
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002129 case CXCursor_TypeRef:
2130 return getCursorTypeRef(C).second;
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002131
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002132 default:
2133 // FIXME: Need a way to enumerate all non-reference cases.
2134 llvm_unreachable("Missed a reference kind");
Douglas Gregora7bde202010-01-19 00:34:46 +00002135 }
2136 }
Douglas Gregor97b98722010-01-19 23:20:36 +00002137
2138 if (clang_isExpression(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002139 return getCursorExpr(C)->getSourceRange();
Douglas Gregor33e9abd2010-01-22 19:49:59 +00002140
2141 if (clang_isStatement(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002142 return getCursorStmt(C)->getSourceRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002143
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002144 if (C.kind == CXCursor_PreprocessingDirective)
2145 return cxcursor::getCursorPreprocessingDirective(C);
Douglas Gregor48072312010-03-18 15:23:44 +00002146
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002147 if (C.kind == CXCursor_MacroInstantiation)
2148 return cxcursor::getCursorMacroInstantiation(C)->getSourceRange();
Douglas Gregor572feb22010-03-18 18:04:21 +00002149
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002150 if (C.kind == CXCursor_MacroDefinition)
2151 return cxcursor::getCursorMacroDefinition(C)->getSourceRange();
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002152
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002153 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl)
2154 return getCursorDecl(C)->getSourceRange();
2155
2156 return SourceRange();
2157}
2158
2159extern "C" {
2160
2161CXSourceRange clang_getCursorExtent(CXCursor C) {
2162 SourceRange R = getRawCursorExtent(C);
2163 if (R.isInvalid())
Douglas Gregor5352ac02010-01-28 00:27:43 +00002164 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002165
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002166 return cxloc::translateSourceRange(getCursorContext(C), R);
Douglas Gregora7bde202010-01-19 00:34:46 +00002167}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002168
2169CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002170 if (clang_isInvalid(C.kind))
2171 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002172
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002173 ASTUnit *CXXUnit = getCursorASTUnit(C);
Douglas Gregorb6998662010-01-19 19:34:47 +00002174 if (clang_isDeclaration(C.kind))
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002175 return C;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002176
Douglas Gregor97b98722010-01-19 23:20:36 +00002177 if (clang_isExpression(C.kind)) {
2178 Decl *D = getDeclFromExpr(getCursorExpr(C));
2179 if (D)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002180 return MakeCXCursor(D, CXXUnit);
Douglas Gregor97b98722010-01-19 23:20:36 +00002181 return clang_getNullCursor();
2182 }
2183
Douglas Gregorbf7efa22010-03-18 18:23:03 +00002184 if (C.kind == CXCursor_MacroInstantiation) {
2185 if (MacroDefinition *Def = getCursorMacroInstantiation(C)->getDefinition())
2186 return MakeMacroDefinitionCursor(Def, CXXUnit);
2187 }
2188
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002189 if (!clang_isReference(C.kind))
2190 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002191
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002192 switch (C.kind) {
2193 case CXCursor_ObjCSuperClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002194 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002195
2196 case CXCursor_ObjCProtocolRef: {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002197 return MakeCXCursor(getCursorObjCProtocolRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002198
2199 case CXCursor_ObjCClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002200 return MakeCXCursor(getCursorObjCClassRef(C).first, CXXUnit);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002201
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002202 case CXCursor_TypeRef:
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002203 return MakeCXCursor(getCursorTypeRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002204
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002205 default:
2206 // We would prefer to enumerate all non-reference cursor kinds here.
2207 llvm_unreachable("Unhandled reference cursor kind");
2208 break;
2209 }
2210 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002211
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002212 return clang_getNullCursor();
2213}
2214
Douglas Gregorb6998662010-01-19 19:34:47 +00002215CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002216 if (clang_isInvalid(C.kind))
2217 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002218
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002219 ASTUnit *CXXUnit = getCursorASTUnit(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002220
Douglas Gregorb6998662010-01-19 19:34:47 +00002221 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00002222 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00002223 C = clang_getCursorReferenced(C);
2224 WasReference = true;
2225 }
2226
Douglas Gregorbf7efa22010-03-18 18:23:03 +00002227 if (C.kind == CXCursor_MacroInstantiation)
2228 return clang_getCursorReferenced(C);
2229
Douglas Gregorb6998662010-01-19 19:34:47 +00002230 if (!clang_isDeclaration(C.kind))
2231 return clang_getNullCursor();
2232
2233 Decl *D = getCursorDecl(C);
2234 if (!D)
2235 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002236
Douglas Gregorb6998662010-01-19 19:34:47 +00002237 switch (D->getKind()) {
2238 // Declaration kinds that don't really separate the notions of
2239 // declaration and definition.
2240 case Decl::Namespace:
2241 case Decl::Typedef:
2242 case Decl::TemplateTypeParm:
2243 case Decl::EnumConstant:
2244 case Decl::Field:
2245 case Decl::ObjCIvar:
2246 case Decl::ObjCAtDefsField:
2247 case Decl::ImplicitParam:
2248 case Decl::ParmVar:
2249 case Decl::NonTypeTemplateParm:
2250 case Decl::TemplateTemplateParm:
2251 case Decl::ObjCCategoryImpl:
2252 case Decl::ObjCImplementation:
Abramo Bagnara6206d532010-06-05 05:09:32 +00002253 case Decl::AccessSpec:
Douglas Gregorb6998662010-01-19 19:34:47 +00002254 case Decl::LinkageSpec:
2255 case Decl::ObjCPropertyImpl:
2256 case Decl::FileScopeAsm:
2257 case Decl::StaticAssert:
2258 case Decl::Block:
2259 return C;
2260
2261 // Declaration kinds that don't make any sense here, but are
2262 // nonetheless harmless.
2263 case Decl::TranslationUnit:
Douglas Gregorb6998662010-01-19 19:34:47 +00002264 break;
2265
2266 // Declaration kinds for which the definition is not resolvable.
2267 case Decl::UnresolvedUsingTypename:
2268 case Decl::UnresolvedUsingValue:
2269 break;
2270
2271 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002272 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
2273 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002274
2275 case Decl::NamespaceAlias:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002276 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002277
2278 case Decl::Enum:
2279 case Decl::Record:
2280 case Decl::CXXRecord:
2281 case Decl::ClassTemplateSpecialization:
2282 case Decl::ClassTemplatePartialSpecialization:
Douglas Gregor952b0172010-02-11 01:04:33 +00002283 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002284 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002285 return clang_getNullCursor();
2286
2287 case Decl::Function:
2288 case Decl::CXXMethod:
2289 case Decl::CXXConstructor:
2290 case Decl::CXXDestructor:
2291 case Decl::CXXConversion: {
2292 const FunctionDecl *Def = 0;
2293 if (cast<FunctionDecl>(D)->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002294 return MakeCXCursor(const_cast<FunctionDecl *>(Def), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002295 return clang_getNullCursor();
2296 }
2297
2298 case Decl::Var: {
Sebastian Redl31310a22010-02-01 20:16:42 +00002299 // Ask the variable if it has a definition.
2300 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
2301 return MakeCXCursor(Def, CXXUnit);
2302 return clang_getNullCursor();
Douglas Gregorb6998662010-01-19 19:34:47 +00002303 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002304
Douglas Gregorb6998662010-01-19 19:34:47 +00002305 case Decl::FunctionTemplate: {
2306 const FunctionDecl *Def = 0;
2307 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002308 return MakeCXCursor(Def->getDescribedFunctionTemplate(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002309 return clang_getNullCursor();
2310 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002311
Douglas Gregorb6998662010-01-19 19:34:47 +00002312 case Decl::ClassTemplate: {
2313 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
Douglas Gregor952b0172010-02-11 01:04:33 +00002314 ->getDefinition())
Douglas Gregorb6998662010-01-19 19:34:47 +00002315 return MakeCXCursor(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002316 cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002317 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002318 return clang_getNullCursor();
2319 }
2320
2321 case Decl::Using: {
2322 UsingDecl *Using = cast<UsingDecl>(D);
2323 CXCursor Def = clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002324 for (UsingDecl::shadow_iterator S = Using->shadow_begin(),
2325 SEnd = Using->shadow_end();
Douglas Gregorb6998662010-01-19 19:34:47 +00002326 S != SEnd; ++S) {
2327 if (Def != clang_getNullCursor()) {
2328 // FIXME: We have no way to return multiple results.
2329 return clang_getNullCursor();
2330 }
2331
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002332 Def = clang_getCursorDefinition(MakeCXCursor((*S)->getTargetDecl(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002333 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002334 }
2335
2336 return Def;
2337 }
2338
2339 case Decl::UsingShadow:
2340 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002341 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002342 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002343
2344 case Decl::ObjCMethod: {
2345 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
2346 if (Method->isThisDeclarationADefinition())
2347 return C;
2348
2349 // Dig out the method definition in the associated
2350 // @implementation, if we have it.
2351 // FIXME: The ASTs should make finding the definition easier.
2352 if (ObjCInterfaceDecl *Class
2353 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
2354 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
2355 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
2356 Method->isInstanceMethod()))
2357 if (Def->isThisDeclarationADefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002358 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002359
2360 return clang_getNullCursor();
2361 }
2362
2363 case Decl::ObjCCategory:
2364 if (ObjCCategoryImplDecl *Impl
2365 = cast<ObjCCategoryDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002366 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002367 return clang_getNullCursor();
2368
2369 case Decl::ObjCProtocol:
2370 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
2371 return C;
2372 return clang_getNullCursor();
2373
2374 case Decl::ObjCInterface:
2375 // There are two notions of a "definition" for an Objective-C
2376 // class: the interface and its implementation. When we resolved a
2377 // reference to an Objective-C class, produce the @interface as
2378 // the definition; when we were provided with the interface,
2379 // produce the @implementation as the definition.
2380 if (WasReference) {
2381 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
2382 return C;
2383 } else if (ObjCImplementationDecl *Impl
2384 = cast<ObjCInterfaceDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002385 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002386 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002387
Douglas Gregorb6998662010-01-19 19:34:47 +00002388 case Decl::ObjCProperty:
2389 // FIXME: We don't really know where to find the
2390 // ObjCPropertyImplDecls that implement this property.
2391 return clang_getNullCursor();
2392
2393 case Decl::ObjCCompatibleAlias:
2394 if (ObjCInterfaceDecl *Class
2395 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
2396 if (!Class->isForwardDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002397 return MakeCXCursor(Class, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002398
Douglas Gregorb6998662010-01-19 19:34:47 +00002399 return clang_getNullCursor();
2400
2401 case Decl::ObjCForwardProtocol: {
2402 ObjCForwardProtocolDecl *Forward = cast<ObjCForwardProtocolDecl>(D);
2403 if (Forward->protocol_size() == 1)
2404 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002405 MakeCXCursor(*Forward->protocol_begin(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002406 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002407
2408 // FIXME: Cannot return multiple definitions.
2409 return clang_getNullCursor();
2410 }
2411
2412 case Decl::ObjCClass: {
2413 ObjCClassDecl *Class = cast<ObjCClassDecl>(D);
2414 if (Class->size() == 1) {
2415 ObjCInterfaceDecl *IFace = Class->begin()->getInterface();
2416 if (!IFace->isForwardDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002417 return MakeCXCursor(IFace, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002418 return clang_getNullCursor();
2419 }
2420
2421 // FIXME: Cannot return multiple definitions.
2422 return clang_getNullCursor();
2423 }
2424
2425 case Decl::Friend:
2426 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002427 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002428 return clang_getNullCursor();
2429
2430 case Decl::FriendTemplate:
2431 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002432 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002433 return clang_getNullCursor();
2434 }
2435
2436 return clang_getNullCursor();
2437}
2438
2439unsigned clang_isCursorDefinition(CXCursor C) {
2440 if (!clang_isDeclaration(C.kind))
2441 return 0;
2442
2443 return clang_getCursorDefinition(C) == C;
2444}
2445
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002446void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00002447 const char **startBuf,
2448 const char **endBuf,
2449 unsigned *startLine,
2450 unsigned *startColumn,
2451 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002452 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00002453 assert(getCursorDecl(C) && "CXCursor has null decl");
2454 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00002455 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
2456 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002457
Steve Naroff4ade6d62009-09-23 17:52:52 +00002458 SourceManager &SM = FD->getASTContext().getSourceManager();
2459 *startBuf = SM.getCharacterData(Body->getLBracLoc());
2460 *endBuf = SM.getCharacterData(Body->getRBracLoc());
2461 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
2462 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
2463 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
2464 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
2465}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002466
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002467void clang_enableStackTraces(void) {
2468 llvm::sys::PrintStackTraceOnErrorSignal();
2469}
2470
Ted Kremenekfb480492010-01-13 21:46:36 +00002471} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00002472
Ted Kremenekfb480492010-01-13 21:46:36 +00002473//===----------------------------------------------------------------------===//
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002474// Token-based Operations.
2475//===----------------------------------------------------------------------===//
2476
2477/* CXToken layout:
2478 * int_data[0]: a CXTokenKind
2479 * int_data[1]: starting token location
2480 * int_data[2]: token length
2481 * int_data[3]: reserved
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002482 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002483 * otherwise unused.
2484 */
2485extern "C" {
2486
2487CXTokenKind clang_getTokenKind(CXToken CXTok) {
2488 return static_cast<CXTokenKind>(CXTok.int_data[0]);
2489}
2490
2491CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
2492 switch (clang_getTokenKind(CXTok)) {
2493 case CXToken_Identifier:
2494 case CXToken_Keyword:
2495 // We know we have an IdentifierInfo*, so use that.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002496 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
2497 ->getNameStart());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002498
2499 case CXToken_Literal: {
2500 // We have stashed the starting pointer in the ptr_data field. Use it.
2501 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002502 return createCXString(llvm::StringRef(Text, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002503 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002504
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002505 case CXToken_Punctuation:
2506 case CXToken_Comment:
2507 break;
2508 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002509
2510 // We have to find the starting buffer pointer the hard way, by
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002511 // deconstructing the source location.
2512 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2513 if (!CXXUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002514 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002515
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002516 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
2517 std::pair<FileID, unsigned> LocInfo
2518 = CXXUnit->getSourceManager().getDecomposedLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +00002519 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002520 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00002521 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
2522 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00002523 return createCXString("");
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002524
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002525 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002526}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002527
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002528CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
2529 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2530 if (!CXXUnit)
2531 return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002532
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002533 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
2534 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
2535}
2536
2537CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
2538 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregor5352ac02010-01-28 00:27:43 +00002539 if (!CXXUnit)
2540 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002541
2542 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002543 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
2544}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002545
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002546void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
2547 CXToken **Tokens, unsigned *NumTokens) {
2548 if (Tokens)
2549 *Tokens = 0;
2550 if (NumTokens)
2551 *NumTokens = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002552
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002553 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2554 if (!CXXUnit || !Tokens || !NumTokens)
2555 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002556
Douglas Gregorbdf60622010-03-05 21:16:25 +00002557 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
2558
Daniel Dunbar85b988f2010-02-14 08:31:57 +00002559 SourceRange R = cxloc::translateCXSourceRange(Range);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002560 if (R.isInvalid())
2561 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002562
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002563 SourceManager &SourceMgr = CXXUnit->getSourceManager();
2564 std::pair<FileID, unsigned> BeginLocInfo
2565 = SourceMgr.getDecomposedLoc(R.getBegin());
2566 std::pair<FileID, unsigned> EndLocInfo
2567 = SourceMgr.getDecomposedLoc(R.getEnd());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002568
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002569 // Cannot tokenize across files.
2570 if (BeginLocInfo.first != EndLocInfo.first)
2571 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002572
2573 // Create a lexer
Douglas Gregorf715ca12010-03-16 00:06:06 +00002574 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002575 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00002576 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
Douglas Gregor47a3fcd2010-03-16 20:26:15 +00002577 if (Invalid)
2578 return;
Douglas Gregoraea67db2010-03-15 22:54:52 +00002579
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002580 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
2581 CXXUnit->getASTContext().getLangOptions(),
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002582 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002583 Lex.SetCommentRetentionState(true);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002584
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002585 // Lex tokens until we hit the end of the range.
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002586 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002587 llvm::SmallVector<CXToken, 32> CXTokens;
2588 Token Tok;
2589 do {
2590 // Lex the next token
2591 Lex.LexFromRawLexer(Tok);
2592 if (Tok.is(tok::eof))
2593 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002594
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002595 // Initialize the CXToken.
2596 CXToken CXTok;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002597
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002598 // - Common fields
2599 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
2600 CXTok.int_data[2] = Tok.getLength();
2601 CXTok.int_data[3] = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002602
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002603 // - Kind-specific fields
2604 if (Tok.isLiteral()) {
2605 CXTok.int_data[0] = CXToken_Literal;
2606 CXTok.ptr_data = (void *)Tok.getLiteralData();
2607 } else if (Tok.is(tok::identifier)) {
Douglas Gregoraea67db2010-03-15 22:54:52 +00002608 // Lookup the identifier to determine whether we have a keyword.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002609 std::pair<FileID, unsigned> LocInfo
2610 = SourceMgr.getDecomposedLoc(Tok.getLocation());
Douglas Gregorf715ca12010-03-16 00:06:06 +00002611 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002612 llvm::StringRef Buf
Douglas Gregorf715ca12010-03-16 00:06:06 +00002613 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
2614 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00002615 return;
2616
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002617 const char *StartPos = Buf.data() + LocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002618 IdentifierInfo *II
2619 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok, StartPos);
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00002620
2621 if (II->getObjCKeywordID() != tok::objc_not_keyword) {
2622 CXTok.int_data[0] = CXToken_Keyword;
2623 }
2624 else {
2625 CXTok.int_data[0] = II->getTokenID() == tok::identifier?
2626 CXToken_Identifier
2627 : CXToken_Keyword;
2628 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002629 CXTok.ptr_data = II;
2630 } else if (Tok.is(tok::comment)) {
2631 CXTok.int_data[0] = CXToken_Comment;
2632 CXTok.ptr_data = 0;
2633 } else {
2634 CXTok.int_data[0] = CXToken_Punctuation;
2635 CXTok.ptr_data = 0;
2636 }
2637 CXTokens.push_back(CXTok);
2638 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002639
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002640 if (CXTokens.empty())
2641 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002642
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002643 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
2644 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
2645 *NumTokens = CXTokens.size();
2646}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002647
Ted Kremenek6db61092010-05-05 00:55:15 +00002648void clang_disposeTokens(CXTranslationUnit TU,
2649 CXToken *Tokens, unsigned NumTokens) {
2650 free(Tokens);
2651}
2652
2653} // end: extern "C"
2654
2655//===----------------------------------------------------------------------===//
2656// Token annotation APIs.
2657//===----------------------------------------------------------------------===//
2658
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002659typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002660static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
2661 CXCursor parent,
2662 CXClientData client_data);
Ted Kremenek6db61092010-05-05 00:55:15 +00002663namespace {
2664class AnnotateTokensWorker {
2665 AnnotateTokensData &Annotated;
Ted Kremenek11949cb2010-05-05 00:55:17 +00002666 CXToken *Tokens;
2667 CXCursor *Cursors;
2668 unsigned NumTokens;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002669 unsigned TokIdx;
2670 CursorVisitor AnnotateVis;
2671 SourceManager &SrcMgr;
2672
2673 bool MoreTokens() const { return TokIdx < NumTokens; }
2674 unsigned NextToken() const { return TokIdx; }
2675 void AdvanceToken() { ++TokIdx; }
2676 SourceLocation GetTokenLoc(unsigned tokI) {
2677 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
2678 }
2679
Ted Kremenek6db61092010-05-05 00:55:15 +00002680public:
Ted Kremenek11949cb2010-05-05 00:55:17 +00002681 AnnotateTokensWorker(AnnotateTokensData &annotated,
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002682 CXToken *tokens, CXCursor *cursors, unsigned numTokens,
2683 ASTUnit *CXXUnit, SourceRange RegionOfInterest)
Ted Kremenek11949cb2010-05-05 00:55:17 +00002684 : Annotated(annotated), Tokens(tokens), Cursors(cursors),
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002685 NumTokens(numTokens), TokIdx(0),
2686 AnnotateVis(CXXUnit, AnnotateTokensVisitor, this,
2687 Decl::MaxPCHLevel, RegionOfInterest),
2688 SrcMgr(CXXUnit->getSourceManager()) {}
Ted Kremenek11949cb2010-05-05 00:55:17 +00002689
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002690 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
Ted Kremenek6db61092010-05-05 00:55:15 +00002691 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002692 void AnnotateTokens(CXCursor parent);
Ted Kremenek6db61092010-05-05 00:55:15 +00002693};
2694}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002695
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002696void AnnotateTokensWorker::AnnotateTokens(CXCursor parent) {
2697 // Walk the AST within the region of interest, annotating tokens
2698 // along the way.
2699 VisitChildren(parent);
Ted Kremenek11949cb2010-05-05 00:55:17 +00002700
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002701 for (unsigned I = 0 ; I < TokIdx ; ++I) {
2702 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
2703 if (Pos != Annotated.end())
2704 Cursors[I] = Pos->second;
2705 }
2706
2707 // Finish up annotating any tokens left.
2708 if (!MoreTokens())
2709 return;
2710
2711 const CXCursor &C = clang_getNullCursor();
2712 for (unsigned I = TokIdx ; I < NumTokens ; ++I) {
2713 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
2714 Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second;
Ted Kremenek11949cb2010-05-05 00:55:17 +00002715 }
2716}
2717
Ted Kremenek6db61092010-05-05 00:55:15 +00002718enum CXChildVisitResult
2719AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002720 CXSourceLocation Loc = clang_getCursorLocation(cursor);
2721 // We can always annotate a preprocessing directive/macro instantiation.
2722 if (clang_isPreprocessing(cursor.kind)) {
2723 Annotated[Loc.int_data] = cursor;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002724 return CXChildVisit_Recurse;
2725 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002726
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002727 SourceRange cursorRange = getRawCursorExtent(cursor);
Ted Kremeneka333c662010-05-12 05:29:33 +00002728
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002729 if (cursorRange.isInvalid())
2730 return CXChildVisit_Continue;
Ted Kremeneka333c662010-05-12 05:29:33 +00002731
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002732 SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data);
2733
Ted Kremeneka333c662010-05-12 05:29:33 +00002734 // Adjust the annotated range based specific declarations.
2735 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
2736 if (cursorK >= CXCursor_FirstDecl && cursorK <= CXCursor_LastDecl) {
Ted Kremenek23173d72010-05-18 21:09:07 +00002737 Decl *D = cxcursor::getCursorDecl(cursor);
2738 // Don't visit synthesized ObjC methods, since they have no syntatic
2739 // representation in the source.
2740 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
2741 if (MD->isSynthesized())
2742 return CXChildVisit_Continue;
2743 }
2744 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
Ted Kremeneka333c662010-05-12 05:29:33 +00002745 if (TypeSourceInfo *TI = DD->getTypeSourceInfo()) {
2746 TypeLoc TL = TI->getTypeLoc();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00002747 SourceLocation TLoc = TL.getSourceRange().getBegin();
Ted Kremenek6bfd5332010-05-13 15:38:38 +00002748 if (TLoc.isValid() &&
2749 SrcMgr.isBeforeInTranslationUnit(TLoc, L))
Ted Kremeneka333c662010-05-12 05:29:33 +00002750 cursorRange.setBegin(TLoc);
Ted Kremeneka333c662010-05-12 05:29:33 +00002751 }
2752 }
2753 }
2754
Ted Kremenek3f404602010-08-14 01:14:06 +00002755 // If the location of the cursor occurs within a macro instantiation, record
2756 // the spelling location of the cursor in our annotation map. We can then
2757 // paper over the token labelings during a post-processing step to try and
2758 // get cursor mappings for tokens that are the *arguments* of a macro
2759 // instantiation.
2760 if (L.isMacroID()) {
2761 unsigned rawEncoding = SrcMgr.getSpellingLoc(L).getRawEncoding();
2762 // Only invalidate the old annotation if it isn't part of a preprocessing
2763 // directive. Here we assume that the default construction of CXCursor
2764 // results in CXCursor.kind being an initialized value (i.e., 0). If
2765 // this isn't the case, we can fix by doing lookup + insertion.
2766
2767 CXCursor &oldC = Annotated[rawEncoding];
2768 if (!clang_isPreprocessing(oldC.kind))
2769 oldC = cursor;
2770 }
2771
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002772 const enum CXCursorKind K = clang_getCursorKind(parent);
2773 const CXCursor updateC =
2774 (clang_isInvalid(K) || K == CXCursor_TranslationUnit ||
2775 L.isMacroID())
2776 ? clang_getNullCursor() : parent;
2777
2778 while (MoreTokens()) {
2779 const unsigned I = NextToken();
2780 SourceLocation TokLoc = GetTokenLoc(I);
2781 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
2782 case RangeBefore:
2783 Cursors[I] = updateC;
2784 AdvanceToken();
2785 continue;
2786 case RangeAfter:
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002787 case RangeOverlap:
2788 break;
2789 }
2790 break;
2791 }
2792
2793 // Visit children to get their cursor information.
2794 const unsigned BeforeChildren = NextToken();
2795 VisitChildren(cursor);
2796 const unsigned AfterChildren = NextToken();
2797
2798 // Adjust 'Last' to the last token within the extent of the cursor.
2799 while (MoreTokens()) {
2800 const unsigned I = NextToken();
2801 SourceLocation TokLoc = GetTokenLoc(I);
2802 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
2803 case RangeBefore:
2804 assert(0 && "Infeasible");
2805 case RangeAfter:
2806 break;
2807 case RangeOverlap:
2808 Cursors[I] = updateC;
2809 AdvanceToken();
2810 continue;
2811 }
2812 break;
2813 }
2814 const unsigned Last = NextToken();
Ted Kremenek6db61092010-05-05 00:55:15 +00002815
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002816 // Scan the tokens that are at the beginning of the cursor, but are not
2817 // capture by the child cursors.
2818
2819 // For AST elements within macros, rely on a post-annotate pass to
2820 // to correctly annotate the tokens with cursors. Otherwise we can
2821 // get confusing results of having tokens that map to cursors that really
2822 // are expanded by an instantiation.
2823 if (L.isMacroID())
2824 cursor = clang_getNullCursor();
2825
2826 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
2827 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
2828 break;
2829 Cursors[I] = cursor;
2830 }
2831 // Scan the tokens that are at the end of the cursor, but are not captured
2832 // but the child cursors.
2833 for (unsigned I = AfterChildren; I != Last; ++I)
2834 Cursors[I] = cursor;
2835
2836 TokIdx = Last;
2837 return CXChildVisit_Continue;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002838}
2839
Ted Kremenek6db61092010-05-05 00:55:15 +00002840static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
2841 CXCursor parent,
2842 CXClientData client_data) {
2843 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
2844}
2845
2846extern "C" {
2847
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002848void clang_annotateTokens(CXTranslationUnit TU,
2849 CXToken *Tokens, unsigned NumTokens,
2850 CXCursor *Cursors) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002851
2852 if (NumTokens == 0 || !Tokens || !Cursors)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002853 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002854
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002855 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002856 if (!CXXUnit) {
2857 // Any token we don't specifically annotate will have a NULL cursor.
2858 const CXCursor &C = clang_getNullCursor();
2859 for (unsigned I = 0; I != NumTokens; ++I)
2860 Cursors[I] = C;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002861 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002862 }
2863
Douglas Gregorbdf60622010-03-05 21:16:25 +00002864 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002865
Douglas Gregor0396f462010-03-19 05:22:59 +00002866 // Determine the region of interest, which contains all of the tokens.
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002867 SourceRange RegionOfInterest;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002868 RegionOfInterest.setBegin(cxloc::translateSourceLocation(
2869 clang_getTokenLocation(TU, Tokens[0])));
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002870 RegionOfInterest.setEnd(cxloc::translateSourceLocation(
2871 clang_getTokenLocation(TU,
2872 Tokens[NumTokens - 1])));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002873
Douglas Gregor0396f462010-03-19 05:22:59 +00002874 // A mapping from the source locations found when re-lexing or traversing the
2875 // region of interest to the corresponding cursors.
2876 AnnotateTokensData Annotated;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002877
2878 // Relex the tokens within the source range to look for preprocessing
Douglas Gregor0396f462010-03-19 05:22:59 +00002879 // directives.
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002880 SourceManager &SourceMgr = CXXUnit->getSourceManager();
2881 std::pair<FileID, unsigned> BeginLocInfo
2882 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
2883 std::pair<FileID, unsigned> EndLocInfo
2884 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002885
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002886 llvm::StringRef Buffer;
Douglas Gregor0396f462010-03-19 05:22:59 +00002887 bool Invalid = false;
2888 if (BeginLocInfo.first == EndLocInfo.first &&
2889 ((Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid)),true) &&
2890 !Invalid) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002891 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
2892 CXXUnit->getASTContext().getLangOptions(),
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002893 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002894 Buffer.end());
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002895 Lex.SetCommentRetentionState(true);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002896
2897 // Lex tokens in raw mode until we hit the end of the range, to avoid
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002898 // entering #includes or expanding macros.
Douglas Gregor48072312010-03-18 15:23:44 +00002899 while (true) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002900 Token Tok;
2901 Lex.LexFromRawLexer(Tok);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002902
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002903 reprocess:
2904 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
2905 // We have found a preprocessing directive. Gobble it up so that we
2906 // don't see it while preprocessing these tokens later, but keep track of
2907 // all of the token locations inside this preprocessing directive so that
2908 // we can annotate them appropriately.
2909 //
2910 // FIXME: Some simple tests here could identify macro definitions and
2911 // #undefs, to provide specific cursor kinds for those.
2912 std::vector<SourceLocation> Locations;
2913 do {
2914 Locations.push_back(Tok.getLocation());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002915 Lex.LexFromRawLexer(Tok);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002916 } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002917
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002918 using namespace cxcursor;
2919 CXCursor Cursor
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002920 = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
2921 Locations.back()),
Ted Kremenek6db61092010-05-05 00:55:15 +00002922 CXXUnit);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002923 for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
2924 Annotated[Locations[I].getRawEncoding()] = Cursor;
2925 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002926
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002927 if (Tok.isAtStartOfLine())
2928 goto reprocess;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002929
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002930 continue;
2931 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002932
Douglas Gregor48072312010-03-18 15:23:44 +00002933 if (Tok.is(tok::eof))
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002934 break;
2935 }
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002936 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002937
Douglas Gregor0396f462010-03-19 05:22:59 +00002938 // Annotate all of the source locations in the region of interest that map to
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002939 // a specific cursor.
2940 AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens,
2941 CXXUnit, RegionOfInterest);
2942 W.AnnotateTokens(clang_getTranslationUnitCursor(CXXUnit));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002943}
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002944} // end: extern "C"
2945
2946//===----------------------------------------------------------------------===//
Ted Kremenek16b42592010-03-03 06:36:57 +00002947// Operations for querying linkage of a cursor.
2948//===----------------------------------------------------------------------===//
2949
2950extern "C" {
2951CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
Douglas Gregor0396f462010-03-19 05:22:59 +00002952 if (!clang_isDeclaration(cursor.kind))
2953 return CXLinkage_Invalid;
2954
Ted Kremenek16b42592010-03-03 06:36:57 +00002955 Decl *D = cxcursor::getCursorDecl(cursor);
2956 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
2957 switch (ND->getLinkage()) {
2958 case NoLinkage: return CXLinkage_NoLinkage;
2959 case InternalLinkage: return CXLinkage_Internal;
2960 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
2961 case ExternalLinkage: return CXLinkage_External;
2962 };
2963
2964 return CXLinkage_Invalid;
2965}
2966} // end: extern "C"
2967
2968//===----------------------------------------------------------------------===//
Ted Kremenek45e1dae2010-04-12 21:22:16 +00002969// Operations for querying language of a cursor.
2970//===----------------------------------------------------------------------===//
2971
2972static CXLanguageKind getDeclLanguage(const Decl *D) {
2973 switch (D->getKind()) {
2974 default:
2975 break;
2976 case Decl::ImplicitParam:
2977 case Decl::ObjCAtDefsField:
2978 case Decl::ObjCCategory:
2979 case Decl::ObjCCategoryImpl:
2980 case Decl::ObjCClass:
2981 case Decl::ObjCCompatibleAlias:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00002982 case Decl::ObjCForwardProtocol:
2983 case Decl::ObjCImplementation:
2984 case Decl::ObjCInterface:
2985 case Decl::ObjCIvar:
2986 case Decl::ObjCMethod:
2987 case Decl::ObjCProperty:
2988 case Decl::ObjCPropertyImpl:
2989 case Decl::ObjCProtocol:
2990 return CXLanguage_ObjC;
2991 case Decl::CXXConstructor:
2992 case Decl::CXXConversion:
2993 case Decl::CXXDestructor:
2994 case Decl::CXXMethod:
2995 case Decl::CXXRecord:
2996 case Decl::ClassTemplate:
2997 case Decl::ClassTemplatePartialSpecialization:
2998 case Decl::ClassTemplateSpecialization:
2999 case Decl::Friend:
3000 case Decl::FriendTemplate:
3001 case Decl::FunctionTemplate:
3002 case Decl::LinkageSpec:
3003 case Decl::Namespace:
3004 case Decl::NamespaceAlias:
3005 case Decl::NonTypeTemplateParm:
3006 case Decl::StaticAssert:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00003007 case Decl::TemplateTemplateParm:
3008 case Decl::TemplateTypeParm:
3009 case Decl::UnresolvedUsingTypename:
3010 case Decl::UnresolvedUsingValue:
3011 case Decl::Using:
3012 case Decl::UsingDirective:
3013 case Decl::UsingShadow:
3014 return CXLanguage_CPlusPlus;
3015 }
3016
3017 return CXLanguage_C;
3018}
3019
3020extern "C" {
3021CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
3022 if (clang_isDeclaration(cursor.kind))
3023 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
3024
3025 return CXLanguage_Invalid;
3026}
3027} // end: extern "C"
3028
Ted Kremenek9ada39a2010-05-17 20:06:56 +00003029
3030//===----------------------------------------------------------------------===//
3031// C++ AST instrospection.
3032//===----------------------------------------------------------------------===//
3033
3034extern "C" {
3035unsigned clang_CXXMethod_isStatic(CXCursor C) {
3036 if (!clang_isDeclaration(C.kind))
3037 return 0;
3038 CXXMethodDecl *D = dyn_cast<CXXMethodDecl>(cxcursor::getCursorDecl(C));
3039 return (D && D->isStatic()) ? 1 : 0;
Ted Kremenek40b492a2010-05-17 20:12:45 +00003040}
Ted Kremenekb12903e2010-05-18 22:32:15 +00003041
Ted Kremenek9ada39a2010-05-17 20:06:56 +00003042} // end: extern "C"
3043
Ted Kremenek45e1dae2010-04-12 21:22:16 +00003044//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00003045// CXString Operations.
3046//===----------------------------------------------------------------------===//
3047
3048extern "C" {
3049const char *clang_getCString(CXString string) {
3050 return string.Spelling;
3051}
3052
3053void clang_disposeString(CXString string) {
3054 if (string.MustFreeString && string.Spelling)
3055 free((void*)string.Spelling);
3056}
Ted Kremenek04bb7162010-01-22 22:44:15 +00003057
Ted Kremenekfb480492010-01-13 21:46:36 +00003058} // end: extern "C"
Ted Kremenek04bb7162010-01-22 22:44:15 +00003059
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003060namespace clang { namespace cxstring {
3061CXString createCXString(const char *String, bool DupString){
3062 CXString Str;
3063 if (DupString) {
3064 Str.Spelling = strdup(String);
3065 Str.MustFreeString = 1;
3066 } else {
3067 Str.Spelling = String;
3068 Str.MustFreeString = 0;
3069 }
3070 return Str;
3071}
3072
3073CXString createCXString(llvm::StringRef String, bool DupString) {
3074 CXString Result;
3075 if (DupString || (!String.empty() && String.data()[String.size()] != 0)) {
3076 char *Spelling = (char *)malloc(String.size() + 1);
3077 memmove(Spelling, String.data(), String.size());
3078 Spelling[String.size()] = 0;
3079 Result.Spelling = Spelling;
3080 Result.MustFreeString = 1;
3081 } else {
3082 Result.Spelling = String.data();
3083 Result.MustFreeString = 0;
3084 }
3085 return Result;
3086}
3087}}
3088
Ted Kremenek04bb7162010-01-22 22:44:15 +00003089//===----------------------------------------------------------------------===//
3090// Misc. utility functions.
3091//===----------------------------------------------------------------------===//
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003092
Ted Kremenek04bb7162010-01-22 22:44:15 +00003093extern "C" {
3094
Ted Kremeneka2a9d6e2010-02-12 22:54:40 +00003095CXString clang_getClangVersion() {
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003096 return createCXString(getClangFullVersion());
Ted Kremenek04bb7162010-01-22 22:44:15 +00003097}
3098
3099} // end: extern "C"