blob: ffcaa882bb2d03f3abdf19863ce368e9852d51e3 [file] [log] [blame]
Ted Kremenekd2fa5662009-08-26 22:36:44 +00001//===- CIndex.cpp - Clang-C Source Indexing Library -----------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00007//
Ted Kremenekd2fa5662009-08-26 22:36:44 +00008//===----------------------------------------------------------------------===//
9//
Ted Kremenekab188932010-01-05 19:32:54 +000010// This file implements the main API hooks in the Clang-C Source Indexing
11// library.
Ted Kremenekd2fa5662009-08-26 22:36:44 +000012//
13//===----------------------------------------------------------------------===//
14
Ted Kremenekab188932010-01-05 19:32:54 +000015#include "CIndexer.h"
Ted Kremenek16c440a2010-01-15 20:35:54 +000016#include "CXCursor.h"
Ted Kremeneka297de22010-01-25 22:34:44 +000017#include "CXSourceLocation.h"
Douglas Gregor5352ac02010-01-28 00:27:43 +000018#include "CIndexDiagnostic.h"
Ted Kremenekab188932010-01-05 19:32:54 +000019
Ted Kremenek04bb7162010-01-22 22:44:15 +000020#include "clang/Basic/Version.h"
Douglas Gregor936ea3b2010-01-28 00:56:43 +000021
Steve Naroff50398192009-08-28 15:28:48 +000022#include "clang/AST/DeclVisitor.h"
Steve Narofffb570422009-09-22 19:25:29 +000023#include "clang/AST/StmtVisitor.h"
Douglas Gregor7d0d40e2010-01-21 16:28:34 +000024#include "clang/AST/TypeLocVisitor.h"
Benjamin Kramerb846deb2010-04-12 19:45:50 +000025#include "clang/Basic/Diagnostic.h"
26#include "clang/Frontend/ASTUnit.h"
27#include "clang/Frontend/CompilerInstance.h"
Douglas Gregor936ea3b2010-01-28 00:56:43 +000028#include "clang/Frontend/FrontendDiagnostic.h"
Ted Kremenekd8210652010-01-06 23:43:31 +000029#include "clang/Lex/Lexer.h"
Benjamin Kramerb846deb2010-04-12 19:45:50 +000030#include "clang/Lex/PreprocessingRecord.h"
Douglas Gregor33e9abd2010-01-22 19:49:59 +000031#include "clang/Lex/Preprocessor.h"
Douglas Gregor02465752009-10-16 21:24:31 +000032#include "llvm/Support/MemoryBuffer.h"
Benjamin Kramer0829a832009-10-18 11:19:36 +000033#include "llvm/System/Program.h"
Douglas Gregor0a812cf2010-02-18 23:07:20 +000034#include "llvm/System/Signals.h"
Ted Kremenekfc062212009-10-19 21:44:57 +000035
Benjamin Kramerc2a98162010-03-13 21:22:49 +000036// Needed to define L_TMPNAM on some systems.
37#include <cstdio>
38
Steve Naroff50398192009-08-28 15:28:48 +000039using namespace clang;
Ted Kremenek16c440a2010-01-15 20:35:54 +000040using namespace clang::cxcursor;
Ted Kremenekee4db4f2010-02-17 00:41:08 +000041using namespace clang::cxstring;
Steve Naroff50398192009-08-28 15:28:48 +000042
Ted Kremenek8a8da7d2010-01-06 03:42:32 +000043//===----------------------------------------------------------------------===//
44// Crash Reporting.
45//===----------------------------------------------------------------------===//
46
47#ifdef __APPLE__
Ted Kremenek29b72842010-01-07 22:49:05 +000048#define USE_CRASHTRACER
Ted Kremenek8a8da7d2010-01-06 03:42:32 +000049#include "clang/Analysis/Support/SaveAndRestore.h"
50// Integrate with crash reporter.
51extern "C" const char *__crashreporter_info__;
Ted Kremenek6b569992010-02-17 21:12:23 +000052#define NUM_CRASH_STRINGS 32
Ted Kremenek29b72842010-01-07 22:49:05 +000053static unsigned crashtracer_counter = 0;
Ted Kremenek254ba7c2010-01-07 23:13:53 +000054static unsigned crashtracer_counter_id[NUM_CRASH_STRINGS] = { 0 };
Ted Kremenek29b72842010-01-07 22:49:05 +000055static const char *crashtracer_strings[NUM_CRASH_STRINGS] = { 0 };
56static const char *agg_crashtracer_strings[NUM_CRASH_STRINGS] = { 0 };
57
58static unsigned SetCrashTracerInfo(const char *str,
59 llvm::SmallString<1024> &AggStr) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +000060
Ted Kremenek254ba7c2010-01-07 23:13:53 +000061 unsigned slot = 0;
Ted Kremenek29b72842010-01-07 22:49:05 +000062 while (crashtracer_strings[slot]) {
63 if (++slot == NUM_CRASH_STRINGS)
64 slot = 0;
65 }
66 crashtracer_strings[slot] = str;
Ted Kremenek254ba7c2010-01-07 23:13:53 +000067 crashtracer_counter_id[slot] = ++crashtracer_counter;
Ted Kremenek29b72842010-01-07 22:49:05 +000068
69 // We need to create an aggregate string because multiple threads
70 // may be in this method at one time. The crash reporter string
71 // will attempt to overapproximate the set of in-flight invocations
72 // of this function. Race conditions can still cause this goal
73 // to not be achieved.
74 {
Ted Kremenekf0e23e82010-02-17 00:41:40 +000075 llvm::raw_svector_ostream Out(AggStr);
Ted Kremenek29b72842010-01-07 22:49:05 +000076 for (unsigned i = 0; i < NUM_CRASH_STRINGS; ++i)
77 if (crashtracer_strings[i]) Out << crashtracer_strings[i] << '\n';
78 }
79 __crashreporter_info__ = agg_crashtracer_strings[slot] = AggStr.c_str();
80 return slot;
81}
82
83static void ResetCrashTracerInfo(unsigned slot) {
Ted Kremenek254ba7c2010-01-07 23:13:53 +000084 unsigned max_slot = 0;
85 unsigned max_value = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +000086
Ted Kremenek254ba7c2010-01-07 23:13:53 +000087 crashtracer_strings[slot] = agg_crashtracer_strings[slot] = 0;
88
89 for (unsigned i = 0 ; i < NUM_CRASH_STRINGS; ++i)
90 if (agg_crashtracer_strings[i] &&
91 crashtracer_counter_id[i] > max_value) {
92 max_slot = i;
93 max_value = crashtracer_counter_id[i];
Ted Kremenek29b72842010-01-07 22:49:05 +000094 }
Ted Kremenek254ba7c2010-01-07 23:13:53 +000095
96 __crashreporter_info__ = agg_crashtracer_strings[max_slot];
Ted Kremenek29b72842010-01-07 22:49:05 +000097}
98
99namespace {
100class ArgsCrashTracerInfo {
101 llvm::SmallString<1024> CrashString;
102 llvm::SmallString<1024> AggregateString;
103 unsigned crashtracerSlot;
104public:
105 ArgsCrashTracerInfo(llvm::SmallVectorImpl<const char*> &Args)
106 : crashtracerSlot(0)
107 {
108 {
109 llvm::raw_svector_ostream Out(CrashString);
Ted Kremenek0baa9522010-03-05 22:43:25 +0000110 Out << "ClangCIndex [" << getClangFullVersion() << "]"
111 << "[createTranslationUnitFromSourceFile]: clang";
Ted Kremenek29b72842010-01-07 22:49:05 +0000112 for (llvm::SmallVectorImpl<const char*>::iterator I=Args.begin(),
113 E=Args.end(); I!=E; ++I)
114 Out << ' ' << *I;
115 }
116 crashtracerSlot = SetCrashTracerInfo(CrashString.c_str(),
117 AggregateString);
118 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000119
Ted Kremenek29b72842010-01-07 22:49:05 +0000120 ~ArgsCrashTracerInfo() {
121 ResetCrashTracerInfo(crashtracerSlot);
122 }
123};
124}
125#endif
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000126
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000127/// \brief The result of comparing two source ranges.
128enum RangeComparisonResult {
129 /// \brief Either the ranges overlap or one of the ranges is invalid.
130 RangeOverlap,
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000131
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000132 /// \brief The first range ends before the second range starts.
133 RangeBefore,
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000134
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000135 /// \brief The first range starts after the second range ends.
136 RangeAfter
137};
138
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000139/// \brief Compare two source ranges to determine their relative position in
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000140/// the translation unit.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000141static RangeComparisonResult RangeCompare(SourceManager &SM,
142 SourceRange R1,
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000143 SourceRange R2) {
144 assert(R1.isValid() && "First range is invalid?");
145 assert(R2.isValid() && "Second range is invalid?");
Daniel Dunbard52864b2010-02-14 10:02:57 +0000146 if (R1.getEnd() == R2.getBegin() ||
147 SM.isBeforeInTranslationUnit(R1.getEnd(), R2.getBegin()))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000148 return RangeBefore;
Daniel Dunbard52864b2010-02-14 10:02:57 +0000149 if (R2.getEnd() == R1.getBegin() ||
150 SM.isBeforeInTranslationUnit(R2.getEnd(), R1.getBegin()))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000151 return RangeAfter;
152 return RangeOverlap;
153}
154
Ted Kremenekfbd84ca2010-05-05 00:55:23 +0000155/// \brief Determine if a source location falls within, before, or after a
156/// a given source range.
157static RangeComparisonResult LocationCompare(SourceManager &SM,
158 SourceLocation L, SourceRange R) {
159 assert(R.isValid() && "First range is invalid?");
160 assert(L.isValid() && "Second range is invalid?");
161 if (L == R.getBegin())
162 return RangeOverlap;
163 if (L == R.getEnd())
164 return RangeAfter;
165 if (SM.isBeforeInTranslationUnit(L, R.getBegin()))
166 return RangeBefore;
167 if (SM.isBeforeInTranslationUnit(R.getEnd(), L))
168 return RangeAfter;
169 return RangeOverlap;
170}
171
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000172/// \brief Translate a Clang source range into a CIndex source range.
173///
174/// Clang internally represents ranges where the end location points to the
175/// start of the token at the end. However, for external clients it is more
176/// useful to have a CXSourceRange be a proper half-open interval. This routine
177/// does the appropriate translation.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000178CXSourceRange cxloc::translateSourceRange(const SourceManager &SM,
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000179 const LangOptions &LangOpts,
180 SourceRange 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();
Douglas Gregor6a5a23f2010-03-19 21:51:54 +0000185 if (!EndLoc.isInvalid() && EndLoc.isFileID()) {
186 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);
300 bool VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
301 bool VisitObjCImplDecl(ObjCImplDecl *D);
302 bool VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
303 bool VisitObjCImplementationDecl(ObjCImplementationDecl *D);
304 // FIXME: ObjCPropertyDecl requires TypeSourceInfo, getter/setter locations,
305 // etc.
306 // FIXME: ObjCCompatibleAliasDecl requires aliased-class locations.
307 bool VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D);
308 bool VisitObjCClassDecl(ObjCClassDecl *D);
Ted Kremeneka0536d82010-05-07 01:04:29 +0000309 bool VisitLinkageSpecDecl(LinkageSpecDecl *D);
Ted Kremenek8f06e0e2010-05-06 23:38:21 +0000310 bool VisitNamespaceDecl(NamespaceDecl *D);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000311
312 // Type visitors
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000313 // FIXME: QualifiedTypeLoc doesn't provide any location information
314 bool VisitBuiltinTypeLoc(BuiltinTypeLoc TL);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000315 bool VisitTypedefTypeLoc(TypedefTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000316 bool VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL);
317 bool VisitTagTypeLoc(TagTypeLoc TL);
318 // FIXME: TemplateTypeParmTypeLoc doesn't provide any location information
319 bool VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL);
320 bool VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL);
321 bool VisitPointerTypeLoc(PointerTypeLoc TL);
322 bool VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL);
323 bool VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL);
324 bool VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL);
325 bool VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL);
326 bool VisitFunctionTypeLoc(FunctionTypeLoc TL);
327 bool VisitArrayTypeLoc(ArrayTypeLoc TL);
Douglas Gregor2332c112010-01-21 20:48:56 +0000328 // FIXME: Implement for TemplateSpecializationTypeLoc
329 // FIXME: Implement visitors here when the unimplemented TypeLocs get
330 // implemented
331 bool VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL);
332 bool VisitTypeOfTypeLoc(TypeOfTypeLoc TL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000333
Douglas Gregora59e3902010-01-21 23:27:09 +0000334 // Statement visitors
335 bool VisitStmt(Stmt *S);
336 bool VisitDeclStmt(DeclStmt *S);
Douglas Gregorf5bab412010-01-22 01:00:11 +0000337 // FIXME: LabelStmt label?
338 bool VisitIfStmt(IfStmt *S);
339 bool VisitSwitchStmt(SwitchStmt *S);
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000340 bool VisitCaseStmt(CaseStmt *S);
Douglas Gregor263b47b2010-01-25 16:12:32 +0000341 bool VisitWhileStmt(WhileStmt *S);
342 bool VisitForStmt(ForStmt *S);
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000343// bool VisitSwitchCase(SwitchCase *S);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000344
Douglas Gregor336fd812010-01-23 00:40:08 +0000345 // Expression visitors
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000346 bool VisitBlockExpr(BlockExpr *B);
Douglas Gregor336fd812010-01-23 00:40:08 +0000347 bool VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000348 bool VisitExplicitCastExpr(ExplicitCastExpr *E);
Douglas Gregorc2350e52010-03-08 16:40:19 +0000349 bool VisitObjCMessageExpr(ObjCMessageExpr *E);
Douglas Gregor81d34662010-04-20 15:39:42 +0000350 bool VisitObjCEncodeExpr(ObjCEncodeExpr *E);
Douglas Gregor8ecdb652010-04-28 22:16:22 +0000351 bool VisitOffsetOfExpr(OffsetOfExpr *E);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000352 bool VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E);
Steve Naroff89922f82009-08-31 00:59:03 +0000353};
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000354
Ted Kremenekab188932010-01-05 19:32:54 +0000355} // end anonymous namespace
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000356
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000357RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000358 return RangeCompare(TU->getSourceManager(), R, RegionOfInterest);
359}
360
Douglas Gregorb1373d02010-01-20 20:59:29 +0000361/// \brief Visit the given cursor and, if requested by the visitor,
362/// its children.
363///
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000364/// \param Cursor the cursor to visit.
365///
366/// \param CheckRegionOfInterest if true, then the caller already checked that
367/// this cursor is within the region of interest.
368///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000369/// \returns true if the visitation should be aborted, false if it
370/// should continue.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000371bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
Douglas Gregorb1373d02010-01-20 20:59:29 +0000372 if (clang_isInvalid(Cursor.kind))
373 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000374
Douglas Gregorb1373d02010-01-20 20:59:29 +0000375 if (clang_isDeclaration(Cursor.kind)) {
376 Decl *D = getCursorDecl(Cursor);
377 assert(D && "Invalid declaration cursor");
378 if (D->getPCHLevel() > MaxPCHLevel)
379 return false;
380
381 if (D->isImplicit())
382 return false;
383 }
384
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000385 // If we have a range of interest, and this cursor doesn't intersect with it,
386 // we're done.
387 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
Daniel Dunbarf408f322010-02-14 08:32:05 +0000388 SourceRange Range =
389 cxloc::translateCXSourceRange(clang_getCursorExtent(Cursor));
390 if (Range.isInvalid() || CompareRegionOfInterest(Range))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000391 return false;
392 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000393
Douglas Gregorb1373d02010-01-20 20:59:29 +0000394 switch (Visitor(Cursor, Parent, ClientData)) {
395 case CXChildVisit_Break:
396 return true;
397
398 case CXChildVisit_Continue:
399 return false;
400
401 case CXChildVisit_Recurse:
402 return VisitChildren(Cursor);
403 }
404
Douglas Gregorfd643772010-01-25 16:45:46 +0000405 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000406}
407
Douglas Gregor788f5a12010-03-20 00:41:21 +0000408std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
409CursorVisitor::getPreprocessedEntities() {
410 PreprocessingRecord &PPRec
411 = *TU->getPreprocessor().getPreprocessingRecord();
412
413 bool OnlyLocalDecls
414 = !TU->isMainFileAST() && TU->getOnlyLocalDecls();
415
416 // There is no region of interest; we have to walk everything.
417 if (RegionOfInterest.isInvalid())
418 return std::make_pair(PPRec.begin(OnlyLocalDecls),
419 PPRec.end(OnlyLocalDecls));
420
421 // Find the file in which the region of interest lands.
422 SourceManager &SM = TU->getSourceManager();
423 std::pair<FileID, unsigned> Begin
424 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getBegin());
425 std::pair<FileID, unsigned> End
426 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getEnd());
427
428 // The region of interest spans files; we have to walk everything.
429 if (Begin.first != End.first)
430 return std::make_pair(PPRec.begin(OnlyLocalDecls),
431 PPRec.end(OnlyLocalDecls));
432
433 ASTUnit::PreprocessedEntitiesByFileMap &ByFileMap
434 = TU->getPreprocessedEntitiesByFile();
435 if (ByFileMap.empty()) {
436 // Build the mapping from files to sets of preprocessed entities.
437 for (PreprocessingRecord::iterator E = PPRec.begin(OnlyLocalDecls),
438 EEnd = PPRec.end(OnlyLocalDecls);
439 E != EEnd; ++E) {
440 std::pair<FileID, unsigned> P
441 = SM.getDecomposedInstantiationLoc((*E)->getSourceRange().getBegin());
442 ByFileMap[P.first].push_back(*E);
443 }
444 }
445
446 return std::make_pair(ByFileMap[Begin.first].begin(),
447 ByFileMap[Begin.first].end());
448}
449
Douglas Gregorb1373d02010-01-20 20:59:29 +0000450/// \brief Visit the children of the given cursor.
451///
452/// \returns true if the visitation should be aborted, false if it
453/// should continue.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000454bool CursorVisitor::VisitChildren(CXCursor Cursor) {
Douglas Gregora59e3902010-01-21 23:27:09 +0000455 if (clang_isReference(Cursor.kind)) {
456 // By definition, references have no children.
457 return false;
458 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000459
460 // Set the Parent field to Cursor, then back to its old value once we're
Douglas Gregorb1373d02010-01-20 20:59:29 +0000461 // done.
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000462 SetParentRAII SetParent(Parent, StmtParent, Cursor);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000463
Douglas Gregorb1373d02010-01-20 20:59:29 +0000464 if (clang_isDeclaration(Cursor.kind)) {
465 Decl *D = getCursorDecl(Cursor);
466 assert(D && "Invalid declaration cursor");
Ted Kremenek539311e2010-02-18 18:47:01 +0000467 return VisitAttributes(D) || Visit(D);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000468 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000469
Douglas Gregora59e3902010-01-21 23:27:09 +0000470 if (clang_isStatement(Cursor.kind))
471 return Visit(getCursorStmt(Cursor));
472 if (clang_isExpression(Cursor.kind))
473 return Visit(getCursorExpr(Cursor));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000474
Douglas Gregorb1373d02010-01-20 20:59:29 +0000475 if (clang_isTranslationUnit(Cursor.kind)) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000476 ASTUnit *CXXUnit = getCursorASTUnit(Cursor);
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000477 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
478 RegionOfInterest.isInvalid()) {
Douglas Gregor7b691f332010-01-20 21:13:59 +0000479 const std::vector<Decl*> &TLDs = CXXUnit->getTopLevelDecls();
480 for (std::vector<Decl*>::const_iterator it = TLDs.begin(),
481 ie = TLDs.end(); it != ie; ++it) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000482 if (Visit(MakeCXCursor(*it, CXXUnit), true))
Douglas Gregor7b691f332010-01-20 21:13:59 +0000483 return true;
484 }
Douglas Gregor0396f462010-03-19 05:22:59 +0000485 } else if (VisitDeclContext(
486 CXXUnit->getASTContext().getTranslationUnitDecl()))
487 return true;
Bob Wilson3178cb62010-03-19 03:57:57 +0000488
Douglas Gregor0396f462010-03-19 05:22:59 +0000489 // Walk the preprocessing record.
Daniel Dunbar8de30ff2010-03-20 01:11:56 +0000490 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000491 // FIXME: Once we have the ability to deserialize a preprocessing record,
492 // do so.
Douglas Gregor788f5a12010-03-20 00:41:21 +0000493 PreprocessingRecord::iterator E, EEnd;
494 for (llvm::tie(E, EEnd) = getPreprocessedEntities(); E != EEnd; ++E) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000495 if (MacroInstantiation *MI = dyn_cast<MacroInstantiation>(*E)) {
496 if (Visit(MakeMacroInstantiationCursor(MI, CXXUnit)))
497 return true;
Douglas Gregor788f5a12010-03-20 00:41:21 +0000498
Douglas Gregor0396f462010-03-19 05:22:59 +0000499 continue;
500 }
501
502 if (MacroDefinition *MD = dyn_cast<MacroDefinition>(*E)) {
503 if (Visit(MakeMacroDefinitionCursor(MD, CXXUnit)))
504 return true;
505
506 continue;
507 }
508 }
509 }
Douglas Gregor7b691f332010-01-20 21:13:59 +0000510 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000511 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000512
Douglas Gregorb1373d02010-01-20 20:59:29 +0000513 // Nothing to visit at the moment.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000514 return false;
515}
516
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000517bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
518 for (BlockDecl::param_iterator I=B->param_begin(), E=B->param_end(); I!=E;++I)
519 if (Decl *D = *I)
520 if (Visit(D))
521 return true;
522
523 return Visit(MakeCXCursor(B->getBody(), StmtParent, TU));
524}
525
Douglas Gregorb1373d02010-01-20 20:59:29 +0000526bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000527 for (DeclContext::decl_iterator
Douglas Gregorb1373d02010-01-20 20:59:29 +0000528 I = DC->decls_begin(), E = DC->decls_end(); I != E; ++I) {
Ted Kremenek09dfa372010-02-18 05:46:33 +0000529
Daniel Dunbard52864b2010-02-14 10:02:57 +0000530 CXCursor Cursor = MakeCXCursor(*I, TU);
531
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000532 if (RegionOfInterest.isValid()) {
Daniel Dunbard52864b2010-02-14 10:02:57 +0000533 SourceRange Range =
534 cxloc::translateCXSourceRange(clang_getCursorExtent(Cursor));
535 if (Range.isInvalid())
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000536 continue;
Daniel Dunbard52864b2010-02-14 10:02:57 +0000537
538 switch (CompareRegionOfInterest(Range)) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000539 case RangeBefore:
540 // This declaration comes before the region of interest; skip it.
541 continue;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000542
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000543 case RangeAfter:
544 // This declaration comes after the region of interest; we're done.
545 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000546
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000547 case RangeOverlap:
548 // This declaration overlaps the region of interest; visit it.
549 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000550 }
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000551 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000552
Daniel Dunbard52864b2010-02-14 10:02:57 +0000553 if (Visit(Cursor, true))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000554 return true;
555 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000556
Douglas Gregorb1373d02010-01-20 20:59:29 +0000557 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000558}
559
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000560bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
561 llvm_unreachable("Translation units are visited directly by Visit()");
562 return false;
563}
564
565bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
566 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
567 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000568
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000569 return false;
570}
571
572bool CursorVisitor::VisitTagDecl(TagDecl *D) {
573 return VisitDeclContext(D);
574}
575
576bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
577 if (Expr *Init = D->getInitExpr())
578 return Visit(MakeCXCursor(Init, StmtParent, TU));
579 return false;
580}
581
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000582bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
583 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
584 if (Visit(TSInfo->getTypeLoc()))
585 return true;
586
587 return false;
588}
589
Douglas Gregorb1373d02010-01-20 20:59:29 +0000590bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000591 if (VisitDeclaratorDecl(ND))
592 return true;
593
Douglas Gregora59e3902010-01-21 23:27:09 +0000594 if (ND->isThisDeclarationADefinition() &&
595 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
596 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000597
Douglas Gregorb1373d02010-01-20 20:59:29 +0000598 return false;
599}
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000600
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000601bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
602 if (VisitDeclaratorDecl(D))
603 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000604
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000605 if (Expr *BitWidth = D->getBitWidth())
606 return Visit(MakeCXCursor(BitWidth, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000607
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000608 return false;
609}
610
611bool CursorVisitor::VisitVarDecl(VarDecl *D) {
612 if (VisitDeclaratorDecl(D))
613 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000614
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000615 if (Expr *Init = D->getInit())
616 return Visit(MakeCXCursor(Init, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000617
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000618 return false;
619}
620
621bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
Douglas Gregor4bc1cb62010-03-08 14:59:44 +0000622 if (TypeSourceInfo *TSInfo = ND->getResultTypeSourceInfo())
623 if (Visit(TSInfo->getTypeLoc()))
624 return true;
625
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000626 for (ObjCMethodDecl::param_iterator P = ND->param_begin(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000627 PEnd = ND->param_end();
628 P != PEnd; ++P) {
629 if (Visit(MakeCXCursor(*P, TU)))
630 return true;
631 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000632
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000633 if (ND->isThisDeclarationADefinition() &&
634 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
635 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000636
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000637 return false;
638}
639
Douglas Gregora59e3902010-01-21 23:27:09 +0000640bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
641 return VisitDeclContext(D);
642}
643
Douglas Gregorb1373d02010-01-20 20:59:29 +0000644bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000645 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
646 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000647 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000648
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000649 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
650 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
651 E = ND->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000652 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000653 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000654
Douglas Gregora59e3902010-01-21 23:27:09 +0000655 return VisitObjCContainerDecl(ND);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000656}
657
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000658bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
659 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
660 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
661 E = PID->protocol_end(); I != E; ++I, ++PL)
662 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
663 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000664
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000665 return VisitObjCContainerDecl(PID);
666}
667
Douglas Gregorb1373d02010-01-20 20:59:29 +0000668bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000669 // Issue callbacks for super class.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000670 if (D->getSuperClass() &&
671 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000672 D->getSuperClassLoc(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000673 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000674 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000675
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000676 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
677 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
678 E = D->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000679 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000680 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000681
Douglas Gregora59e3902010-01-21 23:27:09 +0000682 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000683}
684
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000685bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
686 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000687}
688
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000689bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
Ted Kremenekebfa3392010-03-19 20:39:03 +0000690 // 'ID' could be null when dealing with invalid code.
691 if (ObjCInterfaceDecl *ID = D->getClassInterface())
692 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
693 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000694
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000695 return VisitObjCImplDecl(D);
696}
697
698bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
699#if 0
700 // Issue callbacks for super class.
701 // FIXME: No source location information!
702 if (D->getSuperClass() &&
703 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000704 D->getSuperClassLoc(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000705 TU)))
706 return true;
707#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000708
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000709 return VisitObjCImplDecl(D);
710}
711
712bool CursorVisitor::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D) {
713 ObjCForwardProtocolDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
714 for (ObjCForwardProtocolDecl::protocol_iterator I = D->protocol_begin(),
715 E = D->protocol_end();
716 I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000717 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000718 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000719
720 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000721}
722
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000723bool CursorVisitor::VisitObjCClassDecl(ObjCClassDecl *D) {
724 for (ObjCClassDecl::iterator C = D->begin(), CEnd = D->end(); C != CEnd; ++C)
725 if (Visit(MakeCursorObjCClassRef(C->getInterface(), C->getLocation(), TU)))
726 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000727
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000728 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000729}
730
Ted Kremenek8f06e0e2010-05-06 23:38:21 +0000731bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
732 return VisitDeclContext(D);
733}
734
Ted Kremeneka0536d82010-05-07 01:04:29 +0000735bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
736 return VisitDeclContext(D);
737}
738
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000739bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
740 ASTContext &Context = TU->getASTContext();
741
742 // Some builtin types (such as Objective-C's "id", "sel", and
743 // "Class") have associated declarations. Create cursors for those.
744 QualType VisitType;
745 switch (TL.getType()->getAs<BuiltinType>()->getKind()) {
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000746 case BuiltinType::Void:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000747 case BuiltinType::Bool:
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000748 case BuiltinType::Char_U:
749 case BuiltinType::UChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000750 case BuiltinType::Char16:
751 case BuiltinType::Char32:
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000752 case BuiltinType::UShort:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000753 case BuiltinType::UInt:
754 case BuiltinType::ULong:
755 case BuiltinType::ULongLong:
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000756 case BuiltinType::UInt128:
757 case BuiltinType::Char_S:
758 case BuiltinType::SChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000759 case BuiltinType::WChar:
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000760 case BuiltinType::Short:
761 case BuiltinType::Int:
762 case BuiltinType::Long:
763 case BuiltinType::LongLong:
764 case BuiltinType::Int128:
765 case BuiltinType::Float:
766 case BuiltinType::Double:
767 case BuiltinType::LongDouble:
768 case BuiltinType::NullPtr:
769 case BuiltinType::Overload:
770 case BuiltinType::Dependent:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000771 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000772
773 case BuiltinType::UndeducedAuto: // FIXME: Deserves a cursor?
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000774 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000775
Ted Kremenekc4174cc2010-02-18 18:52:18 +0000776 case BuiltinType::ObjCId:
777 VisitType = Context.getObjCIdType();
778 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000779
780 case BuiltinType::ObjCClass:
781 VisitType = Context.getObjCClassType();
782 break;
783
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000784 case BuiltinType::ObjCSel:
785 VisitType = Context.getObjCSelType();
786 break;
787 }
788
789 if (!VisitType.isNull()) {
790 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000791 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000792 TU));
793 }
794
795 return false;
796}
797
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000798bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
799 return Visit(MakeCursorTypeRef(TL.getTypedefDecl(), TL.getNameLoc(), TU));
800}
801
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000802bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
803 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
804}
805
806bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
807 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
808}
809
810bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
811 if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
812 return true;
813
814 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
815 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
816 TU)))
817 return true;
818 }
819
820 return false;
821}
822
823bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
824 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseTypeLoc()))
825 return true;
826
827 if (TL.hasProtocolsAsWritten()) {
828 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000829 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I),
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000830 TL.getProtocolLoc(I),
831 TU)))
832 return true;
833 }
834 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000835
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000836 return false;
837}
838
839bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
840 return Visit(TL.getPointeeLoc());
841}
842
843bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
844 return Visit(TL.getPointeeLoc());
845}
846
847bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
848 return Visit(TL.getPointeeLoc());
849}
850
851bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000852 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000853}
854
855bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000856 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000857}
858
859bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
860 if (Visit(TL.getResultLoc()))
861 return true;
862
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000863 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
Ted Kremenek5dbacb42010-04-07 00:27:13 +0000864 if (Decl *D = TL.getArg(I))
865 if (Visit(MakeCXCursor(D, TU)))
866 return true;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000867
868 return false;
869}
870
871bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
872 if (Visit(TL.getElementLoc()))
873 return true;
874
875 if (Expr *Size = TL.getSizeExpr())
876 return Visit(MakeCXCursor(Size, StmtParent, TU));
877
878 return false;
879}
880
Douglas Gregor2332c112010-01-21 20:48:56 +0000881bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
882 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
883}
884
885bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
886 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
887 return Visit(TSInfo->getTypeLoc());
888
889 return false;
890}
891
Douglas Gregora59e3902010-01-21 23:27:09 +0000892bool CursorVisitor::VisitStmt(Stmt *S) {
893 for (Stmt::child_iterator Child = S->child_begin(), ChildEnd = S->child_end();
894 Child != ChildEnd; ++Child) {
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000895 if (Stmt *C = *Child)
896 if (Visit(MakeCXCursor(C, StmtParent, TU)))
897 return true;
Douglas Gregora59e3902010-01-21 23:27:09 +0000898 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000899
Douglas Gregora59e3902010-01-21 23:27:09 +0000900 return false;
901}
902
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000903bool CursorVisitor::VisitCaseStmt(CaseStmt *S) {
904 // Specially handle CaseStmts because they can be nested, e.g.:
905 //
906 // case 1:
907 // case 2:
908 //
909 // In this case the second CaseStmt is the child of the first. Walking
910 // these recursively can blow out the stack.
911 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU);
912 while (true) {
913 // Set the Parent field to Cursor, then back to its old value once we're
914 // done.
915 SetParentRAII SetParent(Parent, StmtParent, Cursor);
916
917 if (Stmt *LHS = S->getLHS())
918 if (Visit(MakeCXCursor(LHS, StmtParent, TU)))
919 return true;
920 if (Stmt *RHS = S->getRHS())
921 if (Visit(MakeCXCursor(RHS, StmtParent, TU)))
922 return true;
923 if (Stmt *SubStmt = S->getSubStmt()) {
924 if (!isa<CaseStmt>(SubStmt))
925 return Visit(MakeCXCursor(SubStmt, StmtParent, TU));
926
927 // Specially handle 'CaseStmt' so that we don't blow out the stack.
928 CaseStmt *CS = cast<CaseStmt>(SubStmt);
929 Cursor = MakeCXCursor(CS, StmtParent, TU);
930 if (RegionOfInterest.isValid()) {
931 SourceRange Range = CS->getSourceRange();
932 if (Range.isInvalid() || CompareRegionOfInterest(Range))
933 return false;
934 }
935
936 switch (Visitor(Cursor, Parent, ClientData)) {
937 case CXChildVisit_Break: return true;
938 case CXChildVisit_Continue: return false;
939 case CXChildVisit_Recurse:
940 // Perform tail-recursion manually.
941 S = CS;
942 continue;
943 }
944 }
945 return false;
946 }
947}
948
Douglas Gregora59e3902010-01-21 23:27:09 +0000949bool CursorVisitor::VisitDeclStmt(DeclStmt *S) {
950 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
951 D != DEnd; ++D) {
Douglas Gregor263b47b2010-01-25 16:12:32 +0000952 if (*D && Visit(MakeCXCursor(*D, TU)))
Douglas Gregora59e3902010-01-21 23:27:09 +0000953 return true;
954 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000955
Douglas Gregora59e3902010-01-21 23:27:09 +0000956 return false;
957}
958
Douglas Gregorf5bab412010-01-22 01:00:11 +0000959bool CursorVisitor::VisitIfStmt(IfStmt *S) {
960 if (VarDecl *Var = S->getConditionVariable()) {
961 if (Visit(MakeCXCursor(Var, TU)))
962 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000963 }
964
Douglas Gregor263b47b2010-01-25 16:12:32 +0000965 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
966 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +0000967 if (S->getThen() && Visit(MakeCXCursor(S->getThen(), StmtParent, TU)))
968 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +0000969 if (S->getElse() && Visit(MakeCXCursor(S->getElse(), StmtParent, TU)))
970 return true;
971
972 return false;
973}
974
975bool CursorVisitor::VisitSwitchStmt(SwitchStmt *S) {
976 if (VarDecl *Var = S->getConditionVariable()) {
977 if (Visit(MakeCXCursor(Var, TU)))
978 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000979 }
980
Douglas Gregor263b47b2010-01-25 16:12:32 +0000981 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
982 return true;
983 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
984 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000985
Douglas Gregor263b47b2010-01-25 16:12:32 +0000986 return false;
987}
988
989bool CursorVisitor::VisitWhileStmt(WhileStmt *S) {
990 if (VarDecl *Var = S->getConditionVariable()) {
991 if (Visit(MakeCXCursor(Var, TU)))
992 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000993 }
994
Douglas Gregor263b47b2010-01-25 16:12:32 +0000995 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
996 return true;
997 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
Douglas Gregorf5bab412010-01-22 01:00:11 +0000998 return true;
999
Douglas Gregor263b47b2010-01-25 16:12:32 +00001000 return false;
1001}
1002
1003bool CursorVisitor::VisitForStmt(ForStmt *S) {
1004 if (S->getInit() && Visit(MakeCXCursor(S->getInit(), StmtParent, TU)))
1005 return true;
1006 if (VarDecl *Var = S->getConditionVariable()) {
1007 if (Visit(MakeCXCursor(Var, TU)))
1008 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001009 }
1010
Douglas Gregor263b47b2010-01-25 16:12:32 +00001011 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1012 return true;
1013 if (S->getInc() && Visit(MakeCXCursor(S->getInc(), StmtParent, TU)))
1014 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +00001015 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
1016 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001017
Douglas Gregorf5bab412010-01-22 01:00:11 +00001018 return false;
1019}
1020
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00001021bool CursorVisitor::VisitBlockExpr(BlockExpr *B) {
1022 return Visit(B->getBlockDecl());
1023}
1024
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001025bool CursorVisitor::VisitOffsetOfExpr(OffsetOfExpr *E) {
1026 // FIXME: Visit fields as well?
1027 if (Visit(E->getTypeSourceInfo()->getTypeLoc()))
1028 return true;
1029
1030 return VisitExpr(E);
1031}
1032
Douglas Gregor336fd812010-01-23 00:40:08 +00001033bool CursorVisitor::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E) {
1034 if (E->isArgumentType()) {
1035 if (TypeSourceInfo *TSInfo = E->getArgumentTypeInfo())
1036 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001037
Douglas Gregor336fd812010-01-23 00:40:08 +00001038 return false;
1039 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001040
Douglas Gregor336fd812010-01-23 00:40:08 +00001041 return VisitExpr(E);
1042}
1043
1044bool CursorVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
1045 if (TypeSourceInfo *TSInfo = E->getTypeInfoAsWritten())
1046 if (Visit(TSInfo->getTypeLoc()))
1047 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001048
Douglas Gregor336fd812010-01-23 00:40:08 +00001049 return VisitCastExpr(E);
1050}
1051
1052bool CursorVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
1053 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
1054 if (Visit(TSInfo->getTypeLoc()))
1055 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001056
Douglas Gregor336fd812010-01-23 00:40:08 +00001057 return VisitExpr(E);
1058}
1059
Douglas Gregorc2350e52010-03-08 16:40:19 +00001060bool CursorVisitor::VisitObjCMessageExpr(ObjCMessageExpr *E) {
Douglas Gregor04badcf2010-04-21 00:45:42 +00001061 if (TypeSourceInfo *TSInfo = E->getClassReceiverTypeInfo())
1062 if (Visit(TSInfo->getTypeLoc()))
1063 return true;
Douglas Gregorc2350e52010-03-08 16:40:19 +00001064
1065 return VisitExpr(E);
1066}
1067
Douglas Gregor81d34662010-04-20 15:39:42 +00001068bool CursorVisitor::VisitObjCEncodeExpr(ObjCEncodeExpr *E) {
1069 return Visit(E->getEncodedTypeSourceInfo()->getTypeLoc());
1070}
1071
1072
Ted Kremenek09dfa372010-02-18 05:46:33 +00001073bool CursorVisitor::VisitAttributes(Decl *D) {
1074 for (const Attr *A = D->getAttrs(); A; A = A->getNext())
1075 if (Visit(MakeCXCursor(A, D, TU)))
1076 return true;
1077
1078 return false;
1079}
1080
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00001081extern "C" {
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001082CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
1083 int displayDiagnostics) {
Douglas Gregora030b7c2010-01-22 20:35:53 +00001084 CIndexer *CIdxr = new CIndexer();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001085 if (excludeDeclarationsFromPCH)
1086 CIdxr->setOnlyLocalDecls();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001087 if (displayDiagnostics)
1088 CIdxr->setDisplayDiagnostics();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001089 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +00001090}
1091
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001092void clang_disposeIndex(CXIndex CIdx) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001093 if (CIdx)
1094 delete static_cast<CIndexer *>(CIdx);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00001095}
1096
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001097void clang_setUseExternalASTGeneration(CXIndex CIdx, int value) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001098 if (CIdx) {
1099 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
1100 CXXIdx->setUseExternalASTGeneration(value);
1101 }
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001102}
1103
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001104CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
Douglas Gregora88084b2010-02-18 18:08:43 +00001105 const char *ast_filename) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001106 if (!CIdx)
1107 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001108
Douglas Gregor7d1d49d2009-10-16 20:01:17 +00001109 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001110
Douglas Gregor28019772010-04-05 23:52:57 +00001111 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
1112 return ASTUnit::LoadFromPCHFile(ast_filename, Diags,
Douglas Gregora88084b2010-02-18 18:08:43 +00001113 CXXIdx->getOnlyLocalDecls(),
1114 0, 0, true);
Steve Naroff600866c2009-08-27 19:51:58 +00001115}
1116
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001117CXTranslationUnit
1118clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
1119 const char *source_filename,
1120 int num_command_line_args,
Douglas Gregor4db64a42010-01-23 00:14:00 +00001121 const char **command_line_args,
1122 unsigned num_unsaved_files,
Douglas Gregora88084b2010-02-18 18:08:43 +00001123 struct CXUnsavedFile *unsaved_files) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001124 if (!CIdx)
1125 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001126
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001127 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
1128
Douglas Gregor5352ac02010-01-28 00:27:43 +00001129 // Configure the diagnostics.
1130 DiagnosticOptions DiagOpts;
Douglas Gregor28019772010-04-05 23:52:57 +00001131 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
1132 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001133
Douglas Gregor4db64a42010-01-23 00:14:00 +00001134 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
1135 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattnera0a270c2010-04-05 22:42:27 +00001136 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001137 const llvm::MemoryBuffer *Buffer
Chris Lattnera0a270c2010-04-05 22:42:27 +00001138 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregor4db64a42010-01-23 00:14:00 +00001139 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
1140 Buffer));
1141 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001142
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001143 if (!CXXIdx->getUseExternalASTGeneration()) {
1144 llvm::SmallVector<const char *, 16> Args;
1145
1146 // The 'source_filename' argument is optional. If the caller does not
1147 // specify it then it is assumed that the source file is specified
1148 // in the actual argument list.
1149 if (source_filename)
1150 Args.push_back(source_filename);
1151 Args.insert(Args.end(), command_line_args,
1152 command_line_args + num_command_line_args);
Douglas Gregor94dc8f62010-03-19 16:15:56 +00001153 Args.push_back("-Xclang");
1154 Args.push_back("-detailed-preprocessing-record");
Douglas Gregor5352ac02010-01-28 00:27:43 +00001155 unsigned NumErrors = Diags->getNumErrors();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001156
Ted Kremenek29b72842010-01-07 22:49:05 +00001157#ifdef USE_CRASHTRACER
1158 ArgsCrashTracerInfo ACTI(Args);
Ted Kremenek8a8da7d2010-01-06 03:42:32 +00001159#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001160
Daniel Dunbar94220972009-12-05 02:17:18 +00001161 llvm::OwningPtr<ASTUnit> Unit(
1162 ASTUnit::LoadFromCommandLine(Args.data(), Args.data() + Args.size(),
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001163 Diags,
Daniel Dunbar869824e2009-12-13 03:46:13 +00001164 CXXIdx->getClangResourcesPath(),
Daniel Dunbar94220972009-12-05 02:17:18 +00001165 CXXIdx->getOnlyLocalDecls(),
Douglas Gregor4db64a42010-01-23 00:14:00 +00001166 RemappedFiles.data(),
Douglas Gregora88084b2010-02-18 18:08:43 +00001167 RemappedFiles.size(),
Douglas Gregor94dc8f62010-03-19 16:15:56 +00001168 /*CaptureDiagnostics=*/true));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001169
Daniel Dunbar94220972009-12-05 02:17:18 +00001170 // FIXME: Until we have broader testing, just drop the entire AST if we
1171 // encountered an error.
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001172 if (NumErrors != Diags->getNumErrors()) {
Ted Kremenek34f6a322010-03-05 22:43:29 +00001173 // Make sure to check that 'Unit' is non-NULL.
1174 if (CXXIdx->getDisplayDiagnostics() && Unit.get()) {
Douglas Gregor405634b2010-04-05 18:10:21 +00001175 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
1176 DEnd = Unit->stored_diag_end();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001177 D != DEnd; ++D) {
1178 CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOptions());
Douglas Gregor274f1902010-02-22 23:17:23 +00001179 CXString Msg = clang_formatDiagnostic(&Diag,
1180 clang_defaultDiagnosticDisplayOptions());
1181 fprintf(stderr, "%s\n", clang_getCString(Msg));
1182 clang_disposeString(Msg);
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001183 }
Douglas Gregor274f1902010-02-22 23:17:23 +00001184#ifdef LLVM_ON_WIN32
1185 // On Windows, force a flush, since there may be multiple copies of
1186 // stderr and stdout in the file system, all with different buffers
1187 // but writing to the same device.
1188 fflush(stderr);
Ted Kremenek83c51842010-03-26 01:34:51 +00001189#endif
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001190 }
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001191 }
Daniel Dunbar94220972009-12-05 02:17:18 +00001192
1193 return Unit.take();
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001194 }
1195
Ted Kremenek139ba862009-10-22 00:03:57 +00001196 // Build up the arguments for invoking 'clang'.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001197 std::vector<const char *> argv;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001198
Ted Kremenek139ba862009-10-22 00:03:57 +00001199 // First add the complete path to the 'clang' executable.
1200 llvm::sys::Path ClangPath = static_cast<CIndexer *>(CIdx)->getClangPath();
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00001201 argv.push_back(ClangPath.c_str());
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001202
Ted Kremenek139ba862009-10-22 00:03:57 +00001203 // Add the '-emit-ast' option as our execution mode for 'clang'.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001204 argv.push_back("-emit-ast");
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001205
Ted Kremenek139ba862009-10-22 00:03:57 +00001206 // The 'source_filename' argument is optional. If the caller does not
1207 // specify it then it is assumed that the source file is specified
1208 // in the actual argument list.
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001209 if (source_filename)
1210 argv.push_back(source_filename);
Ted Kremenek139ba862009-10-22 00:03:57 +00001211
Steve Naroff37b5ac22009-10-15 20:50:09 +00001212 // Generate a temporary name for the AST file.
Ted Kremenek139ba862009-10-22 00:03:57 +00001213 argv.push_back("-o");
Benjamin Kramerc2a98162010-03-13 21:22:49 +00001214 char astTmpFile[L_tmpnam];
1215 argv.push_back(tmpnam(astTmpFile));
Ted Kremenek139ba862009-10-22 00:03:57 +00001216
Douglas Gregor4db64a42010-01-23 00:14:00 +00001217 // Remap any unsaved files to temporary files.
1218 std::vector<llvm::sys::Path> TemporaryFiles;
1219 std::vector<std::string> RemapArgs;
1220 if (RemapFiles(num_unsaved_files, unsaved_files, RemapArgs, TemporaryFiles))
1221 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001222
Douglas Gregor4db64a42010-01-23 00:14:00 +00001223 // The pointers into the elements of RemapArgs are stable because we
1224 // won't be adding anything to RemapArgs after this point.
1225 for (unsigned i = 0, e = RemapArgs.size(); i != e; ++i)
1226 argv.push_back(RemapArgs[i].c_str());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001227
Ted Kremenek139ba862009-10-22 00:03:57 +00001228 // Process the compiler options, stripping off '-o', '-c', '-fsyntax-only'.
1229 for (int i = 0; i < num_command_line_args; ++i)
1230 if (const char *arg = command_line_args[i]) {
1231 if (strcmp(arg, "-o") == 0) {
1232 ++i; // Also skip the matching argument.
1233 continue;
1234 }
1235 if (strcmp(arg, "-emit-ast") == 0 ||
1236 strcmp(arg, "-c") == 0 ||
1237 strcmp(arg, "-fsyntax-only") == 0) {
1238 continue;
1239 }
1240
1241 // Keep the argument.
1242 argv.push_back(arg);
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001243 }
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001244
Douglas Gregord93256e2010-01-28 06:00:51 +00001245 // Generate a temporary name for the diagnostics file.
Benjamin Kramerc2a98162010-03-13 21:22:49 +00001246 char tmpFileResults[L_tmpnam];
1247 char *tmpResultsFileName = tmpnam(tmpFileResults);
1248 llvm::sys::Path DiagnosticsFile(tmpResultsFileName);
Douglas Gregord93256e2010-01-28 06:00:51 +00001249 TemporaryFiles.push_back(DiagnosticsFile);
1250 argv.push_back("-fdiagnostics-binary");
1251
Douglas Gregor94dc8f62010-03-19 16:15:56 +00001252 argv.push_back("-Xclang");
1253 argv.push_back("-detailed-preprocessing-record");
1254
Ted Kremenek139ba862009-10-22 00:03:57 +00001255 // Add the null terminator.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001256 argv.push_back(NULL);
1257
Ted Kremenekfeb15e32009-10-26 22:14:08 +00001258 // Invoke 'clang'.
1259 llvm::sys::Path DevNull; // leave empty, causes redirection to /dev/null
1260 // on Unix or NUL (Windows).
Ted Kremenek379afec2009-10-22 03:24:01 +00001261 std::string ErrMsg;
Douglas Gregord93256e2010-01-28 06:00:51 +00001262 const llvm::sys::Path *Redirects[] = { &DevNull, &DevNull, &DiagnosticsFile,
1263 NULL };
Ted Kremenek379afec2009-10-22 03:24:01 +00001264 llvm::sys::Program::ExecuteAndWait(ClangPath, &argv[0], /* env */ NULL,
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001265 /* redirects */ &Redirects[0],
Ted Kremenek379afec2009-10-22 03:24:01 +00001266 /* secondsToWait */ 0, /* memoryLimits */ 0, &ErrMsg);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001267
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001268 if (!ErrMsg.empty()) {
1269 std::string AllArgs;
Ted Kremenek379afec2009-10-22 03:24:01 +00001270 for (std::vector<const char*>::iterator I = argv.begin(), E = argv.end();
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001271 I != E; ++I) {
1272 AllArgs += ' ';
Ted Kremenek779e5f42009-10-26 22:08:39 +00001273 if (*I)
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001274 AllArgs += *I;
Ted Kremenek779e5f42009-10-26 22:08:39 +00001275 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001276
Daniel Dunbar32141c82010-02-23 20:23:45 +00001277 Diags->Report(diag::err_fe_invoking) << AllArgs << ErrMsg;
Ted Kremenek379afec2009-10-22 03:24:01 +00001278 }
Benjamin Kramer0829a832009-10-18 11:19:36 +00001279
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001280 ASTUnit *ATU = ASTUnit::LoadFromPCHFile(astTmpFile, Diags,
Douglas Gregor4db64a42010-01-23 00:14:00 +00001281 CXXIdx->getOnlyLocalDecls(),
Douglas Gregor4db64a42010-01-23 00:14:00 +00001282 RemappedFiles.data(),
Douglas Gregora88084b2010-02-18 18:08:43 +00001283 RemappedFiles.size(),
1284 /*CaptureDiagnostics=*/true);
Douglas Gregora88084b2010-02-18 18:08:43 +00001285 if (ATU) {
1286 LoadSerializedDiagnostics(DiagnosticsFile,
1287 num_unsaved_files, unsaved_files,
1288 ATU->getFileManager(),
1289 ATU->getSourceManager(),
Douglas Gregor405634b2010-04-05 18:10:21 +00001290 ATU->getStoredDiagnostics());
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001291 } else if (CXXIdx->getDisplayDiagnostics()) {
1292 // We failed to load the ASTUnit, but we can still deserialize the
1293 // diagnostics and emit them.
1294 FileManager FileMgr;
Douglas Gregorf715ca12010-03-16 00:06:06 +00001295 Diagnostic Diag;
1296 SourceManager SourceMgr(Diag);
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001297 // FIXME: Faked LangOpts!
1298 LangOptions LangOpts;
1299 llvm::SmallVector<StoredDiagnostic, 4> Diags;
1300 LoadSerializedDiagnostics(DiagnosticsFile,
1301 num_unsaved_files, unsaved_files,
1302 FileMgr, SourceMgr, Diags);
1303 for (llvm::SmallVector<StoredDiagnostic, 4>::iterator D = Diags.begin(),
1304 DEnd = Diags.end();
1305 D != DEnd; ++D) {
1306 CXStoredDiagnostic Diag(*D, LangOpts);
Douglas Gregor274f1902010-02-22 23:17:23 +00001307 CXString Msg = clang_formatDiagnostic(&Diag,
1308 clang_defaultDiagnosticDisplayOptions());
1309 fprintf(stderr, "%s\n", clang_getCString(Msg));
1310 clang_disposeString(Msg);
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001311 }
Douglas Gregor274f1902010-02-22 23:17:23 +00001312
1313#ifdef LLVM_ON_WIN32
1314 // On Windows, force a flush, since there may be multiple copies of
1315 // stderr and stdout in the file system, all with different buffers
1316 // but writing to the same device.
1317 fflush(stderr);
1318#endif
Douglas Gregora88084b2010-02-18 18:08:43 +00001319 }
Douglas Gregord93256e2010-01-28 06:00:51 +00001320
Douglas Gregor313e26c2010-02-18 23:35:40 +00001321 if (ATU) {
1322 // Make the translation unit responsible for destroying all temporary files.
1323 for (unsigned i = 0, e = TemporaryFiles.size(); i != e; ++i)
1324 ATU->addTemporaryFile(TemporaryFiles[i]);
1325 ATU->addTemporaryFile(llvm::sys::Path(ATU->getPCHFileName()));
1326 } else {
1327 // Destroy all of the temporary files now; they can't be referenced any
1328 // longer.
1329 llvm::sys::Path(astTmpFile).eraseFromDisk();
1330 for (unsigned i = 0, e = TemporaryFiles.size(); i != e; ++i)
1331 TemporaryFiles[i].eraseFromDisk();
1332 }
1333
Steve Naroffe19944c2009-10-15 22:23:48 +00001334 return ATU;
Steve Naroff5b7d8e22009-10-15 20:04:39 +00001335}
1336
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001337void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001338 if (CTUnit)
1339 delete static_cast<ASTUnit *>(CTUnit);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00001340}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001341
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001342CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001343 if (!CTUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001344 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001345
Steve Naroff77accc12009-09-03 18:19:54 +00001346 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001347 return createCXString(CXXUnit->getOriginalSourceFileName(), true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +00001348}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +00001349
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001350CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001351 CXCursor Result = { CXCursor_TranslationUnit, { 0, 0, TU } };
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001352 return Result;
1353}
1354
Ted Kremenekfb480492010-01-13 21:46:36 +00001355} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +00001356
Ted Kremenekfb480492010-01-13 21:46:36 +00001357//===----------------------------------------------------------------------===//
Douglas Gregor1db19de2010-01-19 21:36:55 +00001358// CXSourceLocation and CXSourceRange Operations.
1359//===----------------------------------------------------------------------===//
1360
Douglas Gregorb9790342010-01-22 21:44:22 +00001361extern "C" {
1362CXSourceLocation clang_getNullLocation() {
Douglas Gregor5352ac02010-01-28 00:27:43 +00001363 CXSourceLocation Result = { { 0, 0 }, 0 };
Douglas Gregorb9790342010-01-22 21:44:22 +00001364 return Result;
1365}
1366
1367unsigned clang_equalLocations(CXSourceLocation loc1, CXSourceLocation loc2) {
Daniel Dunbar90a6b9e2010-01-30 23:58:27 +00001368 return (loc1.ptr_data[0] == loc2.ptr_data[0] &&
1369 loc1.ptr_data[1] == loc2.ptr_data[1] &&
1370 loc1.int_data == loc2.int_data);
Douglas Gregorb9790342010-01-22 21:44:22 +00001371}
1372
1373CXSourceLocation clang_getLocation(CXTranslationUnit tu,
1374 CXFile file,
1375 unsigned line,
1376 unsigned column) {
Douglas Gregor42748ec2010-04-30 19:45:53 +00001377 if (!tu || !file)
Douglas Gregorb9790342010-01-22 21:44:22 +00001378 return clang_getNullLocation();
Douglas Gregor42748ec2010-04-30 19:45:53 +00001379
Douglas Gregorb9790342010-01-22 21:44:22 +00001380 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
1381 SourceLocation SLoc
1382 = CXXUnit->getSourceManager().getLocation(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001383 static_cast<const FileEntry *>(file),
Douglas Gregorb9790342010-01-22 21:44:22 +00001384 line, column);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001385
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00001386 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
Douglas Gregorb9790342010-01-22 21:44:22 +00001387}
1388
Douglas Gregor5352ac02010-01-28 00:27:43 +00001389CXSourceRange clang_getNullRange() {
1390 CXSourceRange Result = { { 0, 0 }, 0, 0 };
1391 return Result;
1392}
Daniel Dunbard52864b2010-02-14 10:02:57 +00001393
Douglas Gregor5352ac02010-01-28 00:27:43 +00001394CXSourceRange clang_getRange(CXSourceLocation begin, CXSourceLocation end) {
1395 if (begin.ptr_data[0] != end.ptr_data[0] ||
1396 begin.ptr_data[1] != end.ptr_data[1])
1397 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001398
1399 CXSourceRange Result = { { begin.ptr_data[0], begin.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00001400 begin.int_data, end.int_data };
Douglas Gregorb9790342010-01-22 21:44:22 +00001401 return Result;
1402}
1403
Douglas Gregor46766dc2010-01-26 19:19:08 +00001404void clang_getInstantiationLocation(CXSourceLocation location,
1405 CXFile *file,
1406 unsigned *line,
1407 unsigned *column,
1408 unsigned *offset) {
Douglas Gregor1db19de2010-01-19 21:36:55 +00001409 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
1410
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00001411 if (!location.ptr_data[0] || Loc.isInvalid()) {
Douglas Gregor46766dc2010-01-26 19:19:08 +00001412 if (file)
1413 *file = 0;
1414 if (line)
1415 *line = 0;
1416 if (column)
1417 *column = 0;
1418 if (offset)
1419 *offset = 0;
1420 return;
1421 }
1422
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00001423 const SourceManager &SM =
1424 *static_cast<const SourceManager*>(location.ptr_data[0]);
Douglas Gregor1db19de2010-01-19 21:36:55 +00001425 SourceLocation InstLoc = SM.getInstantiationLoc(Loc);
Douglas Gregor1db19de2010-01-19 21:36:55 +00001426
1427 if (file)
1428 *file = (void *)SM.getFileEntryForID(SM.getFileID(InstLoc));
1429 if (line)
1430 *line = SM.getInstantiationLineNumber(InstLoc);
1431 if (column)
1432 *column = SM.getInstantiationColumnNumber(InstLoc);
Douglas Gregore69517c2010-01-26 03:07:15 +00001433 if (offset)
Douglas Gregor46766dc2010-01-26 19:19:08 +00001434 *offset = SM.getDecomposedLoc(InstLoc).second;
Douglas Gregore69517c2010-01-26 03:07:15 +00001435}
1436
Douglas Gregor1db19de2010-01-19 21:36:55 +00001437CXSourceLocation clang_getRangeStart(CXSourceRange range) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001438 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00001439 range.begin_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00001440 return Result;
1441}
1442
1443CXSourceLocation clang_getRangeEnd(CXSourceRange range) {
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00001444 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00001445 range.end_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00001446 return Result;
1447}
1448
Douglas Gregorb9790342010-01-22 21:44:22 +00001449} // end: extern "C"
1450
Douglas Gregor1db19de2010-01-19 21:36:55 +00001451//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00001452// CXFile Operations.
1453//===----------------------------------------------------------------------===//
1454
1455extern "C" {
Ted Kremenek74844072010-02-17 00:41:20 +00001456CXString clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00001457 if (!SFile)
Ted Kremenek74844072010-02-17 00:41:20 +00001458 return createCXString(NULL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001459
Steve Naroff88145032009-10-27 14:35:18 +00001460 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Ted Kremenek74844072010-02-17 00:41:20 +00001461 return createCXString(FEnt->getName());
Steve Naroff88145032009-10-27 14:35:18 +00001462}
1463
1464time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00001465 if (!SFile)
1466 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001467
Steve Naroff88145032009-10-27 14:35:18 +00001468 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
1469 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +00001470}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001471
Douglas Gregorb9790342010-01-22 21:44:22 +00001472CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
1473 if (!tu)
1474 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001475
Douglas Gregorb9790342010-01-22 21:44:22 +00001476 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001477
Douglas Gregorb9790342010-01-22 21:44:22 +00001478 FileManager &FMgr = CXXUnit->getFileManager();
1479 const FileEntry *File = FMgr.getFile(file_name, file_name+strlen(file_name));
1480 return const_cast<FileEntry *>(File);
1481}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001482
Ted Kremenekfb480492010-01-13 21:46:36 +00001483} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +00001484
Ted Kremenekfb480492010-01-13 21:46:36 +00001485//===----------------------------------------------------------------------===//
1486// CXCursor Operations.
1487//===----------------------------------------------------------------------===//
1488
Ted Kremenekfb480492010-01-13 21:46:36 +00001489static Decl *getDeclFromExpr(Stmt *E) {
1490 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
1491 return RefExpr->getDecl();
1492 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
1493 return ME->getMemberDecl();
1494 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
1495 return RE->getDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001496
Ted Kremenekfb480492010-01-13 21:46:36 +00001497 if (CallExpr *CE = dyn_cast<CallExpr>(E))
1498 return getDeclFromExpr(CE->getCallee());
1499 if (CastExpr *CE = dyn_cast<CastExpr>(E))
1500 return getDeclFromExpr(CE->getSubExpr());
1501 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
1502 return OME->getMethodDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001503
Ted Kremenekfb480492010-01-13 21:46:36 +00001504 return 0;
1505}
1506
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00001507static SourceLocation getLocationFromExpr(Expr *E) {
1508 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
1509 return /*FIXME:*/Msg->getLeftLoc();
1510 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
1511 return DRE->getLocation();
1512 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
1513 return Member->getMemberLoc();
1514 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
1515 return Ivar->getLocation();
1516 return E->getLocStart();
1517}
1518
Ted Kremenekfb480492010-01-13 21:46:36 +00001519extern "C" {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001520
1521unsigned clang_visitChildren(CXCursor parent,
Douglas Gregorb1373d02010-01-20 20:59:29 +00001522 CXCursorVisitor visitor,
1523 CXClientData client_data) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001524 ASTUnit *CXXUnit = getCursorASTUnit(parent);
Douglas Gregorb1373d02010-01-20 20:59:29 +00001525
1526 unsigned PCHLevel = Decl::MaxPCHLevel;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001527
Douglas Gregorb1373d02010-01-20 20:59:29 +00001528 // Set the PCHLevel to filter out unwanted decls if requested.
1529 if (CXXUnit->getOnlyLocalDecls()) {
1530 PCHLevel = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001531
Douglas Gregorb1373d02010-01-20 20:59:29 +00001532 // If the main input was an AST, bump the level.
1533 if (CXXUnit->isMainFileAST())
1534 ++PCHLevel;
1535 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001536
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001537 CursorVisitor CursorVis(CXXUnit, visitor, client_data, PCHLevel);
Douglas Gregorb1373d02010-01-20 20:59:29 +00001538 return CursorVis.VisitChildren(parent);
1539}
1540
Douglas Gregor78205d42010-01-20 21:45:58 +00001541static CXString getDeclSpelling(Decl *D) {
1542 NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
1543 if (!ND)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001544 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001545
Douglas Gregor78205d42010-01-20 21:45:58 +00001546 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001547 return createCXString(OMD->getSelector().getAsString());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001548
Douglas Gregor78205d42010-01-20 21:45:58 +00001549 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
1550 // No, this isn't the same as the code below. getIdentifier() is non-virtual
1551 // and returns different names. NamedDecl returns the class name and
1552 // ObjCCategoryImplDecl returns the category name.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001553 return createCXString(CIMP->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001554
Douglas Gregor78205d42010-01-20 21:45:58 +00001555 if (ND->getIdentifier())
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001556 return createCXString(ND->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001557
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001558 return createCXString("");
Douglas Gregor78205d42010-01-20 21:45:58 +00001559}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001560
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001561CXString clang_getCursorSpelling(CXCursor C) {
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001562 if (clang_isTranslationUnit(C.kind))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001563 return clang_getTranslationUnitSpelling(C.data[2]);
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001564
Steve Narofff334b4e2009-09-02 18:26:48 +00001565 if (clang_isReference(C.kind)) {
1566 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00001567 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +00001568 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001569 return createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00001570 }
1571 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +00001572 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001573 return createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00001574 }
1575 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +00001576 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +00001577 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001578 return createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00001579 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001580 case CXCursor_TypeRef: {
1581 TypeDecl *Type = getCursorTypeRef(C).first;
1582 assert(Type && "Missing type decl");
1583
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001584 return createCXString(getCursorContext(C).getTypeDeclType(Type).
1585 getAsString());
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001586 }
1587
Daniel Dunbaracca7252009-11-30 20:42:49 +00001588 default:
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001589 return createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +00001590 }
1591 }
Douglas Gregor97b98722010-01-19 23:20:36 +00001592
1593 if (clang_isExpression(C.kind)) {
1594 Decl *D = getDeclFromExpr(getCursorExpr(C));
1595 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +00001596 return getDeclSpelling(D);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001597 return createCXString("");
Douglas Gregor97b98722010-01-19 23:20:36 +00001598 }
1599
Douglas Gregor4ae8f292010-03-18 17:52:52 +00001600 if (C.kind == CXCursor_MacroInstantiation)
1601 return createCXString(getCursorMacroInstantiation(C)->getName()
1602 ->getNameStart());
1603
Douglas Gregor572feb22010-03-18 18:04:21 +00001604 if (C.kind == CXCursor_MacroDefinition)
1605 return createCXString(getCursorMacroDefinition(C)->getName()
1606 ->getNameStart());
1607
Douglas Gregor60cbfac2010-01-25 16:56:17 +00001608 if (clang_isDeclaration(C.kind))
1609 return getDeclSpelling(getCursorDecl(C));
Ted Kremeneke68fff62010-02-17 00:41:32 +00001610
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001611 return createCXString("");
Steve Narofff334b4e2009-09-02 18:26:48 +00001612}
1613
Ted Kremeneke68fff62010-02-17 00:41:32 +00001614CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00001615 switch (Kind) {
Ted Kremeneke68fff62010-02-17 00:41:32 +00001616 case CXCursor_FunctionDecl:
1617 return createCXString("FunctionDecl");
1618 case CXCursor_TypedefDecl:
1619 return createCXString("TypedefDecl");
1620 case CXCursor_EnumDecl:
1621 return createCXString("EnumDecl");
1622 case CXCursor_EnumConstantDecl:
1623 return createCXString("EnumConstantDecl");
1624 case CXCursor_StructDecl:
1625 return createCXString("StructDecl");
1626 case CXCursor_UnionDecl:
1627 return createCXString("UnionDecl");
1628 case CXCursor_ClassDecl:
1629 return createCXString("ClassDecl");
1630 case CXCursor_FieldDecl:
1631 return createCXString("FieldDecl");
1632 case CXCursor_VarDecl:
1633 return createCXString("VarDecl");
1634 case CXCursor_ParmDecl:
1635 return createCXString("ParmDecl");
1636 case CXCursor_ObjCInterfaceDecl:
1637 return createCXString("ObjCInterfaceDecl");
1638 case CXCursor_ObjCCategoryDecl:
1639 return createCXString("ObjCCategoryDecl");
1640 case CXCursor_ObjCProtocolDecl:
1641 return createCXString("ObjCProtocolDecl");
1642 case CXCursor_ObjCPropertyDecl:
1643 return createCXString("ObjCPropertyDecl");
1644 case CXCursor_ObjCIvarDecl:
1645 return createCXString("ObjCIvarDecl");
1646 case CXCursor_ObjCInstanceMethodDecl:
1647 return createCXString("ObjCInstanceMethodDecl");
1648 case CXCursor_ObjCClassMethodDecl:
1649 return createCXString("ObjCClassMethodDecl");
1650 case CXCursor_ObjCImplementationDecl:
1651 return createCXString("ObjCImplementationDecl");
1652 case CXCursor_ObjCCategoryImplDecl:
1653 return createCXString("ObjCCategoryImplDecl");
Ted Kremenek8bd5a692010-04-13 23:39:06 +00001654 case CXCursor_CXXMethod:
1655 return createCXString("CXXMethod");
Ted Kremeneke68fff62010-02-17 00:41:32 +00001656 case CXCursor_UnexposedDecl:
1657 return createCXString("UnexposedDecl");
1658 case CXCursor_ObjCSuperClassRef:
1659 return createCXString("ObjCSuperClassRef");
1660 case CXCursor_ObjCProtocolRef:
1661 return createCXString("ObjCProtocolRef");
1662 case CXCursor_ObjCClassRef:
1663 return createCXString("ObjCClassRef");
1664 case CXCursor_TypeRef:
1665 return createCXString("TypeRef");
1666 case CXCursor_UnexposedExpr:
1667 return createCXString("UnexposedExpr");
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00001668 case CXCursor_BlockExpr:
1669 return createCXString("BlockExpr");
Ted Kremeneke68fff62010-02-17 00:41:32 +00001670 case CXCursor_DeclRefExpr:
1671 return createCXString("DeclRefExpr");
1672 case CXCursor_MemberRefExpr:
1673 return createCXString("MemberRefExpr");
1674 case CXCursor_CallExpr:
1675 return createCXString("CallExpr");
1676 case CXCursor_ObjCMessageExpr:
1677 return createCXString("ObjCMessageExpr");
1678 case CXCursor_UnexposedStmt:
1679 return createCXString("UnexposedStmt");
1680 case CXCursor_InvalidFile:
1681 return createCXString("InvalidFile");
Ted Kremenek292db642010-03-19 20:39:05 +00001682 case CXCursor_InvalidCode:
1683 return createCXString("InvalidCode");
Ted Kremeneke68fff62010-02-17 00:41:32 +00001684 case CXCursor_NoDeclFound:
1685 return createCXString("NoDeclFound");
1686 case CXCursor_NotImplemented:
1687 return createCXString("NotImplemented");
1688 case CXCursor_TranslationUnit:
1689 return createCXString("TranslationUnit");
Ted Kremeneke77f4432010-02-18 03:09:07 +00001690 case CXCursor_UnexposedAttr:
1691 return createCXString("UnexposedAttr");
1692 case CXCursor_IBActionAttr:
1693 return createCXString("attribute(ibaction)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00001694 case CXCursor_IBOutletAttr:
1695 return createCXString("attribute(iboutlet)");
1696 case CXCursor_PreprocessingDirective:
1697 return createCXString("preprocessing directive");
Douglas Gregor572feb22010-03-18 18:04:21 +00001698 case CXCursor_MacroDefinition:
1699 return createCXString("macro definition");
Douglas Gregor48072312010-03-18 15:23:44 +00001700 case CXCursor_MacroInstantiation:
1701 return createCXString("macro instantiation");
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00001702 case CXCursor_Namespace:
1703 return createCXString("Namespace");
Ted Kremeneka0536d82010-05-07 01:04:29 +00001704 case CXCursor_LinkageSpec:
1705 return createCXString("LinkageSpec");
Steve Naroff89922f82009-08-31 00:59:03 +00001706 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00001707
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00001708 llvm_unreachable("Unhandled CXCursorKind");
Ted Kremeneke68fff62010-02-17 00:41:32 +00001709 return createCXString(NULL);
Steve Naroff600866c2009-08-27 19:51:58 +00001710}
Steve Naroff89922f82009-08-31 00:59:03 +00001711
Ted Kremeneke68fff62010-02-17 00:41:32 +00001712enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
1713 CXCursor parent,
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001714 CXClientData client_data) {
1715 CXCursor *BestCursor = static_cast<CXCursor *>(client_data);
1716 *BestCursor = cursor;
1717 return CXChildVisit_Recurse;
1718}
Ted Kremeneke68fff62010-02-17 00:41:32 +00001719
Douglas Gregorb9790342010-01-22 21:44:22 +00001720CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
1721 if (!TU)
Ted Kremenekf4629892010-01-14 01:51:23 +00001722 return clang_getNullCursor();
Ted Kremeneke68fff62010-02-17 00:41:32 +00001723
Douglas Gregorb9790342010-01-22 21:44:22 +00001724 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
1725
Douglas Gregorbdf60622010-03-05 21:16:25 +00001726 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
1727
Ted Kremeneka297de22010-01-25 22:34:44 +00001728 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001729 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
1730 if (SLoc.isValid()) {
Daniel Dunbard52864b2010-02-14 10:02:57 +00001731 SourceRange RegionOfInterest(SLoc, SLoc.getFileLocWithOffset(1));
Ted Kremeneke68fff62010-02-17 00:41:32 +00001732
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001733 // FIXME: Would be great to have a "hint" cursor, then walk from that
1734 // hint cursor upward until we find a cursor whose source range encloses
1735 // the region of interest, rather than starting from the translation unit.
1736 CXCursor Parent = clang_getTranslationUnitCursor(CXXUnit);
Ted Kremeneke68fff62010-02-17 00:41:32 +00001737 CursorVisitor CursorVis(CXXUnit, GetCursorVisitor, &Result,
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001738 Decl::MaxPCHLevel, RegionOfInterest);
1739 CursorVis.VisitChildren(Parent);
Steve Naroff77128dd2009-09-15 20:25:34 +00001740 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00001741 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00001742}
1743
Ted Kremenek73885552009-11-17 19:28:59 +00001744CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00001745 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00001746}
1747
1748unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00001749 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00001750}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001751
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001752unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00001753 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
1754}
1755
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001756unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +00001757 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
1758}
Steve Naroff2d4d6292009-08-31 14:26:51 +00001759
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001760unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00001761 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
1762}
1763
Douglas Gregor97b98722010-01-19 23:20:36 +00001764unsigned clang_isExpression(enum CXCursorKind K) {
1765 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
1766}
1767
1768unsigned clang_isStatement(enum CXCursorKind K) {
1769 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
1770}
1771
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001772unsigned clang_isTranslationUnit(enum CXCursorKind K) {
1773 return K == CXCursor_TranslationUnit;
1774}
1775
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00001776unsigned clang_isPreprocessing(enum CXCursorKind K) {
1777 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
1778}
1779
Ted Kremenekad6eff62010-03-08 21:17:29 +00001780unsigned clang_isUnexposed(enum CXCursorKind K) {
1781 switch (K) {
1782 case CXCursor_UnexposedDecl:
1783 case CXCursor_UnexposedExpr:
1784 case CXCursor_UnexposedStmt:
1785 case CXCursor_UnexposedAttr:
1786 return true;
1787 default:
1788 return false;
1789 }
1790}
1791
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001792CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00001793 return C.kind;
1794}
1795
Douglas Gregor98258af2010-01-18 22:46:11 +00001796CXSourceLocation clang_getCursorLocation(CXCursor C) {
1797 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00001798 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001799 case CXCursor_ObjCSuperClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00001800 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1801 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001802 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001803 }
1804
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001805 case CXCursor_ObjCProtocolRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00001806 std::pair<ObjCProtocolDecl *, SourceLocation> P
1807 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001808 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001809 }
1810
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001811 case CXCursor_ObjCClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00001812 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1813 = getCursorObjCClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001814 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001815 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001816
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001817 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001818 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001819 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001820 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001821
Douglas Gregorf46034a2010-01-18 23:41:10 +00001822 default:
1823 // FIXME: Need a way to enumerate all non-reference cases.
1824 llvm_unreachable("Missed a reference kind");
1825 }
Douglas Gregor98258af2010-01-18 22:46:11 +00001826 }
Douglas Gregor97b98722010-01-19 23:20:36 +00001827
1828 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001829 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00001830 getLocationFromExpr(getCursorExpr(C)));
1831
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00001832 if (C.kind == CXCursor_PreprocessingDirective) {
1833 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
1834 return cxloc::translateSourceLocation(getCursorContext(C), L);
1835 }
Douglas Gregor48072312010-03-18 15:23:44 +00001836
1837 if (C.kind == CXCursor_MacroInstantiation) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00001838 SourceLocation L
1839 = cxcursor::getCursorMacroInstantiation(C)->getSourceRange().getBegin();
Douglas Gregor48072312010-03-18 15:23:44 +00001840 return cxloc::translateSourceLocation(getCursorContext(C), L);
1841 }
Douglas Gregor572feb22010-03-18 18:04:21 +00001842
1843 if (C.kind == CXCursor_MacroDefinition) {
1844 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
1845 return cxloc::translateSourceLocation(getCursorContext(C), L);
1846 }
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00001847
Ted Kremenek9a700d22010-05-12 06:16:13 +00001848 if (C.kind < CXCursor_FirstDecl || C.kind > CXCursor_LastDecl)
Douglas Gregor5352ac02010-01-28 00:27:43 +00001849 return clang_getNullLocation();
Douglas Gregor98258af2010-01-18 22:46:11 +00001850
Douglas Gregorf46034a2010-01-18 23:41:10 +00001851 Decl *D = getCursorDecl(C);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001852 SourceLocation Loc = D->getLocation();
1853 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
1854 Loc = Class->getClassLoc();
Douglas Gregor2ca54fe2010-03-22 15:53:50 +00001855 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00001856}
Douglas Gregora7bde202010-01-19 00:34:46 +00001857
1858CXSourceRange clang_getCursorExtent(CXCursor C) {
1859 if (clang_isReference(C.kind)) {
1860 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001861 case CXCursor_ObjCSuperClassRef: {
Douglas Gregora7bde202010-01-19 00:34:46 +00001862 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1863 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001864 return cxloc::translateSourceRange(P.first->getASTContext(), P.second);
Douglas Gregora7bde202010-01-19 00:34:46 +00001865 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001866
1867 case CXCursor_ObjCProtocolRef: {
Douglas Gregora7bde202010-01-19 00:34:46 +00001868 std::pair<ObjCProtocolDecl *, SourceLocation> P
1869 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001870 return cxloc::translateSourceRange(P.first->getASTContext(), P.second);
Douglas Gregora7bde202010-01-19 00:34:46 +00001871 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001872
1873 case CXCursor_ObjCClassRef: {
Douglas Gregora7bde202010-01-19 00:34:46 +00001874 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1875 = getCursorObjCClassRef(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001876
Ted Kremeneka297de22010-01-25 22:34:44 +00001877 return cxloc::translateSourceRange(P.first->getASTContext(), P.second);
Douglas Gregora7bde202010-01-19 00:34:46 +00001878 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001879
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001880 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001881 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001882 return cxloc::translateSourceRange(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001883 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001884
Douglas Gregora7bde202010-01-19 00:34:46 +00001885 default:
1886 // FIXME: Need a way to enumerate all non-reference cases.
1887 llvm_unreachable("Missed a reference kind");
1888 }
1889 }
Douglas Gregor97b98722010-01-19 23:20:36 +00001890
1891 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001892 return cxloc::translateSourceRange(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00001893 getCursorExpr(C)->getSourceRange());
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001894
1895 if (clang_isStatement(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001896 return cxloc::translateSourceRange(getCursorContext(C),
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001897 getCursorStmt(C)->getSourceRange());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001898
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00001899 if (C.kind == CXCursor_PreprocessingDirective) {
1900 SourceRange R = cxcursor::getCursorPreprocessingDirective(C);
1901 return cxloc::translateSourceRange(getCursorContext(C), R);
1902 }
Douglas Gregor48072312010-03-18 15:23:44 +00001903
1904 if (C.kind == CXCursor_MacroInstantiation) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00001905 SourceRange R = cxcursor::getCursorMacroInstantiation(C)->getSourceRange();
Douglas Gregor48072312010-03-18 15:23:44 +00001906 return cxloc::translateSourceRange(getCursorContext(C), R);
1907 }
Douglas Gregor572feb22010-03-18 18:04:21 +00001908
1909 if (C.kind == CXCursor_MacroDefinition) {
1910 SourceRange R = cxcursor::getCursorMacroDefinition(C)->getSourceRange();
1911 return cxloc::translateSourceRange(getCursorContext(C), R);
1912 }
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00001913
Ted Kremenek9a700d22010-05-12 06:16:13 +00001914 if (C.kind < CXCursor_FirstDecl || C.kind > CXCursor_LastDecl)
Douglas Gregor5352ac02010-01-28 00:27:43 +00001915 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001916
Douglas Gregora7bde202010-01-19 00:34:46 +00001917 Decl *D = getCursorDecl(C);
Douglas Gregor2ca54fe2010-03-22 15:53:50 +00001918 return cxloc::translateSourceRange(getCursorContext(C), D->getSourceRange());
Douglas Gregora7bde202010-01-19 00:34:46 +00001919}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001920
1921CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001922 if (clang_isInvalid(C.kind))
1923 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001924
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001925 ASTUnit *CXXUnit = getCursorASTUnit(C);
Douglas Gregorb6998662010-01-19 19:34:47 +00001926 if (clang_isDeclaration(C.kind))
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001927 return C;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001928
Douglas Gregor97b98722010-01-19 23:20:36 +00001929 if (clang_isExpression(C.kind)) {
1930 Decl *D = getDeclFromExpr(getCursorExpr(C));
1931 if (D)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001932 return MakeCXCursor(D, CXXUnit);
Douglas Gregor97b98722010-01-19 23:20:36 +00001933 return clang_getNullCursor();
1934 }
1935
Douglas Gregorbf7efa22010-03-18 18:23:03 +00001936 if (C.kind == CXCursor_MacroInstantiation) {
1937 if (MacroDefinition *Def = getCursorMacroInstantiation(C)->getDefinition())
1938 return MakeMacroDefinitionCursor(Def, CXXUnit);
1939 }
1940
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001941 if (!clang_isReference(C.kind))
1942 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001943
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001944 switch (C.kind) {
1945 case CXCursor_ObjCSuperClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001946 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001947
1948 case CXCursor_ObjCProtocolRef: {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001949 return MakeCXCursor(getCursorObjCProtocolRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001950
1951 case CXCursor_ObjCClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001952 return MakeCXCursor(getCursorObjCClassRef(C).first, CXXUnit);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001953
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001954 case CXCursor_TypeRef:
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001955 return MakeCXCursor(getCursorTypeRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001956
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001957 default:
1958 // We would prefer to enumerate all non-reference cursor kinds here.
1959 llvm_unreachable("Unhandled reference cursor kind");
1960 break;
1961 }
1962 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001963
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001964 return clang_getNullCursor();
1965}
1966
Douglas Gregorb6998662010-01-19 19:34:47 +00001967CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001968 if (clang_isInvalid(C.kind))
1969 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001970
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001971 ASTUnit *CXXUnit = getCursorASTUnit(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001972
Douglas Gregorb6998662010-01-19 19:34:47 +00001973 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00001974 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00001975 C = clang_getCursorReferenced(C);
1976 WasReference = true;
1977 }
1978
Douglas Gregorbf7efa22010-03-18 18:23:03 +00001979 if (C.kind == CXCursor_MacroInstantiation)
1980 return clang_getCursorReferenced(C);
1981
Douglas Gregorb6998662010-01-19 19:34:47 +00001982 if (!clang_isDeclaration(C.kind))
1983 return clang_getNullCursor();
1984
1985 Decl *D = getCursorDecl(C);
1986 if (!D)
1987 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001988
Douglas Gregorb6998662010-01-19 19:34:47 +00001989 switch (D->getKind()) {
1990 // Declaration kinds that don't really separate the notions of
1991 // declaration and definition.
1992 case Decl::Namespace:
1993 case Decl::Typedef:
1994 case Decl::TemplateTypeParm:
1995 case Decl::EnumConstant:
1996 case Decl::Field:
1997 case Decl::ObjCIvar:
1998 case Decl::ObjCAtDefsField:
1999 case Decl::ImplicitParam:
2000 case Decl::ParmVar:
2001 case Decl::NonTypeTemplateParm:
2002 case Decl::TemplateTemplateParm:
2003 case Decl::ObjCCategoryImpl:
2004 case Decl::ObjCImplementation:
2005 case Decl::LinkageSpec:
2006 case Decl::ObjCPropertyImpl:
2007 case Decl::FileScopeAsm:
2008 case Decl::StaticAssert:
2009 case Decl::Block:
2010 return C;
2011
2012 // Declaration kinds that don't make any sense here, but are
2013 // nonetheless harmless.
2014 case Decl::TranslationUnit:
Douglas Gregorb6998662010-01-19 19:34:47 +00002015 break;
2016
2017 // Declaration kinds for which the definition is not resolvable.
2018 case Decl::UnresolvedUsingTypename:
2019 case Decl::UnresolvedUsingValue:
2020 break;
2021
2022 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002023 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
2024 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002025
2026 case Decl::NamespaceAlias:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002027 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002028
2029 case Decl::Enum:
2030 case Decl::Record:
2031 case Decl::CXXRecord:
2032 case Decl::ClassTemplateSpecialization:
2033 case Decl::ClassTemplatePartialSpecialization:
Douglas Gregor952b0172010-02-11 01:04:33 +00002034 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002035 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002036 return clang_getNullCursor();
2037
2038 case Decl::Function:
2039 case Decl::CXXMethod:
2040 case Decl::CXXConstructor:
2041 case Decl::CXXDestructor:
2042 case Decl::CXXConversion: {
2043 const FunctionDecl *Def = 0;
2044 if (cast<FunctionDecl>(D)->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002045 return MakeCXCursor(const_cast<FunctionDecl *>(Def), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002046 return clang_getNullCursor();
2047 }
2048
2049 case Decl::Var: {
Sebastian Redl31310a22010-02-01 20:16:42 +00002050 // Ask the variable if it has a definition.
2051 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
2052 return MakeCXCursor(Def, CXXUnit);
2053 return clang_getNullCursor();
Douglas Gregorb6998662010-01-19 19:34:47 +00002054 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002055
Douglas Gregorb6998662010-01-19 19:34:47 +00002056 case Decl::FunctionTemplate: {
2057 const FunctionDecl *Def = 0;
2058 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002059 return MakeCXCursor(Def->getDescribedFunctionTemplate(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002060 return clang_getNullCursor();
2061 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002062
Douglas Gregorb6998662010-01-19 19:34:47 +00002063 case Decl::ClassTemplate: {
2064 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
Douglas Gregor952b0172010-02-11 01:04:33 +00002065 ->getDefinition())
Douglas Gregorb6998662010-01-19 19:34:47 +00002066 return MakeCXCursor(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002067 cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002068 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002069 return clang_getNullCursor();
2070 }
2071
2072 case Decl::Using: {
2073 UsingDecl *Using = cast<UsingDecl>(D);
2074 CXCursor Def = clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002075 for (UsingDecl::shadow_iterator S = Using->shadow_begin(),
2076 SEnd = Using->shadow_end();
Douglas Gregorb6998662010-01-19 19:34:47 +00002077 S != SEnd; ++S) {
2078 if (Def != clang_getNullCursor()) {
2079 // FIXME: We have no way to return multiple results.
2080 return clang_getNullCursor();
2081 }
2082
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002083 Def = clang_getCursorDefinition(MakeCXCursor((*S)->getTargetDecl(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002084 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002085 }
2086
2087 return Def;
2088 }
2089
2090 case Decl::UsingShadow:
2091 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002092 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002093 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002094
2095 case Decl::ObjCMethod: {
2096 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
2097 if (Method->isThisDeclarationADefinition())
2098 return C;
2099
2100 // Dig out the method definition in the associated
2101 // @implementation, if we have it.
2102 // FIXME: The ASTs should make finding the definition easier.
2103 if (ObjCInterfaceDecl *Class
2104 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
2105 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
2106 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
2107 Method->isInstanceMethod()))
2108 if (Def->isThisDeclarationADefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002109 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002110
2111 return clang_getNullCursor();
2112 }
2113
2114 case Decl::ObjCCategory:
2115 if (ObjCCategoryImplDecl *Impl
2116 = cast<ObjCCategoryDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002117 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002118 return clang_getNullCursor();
2119
2120 case Decl::ObjCProtocol:
2121 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
2122 return C;
2123 return clang_getNullCursor();
2124
2125 case Decl::ObjCInterface:
2126 // There are two notions of a "definition" for an Objective-C
2127 // class: the interface and its implementation. When we resolved a
2128 // reference to an Objective-C class, produce the @interface as
2129 // the definition; when we were provided with the interface,
2130 // produce the @implementation as the definition.
2131 if (WasReference) {
2132 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
2133 return C;
2134 } else if (ObjCImplementationDecl *Impl
2135 = cast<ObjCInterfaceDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002136 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002137 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002138
Douglas Gregorb6998662010-01-19 19:34:47 +00002139 case Decl::ObjCProperty:
2140 // FIXME: We don't really know where to find the
2141 // ObjCPropertyImplDecls that implement this property.
2142 return clang_getNullCursor();
2143
2144 case Decl::ObjCCompatibleAlias:
2145 if (ObjCInterfaceDecl *Class
2146 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
2147 if (!Class->isForwardDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002148 return MakeCXCursor(Class, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002149
Douglas Gregorb6998662010-01-19 19:34:47 +00002150 return clang_getNullCursor();
2151
2152 case Decl::ObjCForwardProtocol: {
2153 ObjCForwardProtocolDecl *Forward = cast<ObjCForwardProtocolDecl>(D);
2154 if (Forward->protocol_size() == 1)
2155 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002156 MakeCXCursor(*Forward->protocol_begin(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002157 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002158
2159 // FIXME: Cannot return multiple definitions.
2160 return clang_getNullCursor();
2161 }
2162
2163 case Decl::ObjCClass: {
2164 ObjCClassDecl *Class = cast<ObjCClassDecl>(D);
2165 if (Class->size() == 1) {
2166 ObjCInterfaceDecl *IFace = Class->begin()->getInterface();
2167 if (!IFace->isForwardDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002168 return MakeCXCursor(IFace, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002169 return clang_getNullCursor();
2170 }
2171
2172 // FIXME: Cannot return multiple definitions.
2173 return clang_getNullCursor();
2174 }
2175
2176 case Decl::Friend:
2177 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002178 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002179 return clang_getNullCursor();
2180
2181 case Decl::FriendTemplate:
2182 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002183 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002184 return clang_getNullCursor();
2185 }
2186
2187 return clang_getNullCursor();
2188}
2189
2190unsigned clang_isCursorDefinition(CXCursor C) {
2191 if (!clang_isDeclaration(C.kind))
2192 return 0;
2193
2194 return clang_getCursorDefinition(C) == C;
2195}
2196
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002197void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00002198 const char **startBuf,
2199 const char **endBuf,
2200 unsigned *startLine,
2201 unsigned *startColumn,
2202 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002203 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00002204 assert(getCursorDecl(C) && "CXCursor has null decl");
2205 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00002206 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
2207 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002208
Steve Naroff4ade6d62009-09-23 17:52:52 +00002209 SourceManager &SM = FD->getASTContext().getSourceManager();
2210 *startBuf = SM.getCharacterData(Body->getLBracLoc());
2211 *endBuf = SM.getCharacterData(Body->getRBracLoc());
2212 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
2213 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
2214 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
2215 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
2216}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002217
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002218void clang_enableStackTraces(void) {
2219 llvm::sys::PrintStackTraceOnErrorSignal();
2220}
2221
Ted Kremenekfb480492010-01-13 21:46:36 +00002222} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00002223
Ted Kremenekfb480492010-01-13 21:46:36 +00002224//===----------------------------------------------------------------------===//
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002225// Token-based Operations.
2226//===----------------------------------------------------------------------===//
2227
2228/* CXToken layout:
2229 * int_data[0]: a CXTokenKind
2230 * int_data[1]: starting token location
2231 * int_data[2]: token length
2232 * int_data[3]: reserved
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002233 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002234 * otherwise unused.
2235 */
2236extern "C" {
2237
2238CXTokenKind clang_getTokenKind(CXToken CXTok) {
2239 return static_cast<CXTokenKind>(CXTok.int_data[0]);
2240}
2241
2242CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
2243 switch (clang_getTokenKind(CXTok)) {
2244 case CXToken_Identifier:
2245 case CXToken_Keyword:
2246 // We know we have an IdentifierInfo*, so use that.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002247 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
2248 ->getNameStart());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002249
2250 case CXToken_Literal: {
2251 // We have stashed the starting pointer in the ptr_data field. Use it.
2252 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002253 return createCXString(llvm::StringRef(Text, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002254 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002255
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002256 case CXToken_Punctuation:
2257 case CXToken_Comment:
2258 break;
2259 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002260
2261 // We have to find the starting buffer pointer the hard way, by
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002262 // deconstructing the source location.
2263 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2264 if (!CXXUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002265 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002266
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002267 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
2268 std::pair<FileID, unsigned> LocInfo
2269 = CXXUnit->getSourceManager().getDecomposedLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +00002270 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002271 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00002272 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
2273 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00002274 return createCXString("");
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002275
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002276 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002277}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002278
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002279CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
2280 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2281 if (!CXXUnit)
2282 return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002283
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002284 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
2285 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
2286}
2287
2288CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
2289 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregor5352ac02010-01-28 00:27:43 +00002290 if (!CXXUnit)
2291 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002292
2293 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002294 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
2295}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002296
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002297void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
2298 CXToken **Tokens, unsigned *NumTokens) {
2299 if (Tokens)
2300 *Tokens = 0;
2301 if (NumTokens)
2302 *NumTokens = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002303
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002304 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2305 if (!CXXUnit || !Tokens || !NumTokens)
2306 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002307
Douglas Gregorbdf60622010-03-05 21:16:25 +00002308 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
2309
Daniel Dunbar85b988f2010-02-14 08:31:57 +00002310 SourceRange R = cxloc::translateCXSourceRange(Range);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002311 if (R.isInvalid())
2312 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002313
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002314 SourceManager &SourceMgr = CXXUnit->getSourceManager();
2315 std::pair<FileID, unsigned> BeginLocInfo
2316 = SourceMgr.getDecomposedLoc(R.getBegin());
2317 std::pair<FileID, unsigned> EndLocInfo
2318 = SourceMgr.getDecomposedLoc(R.getEnd());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002319
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002320 // Cannot tokenize across files.
2321 if (BeginLocInfo.first != EndLocInfo.first)
2322 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002323
2324 // Create a lexer
Douglas Gregorf715ca12010-03-16 00:06:06 +00002325 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002326 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00002327 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
Douglas Gregor47a3fcd2010-03-16 20:26:15 +00002328 if (Invalid)
2329 return;
Douglas Gregoraea67db2010-03-15 22:54:52 +00002330
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002331 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
2332 CXXUnit->getASTContext().getLangOptions(),
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002333 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002334 Lex.SetCommentRetentionState(true);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002335
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002336 // Lex tokens until we hit the end of the range.
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002337 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002338 llvm::SmallVector<CXToken, 32> CXTokens;
2339 Token Tok;
2340 do {
2341 // Lex the next token
2342 Lex.LexFromRawLexer(Tok);
2343 if (Tok.is(tok::eof))
2344 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002345
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002346 // Initialize the CXToken.
2347 CXToken CXTok;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002348
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002349 // - Common fields
2350 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
2351 CXTok.int_data[2] = Tok.getLength();
2352 CXTok.int_data[3] = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002353
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002354 // - Kind-specific fields
2355 if (Tok.isLiteral()) {
2356 CXTok.int_data[0] = CXToken_Literal;
2357 CXTok.ptr_data = (void *)Tok.getLiteralData();
2358 } else if (Tok.is(tok::identifier)) {
Douglas Gregoraea67db2010-03-15 22:54:52 +00002359 // Lookup the identifier to determine whether we have a keyword.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002360 std::pair<FileID, unsigned> LocInfo
2361 = SourceMgr.getDecomposedLoc(Tok.getLocation());
Douglas Gregorf715ca12010-03-16 00:06:06 +00002362 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002363 llvm::StringRef Buf
Douglas Gregorf715ca12010-03-16 00:06:06 +00002364 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
2365 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00002366 return;
2367
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002368 const char *StartPos = Buf.data() + LocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002369 IdentifierInfo *II
2370 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok, StartPos);
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00002371
2372 if (II->getObjCKeywordID() != tok::objc_not_keyword) {
2373 CXTok.int_data[0] = CXToken_Keyword;
2374 }
2375 else {
2376 CXTok.int_data[0] = II->getTokenID() == tok::identifier?
2377 CXToken_Identifier
2378 : CXToken_Keyword;
2379 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002380 CXTok.ptr_data = II;
2381 } else if (Tok.is(tok::comment)) {
2382 CXTok.int_data[0] = CXToken_Comment;
2383 CXTok.ptr_data = 0;
2384 } else {
2385 CXTok.int_data[0] = CXToken_Punctuation;
2386 CXTok.ptr_data = 0;
2387 }
2388 CXTokens.push_back(CXTok);
2389 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002390
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002391 if (CXTokens.empty())
2392 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002393
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002394 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
2395 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
2396 *NumTokens = CXTokens.size();
2397}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002398
Ted Kremenek6db61092010-05-05 00:55:15 +00002399void clang_disposeTokens(CXTranslationUnit TU,
2400 CXToken *Tokens, unsigned NumTokens) {
2401 free(Tokens);
2402}
2403
2404} // end: extern "C"
2405
2406//===----------------------------------------------------------------------===//
2407// Token annotation APIs.
2408//===----------------------------------------------------------------------===//
2409
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002410typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002411static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
2412 CXCursor parent,
2413 CXClientData client_data);
Ted Kremenek6db61092010-05-05 00:55:15 +00002414namespace {
2415class AnnotateTokensWorker {
2416 AnnotateTokensData &Annotated;
Ted Kremenek11949cb2010-05-05 00:55:17 +00002417 CXToken *Tokens;
2418 CXCursor *Cursors;
2419 unsigned NumTokens;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002420 unsigned TokIdx;
2421 CursorVisitor AnnotateVis;
2422 SourceManager &SrcMgr;
2423
2424 bool MoreTokens() const { return TokIdx < NumTokens; }
2425 unsigned NextToken() const { return TokIdx; }
2426 void AdvanceToken() { ++TokIdx; }
2427 SourceLocation GetTokenLoc(unsigned tokI) {
2428 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
2429 }
2430
Ted Kremenek6db61092010-05-05 00:55:15 +00002431public:
Ted Kremenek11949cb2010-05-05 00:55:17 +00002432 AnnotateTokensWorker(AnnotateTokensData &annotated,
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002433 CXToken *tokens, CXCursor *cursors, unsigned numTokens,
2434 ASTUnit *CXXUnit, SourceRange RegionOfInterest)
Ted Kremenek11949cb2010-05-05 00:55:17 +00002435 : Annotated(annotated), Tokens(tokens), Cursors(cursors),
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002436 NumTokens(numTokens), TokIdx(0),
2437 AnnotateVis(CXXUnit, AnnotateTokensVisitor, this,
2438 Decl::MaxPCHLevel, RegionOfInterest),
2439 SrcMgr(CXXUnit->getSourceManager()) {}
Ted Kremenek11949cb2010-05-05 00:55:17 +00002440
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002441 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
Ted Kremenek6db61092010-05-05 00:55:15 +00002442 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002443 void AnnotateTokens(CXCursor parent);
Ted Kremenek6db61092010-05-05 00:55:15 +00002444};
2445}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002446
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002447void AnnotateTokensWorker::AnnotateTokens(CXCursor parent) {
2448 // Walk the AST within the region of interest, annotating tokens
2449 // along the way.
2450 VisitChildren(parent);
Ted Kremenek11949cb2010-05-05 00:55:17 +00002451
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002452 for (unsigned I = 0 ; I < TokIdx ; ++I) {
2453 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
2454 if (Pos != Annotated.end())
2455 Cursors[I] = Pos->second;
2456 }
2457
2458 // Finish up annotating any tokens left.
2459 if (!MoreTokens())
2460 return;
2461
2462 const CXCursor &C = clang_getNullCursor();
2463 for (unsigned I = TokIdx ; I < NumTokens ; ++I) {
2464 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
2465 Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second;
Ted Kremenek11949cb2010-05-05 00:55:17 +00002466 }
2467}
2468
Ted Kremenek6db61092010-05-05 00:55:15 +00002469enum CXChildVisitResult
2470AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002471 CXSourceLocation Loc = clang_getCursorLocation(cursor);
2472 // We can always annotate a preprocessing directive/macro instantiation.
2473 if (clang_isPreprocessing(cursor.kind)) {
2474 Annotated[Loc.int_data] = cursor;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002475 return CXChildVisit_Recurse;
2476 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002477
2478 CXSourceRange cursorExtent = clang_getCursorExtent(cursor);
2479 SourceRange cursorRange = cxloc::translateCXSourceRange(cursorExtent);
Ted Kremeneka333c662010-05-12 05:29:33 +00002480
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002481 if (cursorRange.isInvalid())
2482 return CXChildVisit_Continue;
Ted Kremeneka333c662010-05-12 05:29:33 +00002483
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002484 SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data);
2485
Ted Kremeneka333c662010-05-12 05:29:33 +00002486 // Adjust the annotated range based specific declarations.
2487 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
2488 if (cursorK >= CXCursor_FirstDecl && cursorK <= CXCursor_LastDecl) {
2489 if (const DeclaratorDecl *DD =
2490 dyn_cast<DeclaratorDecl>(cxcursor::getCursorDecl(cursor))) {
2491 if (TypeSourceInfo *TI = DD->getTypeSourceInfo()) {
2492 TypeLoc TL = TI->getTypeLoc();
2493 SourceLocation TLoc = TL.getFullSourceRange().getBegin();
Ted Kremeneka333c662010-05-12 05:29:33 +00002494 if (TLoc.isValid()) {
2495 assert(SrcMgr.isBeforeInTranslationUnit(TLoc, L));
2496 cursorRange.setBegin(TLoc);
2497 }
2498 }
2499 }
2500 }
2501
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002502 const enum CXCursorKind K = clang_getCursorKind(parent);
2503 const CXCursor updateC =
2504 (clang_isInvalid(K) || K == CXCursor_TranslationUnit ||
2505 L.isMacroID())
2506 ? clang_getNullCursor() : parent;
2507
2508 while (MoreTokens()) {
2509 const unsigned I = NextToken();
2510 SourceLocation TokLoc = GetTokenLoc(I);
2511 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
2512 case RangeBefore:
2513 Cursors[I] = updateC;
2514 AdvanceToken();
2515 continue;
2516 case RangeAfter:
2517 return CXChildVisit_Continue;
2518 case RangeOverlap:
2519 break;
2520 }
2521 break;
2522 }
2523
2524 // Visit children to get their cursor information.
2525 const unsigned BeforeChildren = NextToken();
2526 VisitChildren(cursor);
2527 const unsigned AfterChildren = NextToken();
2528
2529 // Adjust 'Last' to the last token within the extent of the cursor.
2530 while (MoreTokens()) {
2531 const unsigned I = NextToken();
2532 SourceLocation TokLoc = GetTokenLoc(I);
2533 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
2534 case RangeBefore:
2535 assert(0 && "Infeasible");
2536 case RangeAfter:
2537 break;
2538 case RangeOverlap:
2539 Cursors[I] = updateC;
2540 AdvanceToken();
2541 continue;
2542 }
2543 break;
2544 }
2545 const unsigned Last = NextToken();
Ted Kremenek6db61092010-05-05 00:55:15 +00002546
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002547 // Scan the tokens that are at the beginning of the cursor, but are not
2548 // capture by the child cursors.
2549
2550 // For AST elements within macros, rely on a post-annotate pass to
2551 // to correctly annotate the tokens with cursors. Otherwise we can
2552 // get confusing results of having tokens that map to cursors that really
2553 // are expanded by an instantiation.
2554 if (L.isMacroID())
2555 cursor = clang_getNullCursor();
2556
2557 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
2558 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
2559 break;
2560 Cursors[I] = cursor;
2561 }
2562 // Scan the tokens that are at the end of the cursor, but are not captured
2563 // but the child cursors.
2564 for (unsigned I = AfterChildren; I != Last; ++I)
2565 Cursors[I] = cursor;
2566
2567 TokIdx = Last;
2568 return CXChildVisit_Continue;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002569}
2570
Ted Kremenek6db61092010-05-05 00:55:15 +00002571static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
2572 CXCursor parent,
2573 CXClientData client_data) {
2574 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
2575}
2576
2577extern "C" {
2578
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002579void clang_annotateTokens(CXTranslationUnit TU,
2580 CXToken *Tokens, unsigned NumTokens,
2581 CXCursor *Cursors) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002582
2583 if (NumTokens == 0 || !Tokens || !Cursors)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002584 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002585
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002586 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002587 if (!CXXUnit) {
2588 // Any token we don't specifically annotate will have a NULL cursor.
2589 const CXCursor &C = clang_getNullCursor();
2590 for (unsigned I = 0; I != NumTokens; ++I)
2591 Cursors[I] = C;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002592 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002593 }
2594
Douglas Gregorbdf60622010-03-05 21:16:25 +00002595 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002596
Douglas Gregor0396f462010-03-19 05:22:59 +00002597 // Determine the region of interest, which contains all of the tokens.
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002598 SourceRange RegionOfInterest;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002599 RegionOfInterest.setBegin(cxloc::translateSourceLocation(
2600 clang_getTokenLocation(TU, Tokens[0])));
2601
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002602 SourceLocation End
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002603 = cxloc::translateSourceLocation(clang_getTokenLocation(TU,
2604 Tokens[NumTokens - 1]));
Daniel Dunbard52864b2010-02-14 10:02:57 +00002605 RegionOfInterest.setEnd(CXXUnit->getPreprocessor().getLocForEndOfToken(End));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002606
Douglas Gregor0396f462010-03-19 05:22:59 +00002607 // A mapping from the source locations found when re-lexing or traversing the
2608 // region of interest to the corresponding cursors.
2609 AnnotateTokensData Annotated;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002610
2611 // Relex the tokens within the source range to look for preprocessing
Douglas Gregor0396f462010-03-19 05:22:59 +00002612 // directives.
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002613 SourceManager &SourceMgr = CXXUnit->getSourceManager();
2614 std::pair<FileID, unsigned> BeginLocInfo
2615 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
2616 std::pair<FileID, unsigned> EndLocInfo
2617 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002618
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002619 llvm::StringRef Buffer;
Douglas Gregor0396f462010-03-19 05:22:59 +00002620 bool Invalid = false;
2621 if (BeginLocInfo.first == EndLocInfo.first &&
2622 ((Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid)),true) &&
2623 !Invalid) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002624 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
2625 CXXUnit->getASTContext().getLangOptions(),
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002626 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002627 Buffer.end());
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002628 Lex.SetCommentRetentionState(true);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002629
2630 // Lex tokens in raw mode until we hit the end of the range, to avoid
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002631 // entering #includes or expanding macros.
Douglas Gregor48072312010-03-18 15:23:44 +00002632 while (true) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002633 Token Tok;
2634 Lex.LexFromRawLexer(Tok);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002635
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002636 reprocess:
2637 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
2638 // We have found a preprocessing directive. Gobble it up so that we
2639 // don't see it while preprocessing these tokens later, but keep track of
2640 // all of the token locations inside this preprocessing directive so that
2641 // we can annotate them appropriately.
2642 //
2643 // FIXME: Some simple tests here could identify macro definitions and
2644 // #undefs, to provide specific cursor kinds for those.
2645 std::vector<SourceLocation> Locations;
2646 do {
2647 Locations.push_back(Tok.getLocation());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002648 Lex.LexFromRawLexer(Tok);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002649 } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002650
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002651 using namespace cxcursor;
2652 CXCursor Cursor
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002653 = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
2654 Locations.back()),
Ted Kremenek6db61092010-05-05 00:55:15 +00002655 CXXUnit);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002656 for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
2657 Annotated[Locations[I].getRawEncoding()] = Cursor;
2658 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002659
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002660 if (Tok.isAtStartOfLine())
2661 goto reprocess;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002662
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002663 continue;
2664 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002665
Douglas Gregor48072312010-03-18 15:23:44 +00002666 if (Tok.is(tok::eof))
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002667 break;
2668 }
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002669 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002670
Douglas Gregor0396f462010-03-19 05:22:59 +00002671 // Annotate all of the source locations in the region of interest that map to
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002672 // a specific cursor.
2673 AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens,
2674 CXXUnit, RegionOfInterest);
2675 W.AnnotateTokens(clang_getTranslationUnitCursor(CXXUnit));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002676}
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002677} // end: extern "C"
2678
2679//===----------------------------------------------------------------------===//
Ted Kremenek16b42592010-03-03 06:36:57 +00002680// Operations for querying linkage of a cursor.
2681//===----------------------------------------------------------------------===//
2682
2683extern "C" {
2684CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
Douglas Gregor0396f462010-03-19 05:22:59 +00002685 if (!clang_isDeclaration(cursor.kind))
2686 return CXLinkage_Invalid;
2687
Ted Kremenek16b42592010-03-03 06:36:57 +00002688 Decl *D = cxcursor::getCursorDecl(cursor);
2689 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
2690 switch (ND->getLinkage()) {
2691 case NoLinkage: return CXLinkage_NoLinkage;
2692 case InternalLinkage: return CXLinkage_Internal;
2693 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
2694 case ExternalLinkage: return CXLinkage_External;
2695 };
2696
2697 return CXLinkage_Invalid;
2698}
2699} // end: extern "C"
2700
2701//===----------------------------------------------------------------------===//
Ted Kremenek45e1dae2010-04-12 21:22:16 +00002702// Operations for querying language of a cursor.
2703//===----------------------------------------------------------------------===//
2704
2705static CXLanguageKind getDeclLanguage(const Decl *D) {
2706 switch (D->getKind()) {
2707 default:
2708 break;
2709 case Decl::ImplicitParam:
2710 case Decl::ObjCAtDefsField:
2711 case Decl::ObjCCategory:
2712 case Decl::ObjCCategoryImpl:
2713 case Decl::ObjCClass:
2714 case Decl::ObjCCompatibleAlias:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00002715 case Decl::ObjCForwardProtocol:
2716 case Decl::ObjCImplementation:
2717 case Decl::ObjCInterface:
2718 case Decl::ObjCIvar:
2719 case Decl::ObjCMethod:
2720 case Decl::ObjCProperty:
2721 case Decl::ObjCPropertyImpl:
2722 case Decl::ObjCProtocol:
2723 return CXLanguage_ObjC;
2724 case Decl::CXXConstructor:
2725 case Decl::CXXConversion:
2726 case Decl::CXXDestructor:
2727 case Decl::CXXMethod:
2728 case Decl::CXXRecord:
2729 case Decl::ClassTemplate:
2730 case Decl::ClassTemplatePartialSpecialization:
2731 case Decl::ClassTemplateSpecialization:
2732 case Decl::Friend:
2733 case Decl::FriendTemplate:
2734 case Decl::FunctionTemplate:
2735 case Decl::LinkageSpec:
2736 case Decl::Namespace:
2737 case Decl::NamespaceAlias:
2738 case Decl::NonTypeTemplateParm:
2739 case Decl::StaticAssert:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00002740 case Decl::TemplateTemplateParm:
2741 case Decl::TemplateTypeParm:
2742 case Decl::UnresolvedUsingTypename:
2743 case Decl::UnresolvedUsingValue:
2744 case Decl::Using:
2745 case Decl::UsingDirective:
2746 case Decl::UsingShadow:
2747 return CXLanguage_CPlusPlus;
2748 }
2749
2750 return CXLanguage_C;
2751}
2752
2753extern "C" {
2754CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
2755 if (clang_isDeclaration(cursor.kind))
2756 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
2757
2758 return CXLanguage_Invalid;
2759}
2760} // end: extern "C"
2761
2762//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00002763// CXString Operations.
2764//===----------------------------------------------------------------------===//
2765
2766extern "C" {
2767const char *clang_getCString(CXString string) {
2768 return string.Spelling;
2769}
2770
2771void clang_disposeString(CXString string) {
2772 if (string.MustFreeString && string.Spelling)
2773 free((void*)string.Spelling);
2774}
Ted Kremenek04bb7162010-01-22 22:44:15 +00002775
Ted Kremenekfb480492010-01-13 21:46:36 +00002776} // end: extern "C"
Ted Kremenek04bb7162010-01-22 22:44:15 +00002777
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002778namespace clang { namespace cxstring {
2779CXString createCXString(const char *String, bool DupString){
2780 CXString Str;
2781 if (DupString) {
2782 Str.Spelling = strdup(String);
2783 Str.MustFreeString = 1;
2784 } else {
2785 Str.Spelling = String;
2786 Str.MustFreeString = 0;
2787 }
2788 return Str;
2789}
2790
2791CXString createCXString(llvm::StringRef String, bool DupString) {
2792 CXString Result;
2793 if (DupString || (!String.empty() && String.data()[String.size()] != 0)) {
2794 char *Spelling = (char *)malloc(String.size() + 1);
2795 memmove(Spelling, String.data(), String.size());
2796 Spelling[String.size()] = 0;
2797 Result.Spelling = Spelling;
2798 Result.MustFreeString = 1;
2799 } else {
2800 Result.Spelling = String.data();
2801 Result.MustFreeString = 0;
2802 }
2803 return Result;
2804}
2805}}
2806
Ted Kremenek04bb7162010-01-22 22:44:15 +00002807//===----------------------------------------------------------------------===//
2808// Misc. utility functions.
2809//===----------------------------------------------------------------------===//
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002810
Ted Kremenek04bb7162010-01-22 22:44:15 +00002811extern "C" {
2812
Ted Kremeneka2a9d6e2010-02-12 22:54:40 +00002813CXString clang_getClangVersion() {
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002814 return createCXString(getClangFullVersion());
Ted Kremenek04bb7162010-01-22 22:44:15 +00002815}
2816
2817} // end: extern "C"