blob: ef802f574bf465c4928dc65f83b21a7456b5558a [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
Steve Naroff89922f82009-08-31 00:59:03 +0000242public:
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000243 CursorVisitor(ASTUnit *TU, CXCursorVisitor Visitor, CXClientData ClientData,
244 unsigned MaxPCHLevel,
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000245 SourceRange RegionOfInterest = SourceRange())
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000246 : TU(TU), Visitor(Visitor), ClientData(ClientData),
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000247 MaxPCHLevel(MaxPCHLevel), RegionOfInterest(RegionOfInterest)
Douglas Gregorb1373d02010-01-20 20:59:29 +0000248 {
249 Parent.kind = CXCursor_NoDeclFound;
250 Parent.data[0] = 0;
251 Parent.data[1] = 0;
252 Parent.data[2] = 0;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000253 StmtParent = 0;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000254 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000255
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000256 bool Visit(CXCursor Cursor, bool CheckedRegionOfInterest = false);
Douglas Gregor788f5a12010-03-20 00:41:21 +0000257
258 std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
259 getPreprocessedEntities();
260
Douglas Gregorb1373d02010-01-20 20:59:29 +0000261 bool VisitChildren(CXCursor Parent);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000262
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000263 // Declaration visitors
Ted Kremenek09dfa372010-02-18 05:46:33 +0000264 bool VisitAttributes(Decl *D);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000265 bool VisitBlockDecl(BlockDecl *B);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000266 bool VisitDeclContext(DeclContext *DC);
Ted Kremenek4540c9c2010-02-18 18:47:08 +0000267 bool VisitTranslationUnitDecl(TranslationUnitDecl *D);
268 bool VisitTypedefDecl(TypedefDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000269 bool VisitTagDecl(TagDecl *D);
270 bool VisitEnumConstantDecl(EnumConstantDecl *D);
271 bool VisitDeclaratorDecl(DeclaratorDecl *DD);
272 bool VisitFunctionDecl(FunctionDecl *ND);
273 bool VisitFieldDecl(FieldDecl *D);
Ted Kremenek4540c9c2010-02-18 18:47:08 +0000274 bool VisitVarDecl(VarDecl *);
Ted Kremenek79758f62010-02-18 22:36:18 +0000275 bool VisitObjCMethodDecl(ObjCMethodDecl *ND);
276 bool VisitObjCContainerDecl(ObjCContainerDecl *D);
277 bool VisitObjCCategoryDecl(ObjCCategoryDecl *ND);
278 bool VisitObjCProtocolDecl(ObjCProtocolDecl *PID);
279 bool VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
280 bool VisitObjCImplDecl(ObjCImplDecl *D);
281 bool VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
282 bool VisitObjCImplementationDecl(ObjCImplementationDecl *D);
283 // FIXME: ObjCPropertyDecl requires TypeSourceInfo, getter/setter locations,
284 // etc.
285 // FIXME: ObjCCompatibleAliasDecl requires aliased-class locations.
286 bool VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D);
287 bool VisitObjCClassDecl(ObjCClassDecl *D);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000288
289 // Type visitors
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000290 // FIXME: QualifiedTypeLoc doesn't provide any location information
291 bool VisitBuiltinTypeLoc(BuiltinTypeLoc TL);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000292 bool VisitTypedefTypeLoc(TypedefTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000293 bool VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL);
294 bool VisitTagTypeLoc(TagTypeLoc TL);
295 // FIXME: TemplateTypeParmTypeLoc doesn't provide any location information
296 bool VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL);
297 bool VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL);
298 bool VisitPointerTypeLoc(PointerTypeLoc TL);
299 bool VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL);
300 bool VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL);
301 bool VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL);
302 bool VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL);
303 bool VisitFunctionTypeLoc(FunctionTypeLoc TL);
304 bool VisitArrayTypeLoc(ArrayTypeLoc TL);
Douglas Gregor2332c112010-01-21 20:48:56 +0000305 // FIXME: Implement for TemplateSpecializationTypeLoc
306 // FIXME: Implement visitors here when the unimplemented TypeLocs get
307 // implemented
308 bool VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL);
309 bool VisitTypeOfTypeLoc(TypeOfTypeLoc TL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000310
Douglas Gregora59e3902010-01-21 23:27:09 +0000311 // Statement visitors
312 bool VisitStmt(Stmt *S);
313 bool VisitDeclStmt(DeclStmt *S);
Douglas Gregorf5bab412010-01-22 01:00:11 +0000314 // FIXME: LabelStmt label?
315 bool VisitIfStmt(IfStmt *S);
316 bool VisitSwitchStmt(SwitchStmt *S);
Douglas Gregor263b47b2010-01-25 16:12:32 +0000317 bool VisitWhileStmt(WhileStmt *S);
318 bool VisitForStmt(ForStmt *S);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000319
Douglas Gregor336fd812010-01-23 00:40:08 +0000320 // Expression visitors
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000321 bool VisitBlockExpr(BlockExpr *B);
Douglas Gregor336fd812010-01-23 00:40:08 +0000322 bool VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000323 bool VisitExplicitCastExpr(ExplicitCastExpr *E);
Douglas Gregorc2350e52010-03-08 16:40:19 +0000324 bool VisitObjCMessageExpr(ObjCMessageExpr *E);
Douglas Gregor81d34662010-04-20 15:39:42 +0000325 bool VisitObjCEncodeExpr(ObjCEncodeExpr *E);
Douglas Gregor8ecdb652010-04-28 22:16:22 +0000326 bool VisitOffsetOfExpr(OffsetOfExpr *E);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000327 bool VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E);
Steve Naroff89922f82009-08-31 00:59:03 +0000328};
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000329
Ted Kremenekab188932010-01-05 19:32:54 +0000330} // end anonymous namespace
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000331
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000332RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000333 return RangeCompare(TU->getSourceManager(), R, RegionOfInterest);
334}
335
Douglas Gregorb1373d02010-01-20 20:59:29 +0000336/// \brief Visit the given cursor and, if requested by the visitor,
337/// its children.
338///
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000339/// \param Cursor the cursor to visit.
340///
341/// \param CheckRegionOfInterest if true, then the caller already checked that
342/// this cursor is within the region of interest.
343///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000344/// \returns true if the visitation should be aborted, false if it
345/// should continue.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000346bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
Douglas Gregorb1373d02010-01-20 20:59:29 +0000347 if (clang_isInvalid(Cursor.kind))
348 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000349
Douglas Gregorb1373d02010-01-20 20:59:29 +0000350 if (clang_isDeclaration(Cursor.kind)) {
351 Decl *D = getCursorDecl(Cursor);
352 assert(D && "Invalid declaration cursor");
353 if (D->getPCHLevel() > MaxPCHLevel)
354 return false;
355
356 if (D->isImplicit())
357 return false;
358 }
359
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000360 // If we have a range of interest, and this cursor doesn't intersect with it,
361 // we're done.
362 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
Daniel Dunbarf408f322010-02-14 08:32:05 +0000363 SourceRange Range =
364 cxloc::translateCXSourceRange(clang_getCursorExtent(Cursor));
365 if (Range.isInvalid() || CompareRegionOfInterest(Range))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000366 return false;
367 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000368
Douglas Gregorb1373d02010-01-20 20:59:29 +0000369 switch (Visitor(Cursor, Parent, ClientData)) {
370 case CXChildVisit_Break:
371 return true;
372
373 case CXChildVisit_Continue:
374 return false;
375
376 case CXChildVisit_Recurse:
377 return VisitChildren(Cursor);
378 }
379
Douglas Gregorfd643772010-01-25 16:45:46 +0000380 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000381}
382
Douglas Gregor788f5a12010-03-20 00:41:21 +0000383std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
384CursorVisitor::getPreprocessedEntities() {
385 PreprocessingRecord &PPRec
386 = *TU->getPreprocessor().getPreprocessingRecord();
387
388 bool OnlyLocalDecls
389 = !TU->isMainFileAST() && TU->getOnlyLocalDecls();
390
391 // There is no region of interest; we have to walk everything.
392 if (RegionOfInterest.isInvalid())
393 return std::make_pair(PPRec.begin(OnlyLocalDecls),
394 PPRec.end(OnlyLocalDecls));
395
396 // Find the file in which the region of interest lands.
397 SourceManager &SM = TU->getSourceManager();
398 std::pair<FileID, unsigned> Begin
399 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getBegin());
400 std::pair<FileID, unsigned> End
401 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getEnd());
402
403 // The region of interest spans files; we have to walk everything.
404 if (Begin.first != End.first)
405 return std::make_pair(PPRec.begin(OnlyLocalDecls),
406 PPRec.end(OnlyLocalDecls));
407
408 ASTUnit::PreprocessedEntitiesByFileMap &ByFileMap
409 = TU->getPreprocessedEntitiesByFile();
410 if (ByFileMap.empty()) {
411 // Build the mapping from files to sets of preprocessed entities.
412 for (PreprocessingRecord::iterator E = PPRec.begin(OnlyLocalDecls),
413 EEnd = PPRec.end(OnlyLocalDecls);
414 E != EEnd; ++E) {
415 std::pair<FileID, unsigned> P
416 = SM.getDecomposedInstantiationLoc((*E)->getSourceRange().getBegin());
417 ByFileMap[P.first].push_back(*E);
418 }
419 }
420
421 return std::make_pair(ByFileMap[Begin.first].begin(),
422 ByFileMap[Begin.first].end());
423}
424
Douglas Gregorb1373d02010-01-20 20:59:29 +0000425/// \brief Visit the children of the given cursor.
426///
427/// \returns true if the visitation should be aborted, false if it
428/// should continue.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000429bool CursorVisitor::VisitChildren(CXCursor Cursor) {
Douglas Gregora59e3902010-01-21 23:27:09 +0000430 if (clang_isReference(Cursor.kind)) {
431 // By definition, references have no children.
432 return false;
433 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000434
435 // Set the Parent field to Cursor, then back to its old value once we're
Douglas Gregorb1373d02010-01-20 20:59:29 +0000436 // done.
437 class SetParentRAII {
438 CXCursor &Parent;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000439 Decl *&StmtParent;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000440 CXCursor OldParent;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000441
Douglas Gregorb1373d02010-01-20 20:59:29 +0000442 public:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000443 SetParentRAII(CXCursor &Parent, Decl *&StmtParent, CXCursor NewParent)
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000444 : Parent(Parent), StmtParent(StmtParent), OldParent(Parent)
Douglas Gregorb1373d02010-01-20 20:59:29 +0000445 {
446 Parent = NewParent;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000447 if (clang_isDeclaration(Parent.kind))
448 StmtParent = getCursorDecl(Parent);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000449 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000450
Douglas Gregorb1373d02010-01-20 20:59:29 +0000451 ~SetParentRAII() {
452 Parent = OldParent;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000453 if (clang_isDeclaration(Parent.kind))
454 StmtParent = getCursorDecl(Parent);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000455 }
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000456 } SetParent(Parent, StmtParent, Cursor);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000457
Douglas Gregorb1373d02010-01-20 20:59:29 +0000458 if (clang_isDeclaration(Cursor.kind)) {
459 Decl *D = getCursorDecl(Cursor);
460 assert(D && "Invalid declaration cursor");
Ted Kremenek539311e2010-02-18 18:47:01 +0000461 return VisitAttributes(D) || Visit(D);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000462 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000463
Douglas Gregora59e3902010-01-21 23:27:09 +0000464 if (clang_isStatement(Cursor.kind))
465 return Visit(getCursorStmt(Cursor));
466 if (clang_isExpression(Cursor.kind))
467 return Visit(getCursorExpr(Cursor));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000468
Douglas Gregorb1373d02010-01-20 20:59:29 +0000469 if (clang_isTranslationUnit(Cursor.kind)) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000470 ASTUnit *CXXUnit = getCursorASTUnit(Cursor);
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000471 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
472 RegionOfInterest.isInvalid()) {
Douglas Gregor7b691f332010-01-20 21:13:59 +0000473 const std::vector<Decl*> &TLDs = CXXUnit->getTopLevelDecls();
474 for (std::vector<Decl*>::const_iterator it = TLDs.begin(),
475 ie = TLDs.end(); it != ie; ++it) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000476 if (Visit(MakeCXCursor(*it, CXXUnit), true))
Douglas Gregor7b691f332010-01-20 21:13:59 +0000477 return true;
478 }
Douglas Gregor0396f462010-03-19 05:22:59 +0000479 } else if (VisitDeclContext(
480 CXXUnit->getASTContext().getTranslationUnitDecl()))
481 return true;
Bob Wilson3178cb62010-03-19 03:57:57 +0000482
Douglas Gregor0396f462010-03-19 05:22:59 +0000483 // Walk the preprocessing record.
Daniel Dunbar8de30ff2010-03-20 01:11:56 +0000484 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000485 // FIXME: Once we have the ability to deserialize a preprocessing record,
486 // do so.
Douglas Gregor788f5a12010-03-20 00:41:21 +0000487 PreprocessingRecord::iterator E, EEnd;
488 for (llvm::tie(E, EEnd) = getPreprocessedEntities(); E != EEnd; ++E) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000489 if (MacroInstantiation *MI = dyn_cast<MacroInstantiation>(*E)) {
490 if (Visit(MakeMacroInstantiationCursor(MI, CXXUnit)))
491 return true;
Douglas Gregor788f5a12010-03-20 00:41:21 +0000492
Douglas Gregor0396f462010-03-19 05:22:59 +0000493 continue;
494 }
495
496 if (MacroDefinition *MD = dyn_cast<MacroDefinition>(*E)) {
497 if (Visit(MakeMacroDefinitionCursor(MD, CXXUnit)))
498 return true;
499
500 continue;
501 }
502 }
503 }
Douglas Gregor7b691f332010-01-20 21:13:59 +0000504 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000505 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000506
Douglas Gregorb1373d02010-01-20 20:59:29 +0000507 // Nothing to visit at the moment.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000508 return false;
509}
510
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000511bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
512 for (BlockDecl::param_iterator I=B->param_begin(), E=B->param_end(); I!=E;++I)
513 if (Decl *D = *I)
514 if (Visit(D))
515 return true;
516
517 return Visit(MakeCXCursor(B->getBody(), StmtParent, TU));
518}
519
Douglas Gregorb1373d02010-01-20 20:59:29 +0000520bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000521 for (DeclContext::decl_iterator
Douglas Gregorb1373d02010-01-20 20:59:29 +0000522 I = DC->decls_begin(), E = DC->decls_end(); I != E; ++I) {
Ted Kremenek09dfa372010-02-18 05:46:33 +0000523
Daniel Dunbard52864b2010-02-14 10:02:57 +0000524 CXCursor Cursor = MakeCXCursor(*I, TU);
525
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000526 if (RegionOfInterest.isValid()) {
Daniel Dunbard52864b2010-02-14 10:02:57 +0000527 SourceRange Range =
528 cxloc::translateCXSourceRange(clang_getCursorExtent(Cursor));
529 if (Range.isInvalid())
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000530 continue;
Daniel Dunbard52864b2010-02-14 10:02:57 +0000531
532 switch (CompareRegionOfInterest(Range)) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000533 case RangeBefore:
534 // This declaration comes before the region of interest; skip it.
535 continue;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000536
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000537 case RangeAfter:
538 // This declaration comes after the region of interest; we're done.
539 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000540
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000541 case RangeOverlap:
542 // This declaration overlaps the region of interest; visit it.
543 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000544 }
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000545 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000546
Daniel Dunbard52864b2010-02-14 10:02:57 +0000547 if (Visit(Cursor, true))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000548 return true;
549 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000550
Douglas Gregorb1373d02010-01-20 20:59:29 +0000551 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000552}
553
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000554bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
555 llvm_unreachable("Translation units are visited directly by Visit()");
556 return false;
557}
558
559bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
560 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
561 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000562
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000563 return false;
564}
565
566bool CursorVisitor::VisitTagDecl(TagDecl *D) {
567 return VisitDeclContext(D);
568}
569
570bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
571 if (Expr *Init = D->getInitExpr())
572 return Visit(MakeCXCursor(Init, StmtParent, TU));
573 return false;
574}
575
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000576bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
577 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
578 if (Visit(TSInfo->getTypeLoc()))
579 return true;
580
581 return false;
582}
583
Douglas Gregorb1373d02010-01-20 20:59:29 +0000584bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000585 if (VisitDeclaratorDecl(ND))
586 return true;
587
Douglas Gregora59e3902010-01-21 23:27:09 +0000588 if (ND->isThisDeclarationADefinition() &&
589 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
590 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000591
Douglas Gregorb1373d02010-01-20 20:59:29 +0000592 return false;
593}
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000594
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000595bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
596 if (VisitDeclaratorDecl(D))
597 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000598
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000599 if (Expr *BitWidth = D->getBitWidth())
600 return Visit(MakeCXCursor(BitWidth, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000601
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000602 return false;
603}
604
605bool CursorVisitor::VisitVarDecl(VarDecl *D) {
606 if (VisitDeclaratorDecl(D))
607 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000608
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000609 if (Expr *Init = D->getInit())
610 return Visit(MakeCXCursor(Init, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000611
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000612 return false;
613}
614
615bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
Douglas Gregor4bc1cb62010-03-08 14:59:44 +0000616 if (TypeSourceInfo *TSInfo = ND->getResultTypeSourceInfo())
617 if (Visit(TSInfo->getTypeLoc()))
618 return true;
619
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000620 for (ObjCMethodDecl::param_iterator P = ND->param_begin(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000621 PEnd = ND->param_end();
622 P != PEnd; ++P) {
623 if (Visit(MakeCXCursor(*P, TU)))
624 return true;
625 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000626
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000627 if (ND->isThisDeclarationADefinition() &&
628 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
629 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000630
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000631 return false;
632}
633
Douglas Gregora59e3902010-01-21 23:27:09 +0000634bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
635 return VisitDeclContext(D);
636}
637
Douglas Gregorb1373d02010-01-20 20:59:29 +0000638bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000639 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
640 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000641 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000642
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000643 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
644 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
645 E = ND->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000646 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000647 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000648
Douglas Gregora59e3902010-01-21 23:27:09 +0000649 return VisitObjCContainerDecl(ND);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000650}
651
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000652bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
653 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
654 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
655 E = PID->protocol_end(); I != E; ++I, ++PL)
656 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
657 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000658
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000659 return VisitObjCContainerDecl(PID);
660}
661
Douglas Gregorb1373d02010-01-20 20:59:29 +0000662bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000663 // Issue callbacks for super class.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000664 if (D->getSuperClass() &&
665 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000666 D->getSuperClassLoc(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000667 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000668 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000669
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000670 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
671 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
672 E = D->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000673 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000674 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000675
Douglas Gregora59e3902010-01-21 23:27:09 +0000676 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000677}
678
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000679bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
680 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000681}
682
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000683bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
Ted Kremenekebfa3392010-03-19 20:39:03 +0000684 // 'ID' could be null when dealing with invalid code.
685 if (ObjCInterfaceDecl *ID = D->getClassInterface())
686 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
687 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000688
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000689 return VisitObjCImplDecl(D);
690}
691
692bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
693#if 0
694 // Issue callbacks for super class.
695 // FIXME: No source location information!
696 if (D->getSuperClass() &&
697 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000698 D->getSuperClassLoc(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000699 TU)))
700 return true;
701#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000702
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000703 return VisitObjCImplDecl(D);
704}
705
706bool CursorVisitor::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D) {
707 ObjCForwardProtocolDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
708 for (ObjCForwardProtocolDecl::protocol_iterator I = D->protocol_begin(),
709 E = D->protocol_end();
710 I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000711 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000712 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000713
714 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000715}
716
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000717bool CursorVisitor::VisitObjCClassDecl(ObjCClassDecl *D) {
718 for (ObjCClassDecl::iterator C = D->begin(), CEnd = D->end(); C != CEnd; ++C)
719 if (Visit(MakeCursorObjCClassRef(C->getInterface(), C->getLocation(), TU)))
720 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000721
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000722 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000723}
724
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000725bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
726 ASTContext &Context = TU->getASTContext();
727
728 // Some builtin types (such as Objective-C's "id", "sel", and
729 // "Class") have associated declarations. Create cursors for those.
730 QualType VisitType;
731 switch (TL.getType()->getAs<BuiltinType>()->getKind()) {
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000732 case BuiltinType::Void:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000733 case BuiltinType::Bool:
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000734 case BuiltinType::Char_U:
735 case BuiltinType::UChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000736 case BuiltinType::Char16:
737 case BuiltinType::Char32:
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000738 case BuiltinType::UShort:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000739 case BuiltinType::UInt:
740 case BuiltinType::ULong:
741 case BuiltinType::ULongLong:
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000742 case BuiltinType::UInt128:
743 case BuiltinType::Char_S:
744 case BuiltinType::SChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000745 case BuiltinType::WChar:
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000746 case BuiltinType::Short:
747 case BuiltinType::Int:
748 case BuiltinType::Long:
749 case BuiltinType::LongLong:
750 case BuiltinType::Int128:
751 case BuiltinType::Float:
752 case BuiltinType::Double:
753 case BuiltinType::LongDouble:
754 case BuiltinType::NullPtr:
755 case BuiltinType::Overload:
756 case BuiltinType::Dependent:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000757 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000758
759 case BuiltinType::UndeducedAuto: // FIXME: Deserves a cursor?
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000760 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000761
Ted Kremenekc4174cc2010-02-18 18:52:18 +0000762 case BuiltinType::ObjCId:
763 VisitType = Context.getObjCIdType();
764 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000765
766 case BuiltinType::ObjCClass:
767 VisitType = Context.getObjCClassType();
768 break;
769
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000770 case BuiltinType::ObjCSel:
771 VisitType = Context.getObjCSelType();
772 break;
773 }
774
775 if (!VisitType.isNull()) {
776 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000777 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000778 TU));
779 }
780
781 return false;
782}
783
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000784bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
785 return Visit(MakeCursorTypeRef(TL.getTypedefDecl(), TL.getNameLoc(), TU));
786}
787
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000788bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
789 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
790}
791
792bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
793 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
794}
795
796bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
797 if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
798 return true;
799
800 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
801 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
802 TU)))
803 return true;
804 }
805
806 return false;
807}
808
809bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
810 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseTypeLoc()))
811 return true;
812
813 if (TL.hasProtocolsAsWritten()) {
814 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000815 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I),
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000816 TL.getProtocolLoc(I),
817 TU)))
818 return true;
819 }
820 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000821
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000822 return false;
823}
824
825bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
826 return Visit(TL.getPointeeLoc());
827}
828
829bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
830 return Visit(TL.getPointeeLoc());
831}
832
833bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
834 return Visit(TL.getPointeeLoc());
835}
836
837bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000838 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000839}
840
841bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000842 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000843}
844
845bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
846 if (Visit(TL.getResultLoc()))
847 return true;
848
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000849 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
Ted Kremenek5dbacb42010-04-07 00:27:13 +0000850 if (Decl *D = TL.getArg(I))
851 if (Visit(MakeCXCursor(D, TU)))
852 return true;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000853
854 return false;
855}
856
857bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
858 if (Visit(TL.getElementLoc()))
859 return true;
860
861 if (Expr *Size = TL.getSizeExpr())
862 return Visit(MakeCXCursor(Size, StmtParent, TU));
863
864 return false;
865}
866
Douglas Gregor2332c112010-01-21 20:48:56 +0000867bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
868 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
869}
870
871bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
872 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
873 return Visit(TSInfo->getTypeLoc());
874
875 return false;
876}
877
Douglas Gregora59e3902010-01-21 23:27:09 +0000878bool CursorVisitor::VisitStmt(Stmt *S) {
879 for (Stmt::child_iterator Child = S->child_begin(), ChildEnd = S->child_end();
880 Child != ChildEnd; ++Child) {
Daniel Dunbar54d67ca2010-01-25 00:40:30 +0000881 if (*Child && Visit(MakeCXCursor(*Child, StmtParent, TU)))
Douglas Gregora59e3902010-01-21 23:27:09 +0000882 return true;
883 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000884
Douglas Gregora59e3902010-01-21 23:27:09 +0000885 return false;
886}
887
888bool CursorVisitor::VisitDeclStmt(DeclStmt *S) {
889 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
890 D != DEnd; ++D) {
Douglas Gregor263b47b2010-01-25 16:12:32 +0000891 if (*D && Visit(MakeCXCursor(*D, TU)))
Douglas Gregora59e3902010-01-21 23:27:09 +0000892 return true;
893 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000894
Douglas Gregora59e3902010-01-21 23:27:09 +0000895 return false;
896}
897
Douglas Gregorf5bab412010-01-22 01:00:11 +0000898bool CursorVisitor::VisitIfStmt(IfStmt *S) {
899 if (VarDecl *Var = S->getConditionVariable()) {
900 if (Visit(MakeCXCursor(Var, TU)))
901 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000902 }
903
Douglas Gregor263b47b2010-01-25 16:12:32 +0000904 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
905 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +0000906 if (S->getThen() && Visit(MakeCXCursor(S->getThen(), StmtParent, TU)))
907 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +0000908 if (S->getElse() && Visit(MakeCXCursor(S->getElse(), StmtParent, TU)))
909 return true;
910
911 return false;
912}
913
914bool CursorVisitor::VisitSwitchStmt(SwitchStmt *S) {
915 if (VarDecl *Var = S->getConditionVariable()) {
916 if (Visit(MakeCXCursor(Var, TU)))
917 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000918 }
919
Douglas Gregor263b47b2010-01-25 16:12:32 +0000920 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
921 return true;
922 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
923 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000924
Douglas Gregor263b47b2010-01-25 16:12:32 +0000925 return false;
926}
927
928bool CursorVisitor::VisitWhileStmt(WhileStmt *S) {
929 if (VarDecl *Var = S->getConditionVariable()) {
930 if (Visit(MakeCXCursor(Var, TU)))
931 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000932 }
933
Douglas Gregor263b47b2010-01-25 16:12:32 +0000934 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
935 return true;
936 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
Douglas Gregorf5bab412010-01-22 01:00:11 +0000937 return true;
938
Douglas Gregor263b47b2010-01-25 16:12:32 +0000939 return false;
940}
941
942bool CursorVisitor::VisitForStmt(ForStmt *S) {
943 if (S->getInit() && Visit(MakeCXCursor(S->getInit(), StmtParent, TU)))
944 return true;
945 if (VarDecl *Var = S->getConditionVariable()) {
946 if (Visit(MakeCXCursor(Var, TU)))
947 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000948 }
949
Douglas Gregor263b47b2010-01-25 16:12:32 +0000950 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
951 return true;
952 if (S->getInc() && Visit(MakeCXCursor(S->getInc(), StmtParent, TU)))
953 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +0000954 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
955 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000956
Douglas Gregorf5bab412010-01-22 01:00:11 +0000957 return false;
958}
959
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000960bool CursorVisitor::VisitBlockExpr(BlockExpr *B) {
961 return Visit(B->getBlockDecl());
962}
963
Douglas Gregor8ecdb652010-04-28 22:16:22 +0000964bool CursorVisitor::VisitOffsetOfExpr(OffsetOfExpr *E) {
965 // FIXME: Visit fields as well?
966 if (Visit(E->getTypeSourceInfo()->getTypeLoc()))
967 return true;
968
969 return VisitExpr(E);
970}
971
Douglas Gregor336fd812010-01-23 00:40:08 +0000972bool CursorVisitor::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E) {
973 if (E->isArgumentType()) {
974 if (TypeSourceInfo *TSInfo = E->getArgumentTypeInfo())
975 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000976
Douglas Gregor336fd812010-01-23 00:40:08 +0000977 return false;
978 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000979
Douglas Gregor336fd812010-01-23 00:40:08 +0000980 return VisitExpr(E);
981}
982
983bool CursorVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
984 if (TypeSourceInfo *TSInfo = E->getTypeInfoAsWritten())
985 if (Visit(TSInfo->getTypeLoc()))
986 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000987
Douglas Gregor336fd812010-01-23 00:40:08 +0000988 return VisitCastExpr(E);
989}
990
991bool CursorVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
992 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
993 if (Visit(TSInfo->getTypeLoc()))
994 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000995
Douglas Gregor336fd812010-01-23 00:40:08 +0000996 return VisitExpr(E);
997}
998
Douglas Gregorc2350e52010-03-08 16:40:19 +0000999bool CursorVisitor::VisitObjCMessageExpr(ObjCMessageExpr *E) {
Douglas Gregor04badcf2010-04-21 00:45:42 +00001000 if (TypeSourceInfo *TSInfo = E->getClassReceiverTypeInfo())
1001 if (Visit(TSInfo->getTypeLoc()))
1002 return true;
Douglas Gregorc2350e52010-03-08 16:40:19 +00001003
1004 return VisitExpr(E);
1005}
1006
Douglas Gregor81d34662010-04-20 15:39:42 +00001007bool CursorVisitor::VisitObjCEncodeExpr(ObjCEncodeExpr *E) {
1008 return Visit(E->getEncodedTypeSourceInfo()->getTypeLoc());
1009}
1010
1011
Ted Kremenek09dfa372010-02-18 05:46:33 +00001012bool CursorVisitor::VisitAttributes(Decl *D) {
1013 for (const Attr *A = D->getAttrs(); A; A = A->getNext())
1014 if (Visit(MakeCXCursor(A, D, TU)))
1015 return true;
1016
1017 return false;
1018}
1019
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00001020extern "C" {
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001021CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
1022 int displayDiagnostics) {
Douglas Gregora030b7c2010-01-22 20:35:53 +00001023 CIndexer *CIdxr = new CIndexer();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001024 if (excludeDeclarationsFromPCH)
1025 CIdxr->setOnlyLocalDecls();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001026 if (displayDiagnostics)
1027 CIdxr->setDisplayDiagnostics();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001028 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +00001029}
1030
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001031void clang_disposeIndex(CXIndex CIdx) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001032 if (CIdx)
1033 delete static_cast<CIndexer *>(CIdx);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00001034}
1035
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001036void clang_setUseExternalASTGeneration(CXIndex CIdx, int value) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001037 if (CIdx) {
1038 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
1039 CXXIdx->setUseExternalASTGeneration(value);
1040 }
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001041}
1042
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001043CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
Douglas Gregora88084b2010-02-18 18:08:43 +00001044 const char *ast_filename) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001045 if (!CIdx)
1046 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001047
Douglas Gregor7d1d49d2009-10-16 20:01:17 +00001048 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001049
Douglas Gregor28019772010-04-05 23:52:57 +00001050 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
1051 return ASTUnit::LoadFromPCHFile(ast_filename, Diags,
Douglas Gregora88084b2010-02-18 18:08:43 +00001052 CXXIdx->getOnlyLocalDecls(),
1053 0, 0, true);
Steve Naroff600866c2009-08-27 19:51:58 +00001054}
1055
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001056CXTranslationUnit
1057clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
1058 const char *source_filename,
1059 int num_command_line_args,
Douglas Gregor4db64a42010-01-23 00:14:00 +00001060 const char **command_line_args,
1061 unsigned num_unsaved_files,
Douglas Gregora88084b2010-02-18 18:08:43 +00001062 struct CXUnsavedFile *unsaved_files) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001063 if (!CIdx)
1064 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001065
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001066 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
1067
Douglas Gregor5352ac02010-01-28 00:27:43 +00001068 // Configure the diagnostics.
1069 DiagnosticOptions DiagOpts;
Douglas Gregor28019772010-04-05 23:52:57 +00001070 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
1071 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001072
Douglas Gregor4db64a42010-01-23 00:14:00 +00001073 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
1074 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattnera0a270c2010-04-05 22:42:27 +00001075 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001076 const llvm::MemoryBuffer *Buffer
Chris Lattnera0a270c2010-04-05 22:42:27 +00001077 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregor4db64a42010-01-23 00:14:00 +00001078 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
1079 Buffer));
1080 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001081
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001082 if (!CXXIdx->getUseExternalASTGeneration()) {
1083 llvm::SmallVector<const char *, 16> Args;
1084
1085 // The 'source_filename' argument is optional. If the caller does not
1086 // specify it then it is assumed that the source file is specified
1087 // in the actual argument list.
1088 if (source_filename)
1089 Args.push_back(source_filename);
1090 Args.insert(Args.end(), command_line_args,
1091 command_line_args + num_command_line_args);
Douglas Gregor94dc8f62010-03-19 16:15:56 +00001092 Args.push_back("-Xclang");
1093 Args.push_back("-detailed-preprocessing-record");
Douglas Gregor5352ac02010-01-28 00:27:43 +00001094 unsigned NumErrors = Diags->getNumErrors();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001095
Ted Kremenek29b72842010-01-07 22:49:05 +00001096#ifdef USE_CRASHTRACER
1097 ArgsCrashTracerInfo ACTI(Args);
Ted Kremenek8a8da7d2010-01-06 03:42:32 +00001098#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001099
Daniel Dunbar94220972009-12-05 02:17:18 +00001100 llvm::OwningPtr<ASTUnit> Unit(
1101 ASTUnit::LoadFromCommandLine(Args.data(), Args.data() + Args.size(),
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001102 Diags,
Daniel Dunbar869824e2009-12-13 03:46:13 +00001103 CXXIdx->getClangResourcesPath(),
Daniel Dunbar94220972009-12-05 02:17:18 +00001104 CXXIdx->getOnlyLocalDecls(),
Douglas Gregor4db64a42010-01-23 00:14:00 +00001105 RemappedFiles.data(),
Douglas Gregora88084b2010-02-18 18:08:43 +00001106 RemappedFiles.size(),
Douglas Gregor94dc8f62010-03-19 16:15:56 +00001107 /*CaptureDiagnostics=*/true));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001108
Daniel Dunbar94220972009-12-05 02:17:18 +00001109 // FIXME: Until we have broader testing, just drop the entire AST if we
1110 // encountered an error.
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001111 if (NumErrors != Diags->getNumErrors()) {
Ted Kremenek34f6a322010-03-05 22:43:29 +00001112 // Make sure to check that 'Unit' is non-NULL.
1113 if (CXXIdx->getDisplayDiagnostics() && Unit.get()) {
Douglas Gregor405634b2010-04-05 18:10:21 +00001114 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
1115 DEnd = Unit->stored_diag_end();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001116 D != DEnd; ++D) {
1117 CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOptions());
Douglas Gregor274f1902010-02-22 23:17:23 +00001118 CXString Msg = clang_formatDiagnostic(&Diag,
1119 clang_defaultDiagnosticDisplayOptions());
1120 fprintf(stderr, "%s\n", clang_getCString(Msg));
1121 clang_disposeString(Msg);
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001122 }
Douglas Gregor274f1902010-02-22 23:17:23 +00001123#ifdef LLVM_ON_WIN32
1124 // On Windows, force a flush, since there may be multiple copies of
1125 // stderr and stdout in the file system, all with different buffers
1126 // but writing to the same device.
1127 fflush(stderr);
Ted Kremenek83c51842010-03-26 01:34:51 +00001128#endif
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001129 }
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001130 }
Daniel Dunbar94220972009-12-05 02:17:18 +00001131
1132 return Unit.take();
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001133 }
1134
Ted Kremenek139ba862009-10-22 00:03:57 +00001135 // Build up the arguments for invoking 'clang'.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001136 std::vector<const char *> argv;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001137
Ted Kremenek139ba862009-10-22 00:03:57 +00001138 // First add the complete path to the 'clang' executable.
1139 llvm::sys::Path ClangPath = static_cast<CIndexer *>(CIdx)->getClangPath();
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00001140 argv.push_back(ClangPath.c_str());
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001141
Ted Kremenek139ba862009-10-22 00:03:57 +00001142 // Add the '-emit-ast' option as our execution mode for 'clang'.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001143 argv.push_back("-emit-ast");
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001144
Ted Kremenek139ba862009-10-22 00:03:57 +00001145 // The 'source_filename' argument is optional. If the caller does not
1146 // specify it then it is assumed that the source file is specified
1147 // in the actual argument list.
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001148 if (source_filename)
1149 argv.push_back(source_filename);
Ted Kremenek139ba862009-10-22 00:03:57 +00001150
Steve Naroff37b5ac22009-10-15 20:50:09 +00001151 // Generate a temporary name for the AST file.
Ted Kremenek139ba862009-10-22 00:03:57 +00001152 argv.push_back("-o");
Benjamin Kramerc2a98162010-03-13 21:22:49 +00001153 char astTmpFile[L_tmpnam];
1154 argv.push_back(tmpnam(astTmpFile));
Ted Kremenek139ba862009-10-22 00:03:57 +00001155
Douglas Gregor4db64a42010-01-23 00:14:00 +00001156 // Remap any unsaved files to temporary files.
1157 std::vector<llvm::sys::Path> TemporaryFiles;
1158 std::vector<std::string> RemapArgs;
1159 if (RemapFiles(num_unsaved_files, unsaved_files, RemapArgs, TemporaryFiles))
1160 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001161
Douglas Gregor4db64a42010-01-23 00:14:00 +00001162 // The pointers into the elements of RemapArgs are stable because we
1163 // won't be adding anything to RemapArgs after this point.
1164 for (unsigned i = 0, e = RemapArgs.size(); i != e; ++i)
1165 argv.push_back(RemapArgs[i].c_str());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001166
Ted Kremenek139ba862009-10-22 00:03:57 +00001167 // Process the compiler options, stripping off '-o', '-c', '-fsyntax-only'.
1168 for (int i = 0; i < num_command_line_args; ++i)
1169 if (const char *arg = command_line_args[i]) {
1170 if (strcmp(arg, "-o") == 0) {
1171 ++i; // Also skip the matching argument.
1172 continue;
1173 }
1174 if (strcmp(arg, "-emit-ast") == 0 ||
1175 strcmp(arg, "-c") == 0 ||
1176 strcmp(arg, "-fsyntax-only") == 0) {
1177 continue;
1178 }
1179
1180 // Keep the argument.
1181 argv.push_back(arg);
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001182 }
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001183
Douglas Gregord93256e2010-01-28 06:00:51 +00001184 // Generate a temporary name for the diagnostics file.
Benjamin Kramerc2a98162010-03-13 21:22:49 +00001185 char tmpFileResults[L_tmpnam];
1186 char *tmpResultsFileName = tmpnam(tmpFileResults);
1187 llvm::sys::Path DiagnosticsFile(tmpResultsFileName);
Douglas Gregord93256e2010-01-28 06:00:51 +00001188 TemporaryFiles.push_back(DiagnosticsFile);
1189 argv.push_back("-fdiagnostics-binary");
1190
Douglas Gregor94dc8f62010-03-19 16:15:56 +00001191 argv.push_back("-Xclang");
1192 argv.push_back("-detailed-preprocessing-record");
1193
Ted Kremenek139ba862009-10-22 00:03:57 +00001194 // Add the null terminator.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001195 argv.push_back(NULL);
1196
Ted Kremenekfeb15e32009-10-26 22:14:08 +00001197 // Invoke 'clang'.
1198 llvm::sys::Path DevNull; // leave empty, causes redirection to /dev/null
1199 // on Unix or NUL (Windows).
Ted Kremenek379afec2009-10-22 03:24:01 +00001200 std::string ErrMsg;
Douglas Gregord93256e2010-01-28 06:00:51 +00001201 const llvm::sys::Path *Redirects[] = { &DevNull, &DevNull, &DiagnosticsFile,
1202 NULL };
Ted Kremenek379afec2009-10-22 03:24:01 +00001203 llvm::sys::Program::ExecuteAndWait(ClangPath, &argv[0], /* env */ NULL,
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001204 /* redirects */ &Redirects[0],
Ted Kremenek379afec2009-10-22 03:24:01 +00001205 /* secondsToWait */ 0, /* memoryLimits */ 0, &ErrMsg);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001206
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001207 if (!ErrMsg.empty()) {
1208 std::string AllArgs;
Ted Kremenek379afec2009-10-22 03:24:01 +00001209 for (std::vector<const char*>::iterator I = argv.begin(), E = argv.end();
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001210 I != E; ++I) {
1211 AllArgs += ' ';
Ted Kremenek779e5f42009-10-26 22:08:39 +00001212 if (*I)
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001213 AllArgs += *I;
Ted Kremenek779e5f42009-10-26 22:08:39 +00001214 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001215
Daniel Dunbar32141c82010-02-23 20:23:45 +00001216 Diags->Report(diag::err_fe_invoking) << AllArgs << ErrMsg;
Ted Kremenek379afec2009-10-22 03:24:01 +00001217 }
Benjamin Kramer0829a832009-10-18 11:19:36 +00001218
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001219 ASTUnit *ATU = ASTUnit::LoadFromPCHFile(astTmpFile, Diags,
Douglas Gregor4db64a42010-01-23 00:14:00 +00001220 CXXIdx->getOnlyLocalDecls(),
Douglas Gregor4db64a42010-01-23 00:14:00 +00001221 RemappedFiles.data(),
Douglas Gregora88084b2010-02-18 18:08:43 +00001222 RemappedFiles.size(),
1223 /*CaptureDiagnostics=*/true);
Douglas Gregora88084b2010-02-18 18:08:43 +00001224 if (ATU) {
1225 LoadSerializedDiagnostics(DiagnosticsFile,
1226 num_unsaved_files, unsaved_files,
1227 ATU->getFileManager(),
1228 ATU->getSourceManager(),
Douglas Gregor405634b2010-04-05 18:10:21 +00001229 ATU->getStoredDiagnostics());
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001230 } else if (CXXIdx->getDisplayDiagnostics()) {
1231 // We failed to load the ASTUnit, but we can still deserialize the
1232 // diagnostics and emit them.
1233 FileManager FileMgr;
Douglas Gregorf715ca12010-03-16 00:06:06 +00001234 Diagnostic Diag;
1235 SourceManager SourceMgr(Diag);
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001236 // FIXME: Faked LangOpts!
1237 LangOptions LangOpts;
1238 llvm::SmallVector<StoredDiagnostic, 4> Diags;
1239 LoadSerializedDiagnostics(DiagnosticsFile,
1240 num_unsaved_files, unsaved_files,
1241 FileMgr, SourceMgr, Diags);
1242 for (llvm::SmallVector<StoredDiagnostic, 4>::iterator D = Diags.begin(),
1243 DEnd = Diags.end();
1244 D != DEnd; ++D) {
1245 CXStoredDiagnostic Diag(*D, LangOpts);
Douglas Gregor274f1902010-02-22 23:17:23 +00001246 CXString Msg = clang_formatDiagnostic(&Diag,
1247 clang_defaultDiagnosticDisplayOptions());
1248 fprintf(stderr, "%s\n", clang_getCString(Msg));
1249 clang_disposeString(Msg);
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001250 }
Douglas Gregor274f1902010-02-22 23:17:23 +00001251
1252#ifdef LLVM_ON_WIN32
1253 // On Windows, force a flush, since there may be multiple copies of
1254 // stderr and stdout in the file system, all with different buffers
1255 // but writing to the same device.
1256 fflush(stderr);
1257#endif
Douglas Gregora88084b2010-02-18 18:08:43 +00001258 }
Douglas Gregord93256e2010-01-28 06:00:51 +00001259
Douglas Gregor313e26c2010-02-18 23:35:40 +00001260 if (ATU) {
1261 // Make the translation unit responsible for destroying all temporary files.
1262 for (unsigned i = 0, e = TemporaryFiles.size(); i != e; ++i)
1263 ATU->addTemporaryFile(TemporaryFiles[i]);
1264 ATU->addTemporaryFile(llvm::sys::Path(ATU->getPCHFileName()));
1265 } else {
1266 // Destroy all of the temporary files now; they can't be referenced any
1267 // longer.
1268 llvm::sys::Path(astTmpFile).eraseFromDisk();
1269 for (unsigned i = 0, e = TemporaryFiles.size(); i != e; ++i)
1270 TemporaryFiles[i].eraseFromDisk();
1271 }
1272
Steve Naroffe19944c2009-10-15 22:23:48 +00001273 return ATU;
Steve Naroff5b7d8e22009-10-15 20:04:39 +00001274}
1275
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001276void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001277 if (CTUnit)
1278 delete static_cast<ASTUnit *>(CTUnit);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00001279}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001280
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001281CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001282 if (!CTUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001283 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001284
Steve Naroff77accc12009-09-03 18:19:54 +00001285 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001286 return createCXString(CXXUnit->getOriginalSourceFileName(), true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +00001287}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +00001288
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001289CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001290 CXCursor Result = { CXCursor_TranslationUnit, { 0, 0, TU } };
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001291 return Result;
1292}
1293
Ted Kremenekfb480492010-01-13 21:46:36 +00001294} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +00001295
Ted Kremenekfb480492010-01-13 21:46:36 +00001296//===----------------------------------------------------------------------===//
Douglas Gregor1db19de2010-01-19 21:36:55 +00001297// CXSourceLocation and CXSourceRange Operations.
1298//===----------------------------------------------------------------------===//
1299
Douglas Gregorb9790342010-01-22 21:44:22 +00001300extern "C" {
1301CXSourceLocation clang_getNullLocation() {
Douglas Gregor5352ac02010-01-28 00:27:43 +00001302 CXSourceLocation Result = { { 0, 0 }, 0 };
Douglas Gregorb9790342010-01-22 21:44:22 +00001303 return Result;
1304}
1305
1306unsigned clang_equalLocations(CXSourceLocation loc1, CXSourceLocation loc2) {
Daniel Dunbar90a6b9e2010-01-30 23:58:27 +00001307 return (loc1.ptr_data[0] == loc2.ptr_data[0] &&
1308 loc1.ptr_data[1] == loc2.ptr_data[1] &&
1309 loc1.int_data == loc2.int_data);
Douglas Gregorb9790342010-01-22 21:44:22 +00001310}
1311
1312CXSourceLocation clang_getLocation(CXTranslationUnit tu,
1313 CXFile file,
1314 unsigned line,
1315 unsigned column) {
Douglas Gregor42748ec2010-04-30 19:45:53 +00001316 if (!tu || !file)
Douglas Gregorb9790342010-01-22 21:44:22 +00001317 return clang_getNullLocation();
Douglas Gregor42748ec2010-04-30 19:45:53 +00001318
Douglas Gregorb9790342010-01-22 21:44:22 +00001319 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
1320 SourceLocation SLoc
1321 = CXXUnit->getSourceManager().getLocation(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001322 static_cast<const FileEntry *>(file),
Douglas Gregorb9790342010-01-22 21:44:22 +00001323 line, column);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001324
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00001325 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
Douglas Gregorb9790342010-01-22 21:44:22 +00001326}
1327
Douglas Gregor5352ac02010-01-28 00:27:43 +00001328CXSourceRange clang_getNullRange() {
1329 CXSourceRange Result = { { 0, 0 }, 0, 0 };
1330 return Result;
1331}
Daniel Dunbard52864b2010-02-14 10:02:57 +00001332
Douglas Gregor5352ac02010-01-28 00:27:43 +00001333CXSourceRange clang_getRange(CXSourceLocation begin, CXSourceLocation end) {
1334 if (begin.ptr_data[0] != end.ptr_data[0] ||
1335 begin.ptr_data[1] != end.ptr_data[1])
1336 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001337
1338 CXSourceRange Result = { { begin.ptr_data[0], begin.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00001339 begin.int_data, end.int_data };
Douglas Gregorb9790342010-01-22 21:44:22 +00001340 return Result;
1341}
1342
Douglas Gregor46766dc2010-01-26 19:19:08 +00001343void clang_getInstantiationLocation(CXSourceLocation location,
1344 CXFile *file,
1345 unsigned *line,
1346 unsigned *column,
1347 unsigned *offset) {
Douglas Gregor1db19de2010-01-19 21:36:55 +00001348 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
1349
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00001350 if (!location.ptr_data[0] || Loc.isInvalid()) {
Douglas Gregor46766dc2010-01-26 19:19:08 +00001351 if (file)
1352 *file = 0;
1353 if (line)
1354 *line = 0;
1355 if (column)
1356 *column = 0;
1357 if (offset)
1358 *offset = 0;
1359 return;
1360 }
1361
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00001362 const SourceManager &SM =
1363 *static_cast<const SourceManager*>(location.ptr_data[0]);
Douglas Gregor1db19de2010-01-19 21:36:55 +00001364 SourceLocation InstLoc = SM.getInstantiationLoc(Loc);
Douglas Gregor1db19de2010-01-19 21:36:55 +00001365
1366 if (file)
1367 *file = (void *)SM.getFileEntryForID(SM.getFileID(InstLoc));
1368 if (line)
1369 *line = SM.getInstantiationLineNumber(InstLoc);
1370 if (column)
1371 *column = SM.getInstantiationColumnNumber(InstLoc);
Douglas Gregore69517c2010-01-26 03:07:15 +00001372 if (offset)
Douglas Gregor46766dc2010-01-26 19:19:08 +00001373 *offset = SM.getDecomposedLoc(InstLoc).second;
Douglas Gregore69517c2010-01-26 03:07:15 +00001374}
1375
Douglas Gregor1db19de2010-01-19 21:36:55 +00001376CXSourceLocation clang_getRangeStart(CXSourceRange range) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001377 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00001378 range.begin_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00001379 return Result;
1380}
1381
1382CXSourceLocation clang_getRangeEnd(CXSourceRange range) {
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00001383 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00001384 range.end_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00001385 return Result;
1386}
1387
Douglas Gregorb9790342010-01-22 21:44:22 +00001388} // end: extern "C"
1389
Douglas Gregor1db19de2010-01-19 21:36:55 +00001390//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00001391// CXFile Operations.
1392//===----------------------------------------------------------------------===//
1393
1394extern "C" {
Ted Kremenek74844072010-02-17 00:41:20 +00001395CXString clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00001396 if (!SFile)
Ted Kremenek74844072010-02-17 00:41:20 +00001397 return createCXString(NULL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001398
Steve Naroff88145032009-10-27 14:35:18 +00001399 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Ted Kremenek74844072010-02-17 00:41:20 +00001400 return createCXString(FEnt->getName());
Steve Naroff88145032009-10-27 14:35:18 +00001401}
1402
1403time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00001404 if (!SFile)
1405 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001406
Steve Naroff88145032009-10-27 14:35:18 +00001407 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
1408 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +00001409}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001410
Douglas Gregorb9790342010-01-22 21:44:22 +00001411CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
1412 if (!tu)
1413 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001414
Douglas Gregorb9790342010-01-22 21:44:22 +00001415 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001416
Douglas Gregorb9790342010-01-22 21:44:22 +00001417 FileManager &FMgr = CXXUnit->getFileManager();
1418 const FileEntry *File = FMgr.getFile(file_name, file_name+strlen(file_name));
1419 return const_cast<FileEntry *>(File);
1420}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001421
Ted Kremenekfb480492010-01-13 21:46:36 +00001422} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +00001423
Ted Kremenekfb480492010-01-13 21:46:36 +00001424//===----------------------------------------------------------------------===//
1425// CXCursor Operations.
1426//===----------------------------------------------------------------------===//
1427
Ted Kremenekfb480492010-01-13 21:46:36 +00001428static Decl *getDeclFromExpr(Stmt *E) {
1429 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
1430 return RefExpr->getDecl();
1431 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
1432 return ME->getMemberDecl();
1433 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
1434 return RE->getDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001435
Ted Kremenekfb480492010-01-13 21:46:36 +00001436 if (CallExpr *CE = dyn_cast<CallExpr>(E))
1437 return getDeclFromExpr(CE->getCallee());
1438 if (CastExpr *CE = dyn_cast<CastExpr>(E))
1439 return getDeclFromExpr(CE->getSubExpr());
1440 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
1441 return OME->getMethodDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001442
Ted Kremenekfb480492010-01-13 21:46:36 +00001443 return 0;
1444}
1445
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00001446static SourceLocation getLocationFromExpr(Expr *E) {
1447 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
1448 return /*FIXME:*/Msg->getLeftLoc();
1449 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
1450 return DRE->getLocation();
1451 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
1452 return Member->getMemberLoc();
1453 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
1454 return Ivar->getLocation();
1455 return E->getLocStart();
1456}
1457
Ted Kremenekfb480492010-01-13 21:46:36 +00001458extern "C" {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001459
1460unsigned clang_visitChildren(CXCursor parent,
Douglas Gregorb1373d02010-01-20 20:59:29 +00001461 CXCursorVisitor visitor,
1462 CXClientData client_data) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001463 ASTUnit *CXXUnit = getCursorASTUnit(parent);
Douglas Gregorb1373d02010-01-20 20:59:29 +00001464
1465 unsigned PCHLevel = Decl::MaxPCHLevel;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001466
Douglas Gregorb1373d02010-01-20 20:59:29 +00001467 // Set the PCHLevel to filter out unwanted decls if requested.
1468 if (CXXUnit->getOnlyLocalDecls()) {
1469 PCHLevel = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001470
Douglas Gregorb1373d02010-01-20 20:59:29 +00001471 // If the main input was an AST, bump the level.
1472 if (CXXUnit->isMainFileAST())
1473 ++PCHLevel;
1474 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001475
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001476 CursorVisitor CursorVis(CXXUnit, visitor, client_data, PCHLevel);
Douglas Gregorb1373d02010-01-20 20:59:29 +00001477 return CursorVis.VisitChildren(parent);
1478}
1479
Douglas Gregor78205d42010-01-20 21:45:58 +00001480static CXString getDeclSpelling(Decl *D) {
1481 NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
1482 if (!ND)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001483 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001484
Douglas Gregor78205d42010-01-20 21:45:58 +00001485 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001486 return createCXString(OMD->getSelector().getAsString());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001487
Douglas Gregor78205d42010-01-20 21:45:58 +00001488 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
1489 // No, this isn't the same as the code below. getIdentifier() is non-virtual
1490 // and returns different names. NamedDecl returns the class name and
1491 // ObjCCategoryImplDecl returns the category name.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001492 return createCXString(CIMP->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001493
Douglas Gregor78205d42010-01-20 21:45:58 +00001494 if (ND->getIdentifier())
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001495 return createCXString(ND->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001496
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001497 return createCXString("");
Douglas Gregor78205d42010-01-20 21:45:58 +00001498}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001499
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001500CXString clang_getCursorSpelling(CXCursor C) {
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001501 if (clang_isTranslationUnit(C.kind))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001502 return clang_getTranslationUnitSpelling(C.data[2]);
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001503
Steve Narofff334b4e2009-09-02 18:26:48 +00001504 if (clang_isReference(C.kind)) {
1505 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00001506 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +00001507 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001508 return createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00001509 }
1510 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +00001511 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001512 return createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00001513 }
1514 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +00001515 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +00001516 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001517 return createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00001518 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001519 case CXCursor_TypeRef: {
1520 TypeDecl *Type = getCursorTypeRef(C).first;
1521 assert(Type && "Missing type decl");
1522
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001523 return createCXString(getCursorContext(C).getTypeDeclType(Type).
1524 getAsString());
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001525 }
1526
Daniel Dunbaracca7252009-11-30 20:42:49 +00001527 default:
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001528 return createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +00001529 }
1530 }
Douglas Gregor97b98722010-01-19 23:20:36 +00001531
1532 if (clang_isExpression(C.kind)) {
1533 Decl *D = getDeclFromExpr(getCursorExpr(C));
1534 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +00001535 return getDeclSpelling(D);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001536 return createCXString("");
Douglas Gregor97b98722010-01-19 23:20:36 +00001537 }
1538
Douglas Gregor4ae8f292010-03-18 17:52:52 +00001539 if (C.kind == CXCursor_MacroInstantiation)
1540 return createCXString(getCursorMacroInstantiation(C)->getName()
1541 ->getNameStart());
1542
Douglas Gregor572feb22010-03-18 18:04:21 +00001543 if (C.kind == CXCursor_MacroDefinition)
1544 return createCXString(getCursorMacroDefinition(C)->getName()
1545 ->getNameStart());
1546
Douglas Gregor60cbfac2010-01-25 16:56:17 +00001547 if (clang_isDeclaration(C.kind))
1548 return getDeclSpelling(getCursorDecl(C));
Ted Kremeneke68fff62010-02-17 00:41:32 +00001549
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001550 return createCXString("");
Steve Narofff334b4e2009-09-02 18:26:48 +00001551}
1552
Ted Kremeneke68fff62010-02-17 00:41:32 +00001553CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00001554 switch (Kind) {
Ted Kremeneke68fff62010-02-17 00:41:32 +00001555 case CXCursor_FunctionDecl:
1556 return createCXString("FunctionDecl");
1557 case CXCursor_TypedefDecl:
1558 return createCXString("TypedefDecl");
1559 case CXCursor_EnumDecl:
1560 return createCXString("EnumDecl");
1561 case CXCursor_EnumConstantDecl:
1562 return createCXString("EnumConstantDecl");
1563 case CXCursor_StructDecl:
1564 return createCXString("StructDecl");
1565 case CXCursor_UnionDecl:
1566 return createCXString("UnionDecl");
1567 case CXCursor_ClassDecl:
1568 return createCXString("ClassDecl");
1569 case CXCursor_FieldDecl:
1570 return createCXString("FieldDecl");
1571 case CXCursor_VarDecl:
1572 return createCXString("VarDecl");
1573 case CXCursor_ParmDecl:
1574 return createCXString("ParmDecl");
1575 case CXCursor_ObjCInterfaceDecl:
1576 return createCXString("ObjCInterfaceDecl");
1577 case CXCursor_ObjCCategoryDecl:
1578 return createCXString("ObjCCategoryDecl");
1579 case CXCursor_ObjCProtocolDecl:
1580 return createCXString("ObjCProtocolDecl");
1581 case CXCursor_ObjCPropertyDecl:
1582 return createCXString("ObjCPropertyDecl");
1583 case CXCursor_ObjCIvarDecl:
1584 return createCXString("ObjCIvarDecl");
1585 case CXCursor_ObjCInstanceMethodDecl:
1586 return createCXString("ObjCInstanceMethodDecl");
1587 case CXCursor_ObjCClassMethodDecl:
1588 return createCXString("ObjCClassMethodDecl");
1589 case CXCursor_ObjCImplementationDecl:
1590 return createCXString("ObjCImplementationDecl");
1591 case CXCursor_ObjCCategoryImplDecl:
1592 return createCXString("ObjCCategoryImplDecl");
Ted Kremenek8bd5a692010-04-13 23:39:06 +00001593 case CXCursor_CXXMethod:
1594 return createCXString("CXXMethod");
Ted Kremeneke68fff62010-02-17 00:41:32 +00001595 case CXCursor_UnexposedDecl:
1596 return createCXString("UnexposedDecl");
1597 case CXCursor_ObjCSuperClassRef:
1598 return createCXString("ObjCSuperClassRef");
1599 case CXCursor_ObjCProtocolRef:
1600 return createCXString("ObjCProtocolRef");
1601 case CXCursor_ObjCClassRef:
1602 return createCXString("ObjCClassRef");
1603 case CXCursor_TypeRef:
1604 return createCXString("TypeRef");
1605 case CXCursor_UnexposedExpr:
1606 return createCXString("UnexposedExpr");
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00001607 case CXCursor_BlockExpr:
1608 return createCXString("BlockExpr");
Ted Kremeneke68fff62010-02-17 00:41:32 +00001609 case CXCursor_DeclRefExpr:
1610 return createCXString("DeclRefExpr");
1611 case CXCursor_MemberRefExpr:
1612 return createCXString("MemberRefExpr");
1613 case CXCursor_CallExpr:
1614 return createCXString("CallExpr");
1615 case CXCursor_ObjCMessageExpr:
1616 return createCXString("ObjCMessageExpr");
1617 case CXCursor_UnexposedStmt:
1618 return createCXString("UnexposedStmt");
1619 case CXCursor_InvalidFile:
1620 return createCXString("InvalidFile");
Ted Kremenek292db642010-03-19 20:39:05 +00001621 case CXCursor_InvalidCode:
1622 return createCXString("InvalidCode");
Ted Kremeneke68fff62010-02-17 00:41:32 +00001623 case CXCursor_NoDeclFound:
1624 return createCXString("NoDeclFound");
1625 case CXCursor_NotImplemented:
1626 return createCXString("NotImplemented");
1627 case CXCursor_TranslationUnit:
1628 return createCXString("TranslationUnit");
Ted Kremeneke77f4432010-02-18 03:09:07 +00001629 case CXCursor_UnexposedAttr:
1630 return createCXString("UnexposedAttr");
1631 case CXCursor_IBActionAttr:
1632 return createCXString("attribute(ibaction)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00001633 case CXCursor_IBOutletAttr:
1634 return createCXString("attribute(iboutlet)");
1635 case CXCursor_PreprocessingDirective:
1636 return createCXString("preprocessing directive");
Douglas Gregor572feb22010-03-18 18:04:21 +00001637 case CXCursor_MacroDefinition:
1638 return createCXString("macro definition");
Douglas Gregor48072312010-03-18 15:23:44 +00001639 case CXCursor_MacroInstantiation:
1640 return createCXString("macro instantiation");
Steve Naroff89922f82009-08-31 00:59:03 +00001641 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00001642
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00001643 llvm_unreachable("Unhandled CXCursorKind");
Ted Kremeneke68fff62010-02-17 00:41:32 +00001644 return createCXString(NULL);
Steve Naroff600866c2009-08-27 19:51:58 +00001645}
Steve Naroff89922f82009-08-31 00:59:03 +00001646
Ted Kremeneke68fff62010-02-17 00:41:32 +00001647enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
1648 CXCursor parent,
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001649 CXClientData client_data) {
1650 CXCursor *BestCursor = static_cast<CXCursor *>(client_data);
1651 *BestCursor = cursor;
1652 return CXChildVisit_Recurse;
1653}
Ted Kremeneke68fff62010-02-17 00:41:32 +00001654
Douglas Gregorb9790342010-01-22 21:44:22 +00001655CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
1656 if (!TU)
Ted Kremenekf4629892010-01-14 01:51:23 +00001657 return clang_getNullCursor();
Ted Kremeneke68fff62010-02-17 00:41:32 +00001658
Douglas Gregorb9790342010-01-22 21:44:22 +00001659 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
1660
Douglas Gregorbdf60622010-03-05 21:16:25 +00001661 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
1662
Ted Kremeneka297de22010-01-25 22:34:44 +00001663 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001664 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
1665 if (SLoc.isValid()) {
Daniel Dunbard52864b2010-02-14 10:02:57 +00001666 SourceRange RegionOfInterest(SLoc, SLoc.getFileLocWithOffset(1));
Ted Kremeneke68fff62010-02-17 00:41:32 +00001667
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001668 // FIXME: Would be great to have a "hint" cursor, then walk from that
1669 // hint cursor upward until we find a cursor whose source range encloses
1670 // the region of interest, rather than starting from the translation unit.
1671 CXCursor Parent = clang_getTranslationUnitCursor(CXXUnit);
Ted Kremeneke68fff62010-02-17 00:41:32 +00001672 CursorVisitor CursorVis(CXXUnit, GetCursorVisitor, &Result,
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001673 Decl::MaxPCHLevel, RegionOfInterest);
1674 CursorVis.VisitChildren(Parent);
Steve Naroff77128dd2009-09-15 20:25:34 +00001675 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00001676 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00001677}
1678
Ted Kremenek73885552009-11-17 19:28:59 +00001679CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00001680 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00001681}
1682
1683unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00001684 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00001685}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001686
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001687unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00001688 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
1689}
1690
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001691unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +00001692 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
1693}
Steve Naroff2d4d6292009-08-31 14:26:51 +00001694
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001695unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00001696 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
1697}
1698
Douglas Gregor97b98722010-01-19 23:20:36 +00001699unsigned clang_isExpression(enum CXCursorKind K) {
1700 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
1701}
1702
1703unsigned clang_isStatement(enum CXCursorKind K) {
1704 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
1705}
1706
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001707unsigned clang_isTranslationUnit(enum CXCursorKind K) {
1708 return K == CXCursor_TranslationUnit;
1709}
1710
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00001711unsigned clang_isPreprocessing(enum CXCursorKind K) {
1712 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
1713}
1714
Ted Kremenekad6eff62010-03-08 21:17:29 +00001715unsigned clang_isUnexposed(enum CXCursorKind K) {
1716 switch (K) {
1717 case CXCursor_UnexposedDecl:
1718 case CXCursor_UnexposedExpr:
1719 case CXCursor_UnexposedStmt:
1720 case CXCursor_UnexposedAttr:
1721 return true;
1722 default:
1723 return false;
1724 }
1725}
1726
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001727CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00001728 return C.kind;
1729}
1730
Douglas Gregor98258af2010-01-18 22:46:11 +00001731CXSourceLocation clang_getCursorLocation(CXCursor C) {
1732 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00001733 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001734 case CXCursor_ObjCSuperClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00001735 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1736 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001737 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001738 }
1739
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001740 case CXCursor_ObjCProtocolRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00001741 std::pair<ObjCProtocolDecl *, SourceLocation> P
1742 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001743 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001744 }
1745
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001746 case CXCursor_ObjCClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00001747 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1748 = getCursorObjCClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001749 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001750 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001751
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001752 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001753 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001754 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001755 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001756
Douglas Gregorf46034a2010-01-18 23:41:10 +00001757 default:
1758 // FIXME: Need a way to enumerate all non-reference cases.
1759 llvm_unreachable("Missed a reference kind");
1760 }
Douglas Gregor98258af2010-01-18 22:46:11 +00001761 }
Douglas Gregor97b98722010-01-19 23:20:36 +00001762
1763 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001764 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00001765 getLocationFromExpr(getCursorExpr(C)));
1766
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00001767 if (C.kind == CXCursor_PreprocessingDirective) {
1768 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
1769 return cxloc::translateSourceLocation(getCursorContext(C), L);
1770 }
Douglas Gregor48072312010-03-18 15:23:44 +00001771
1772 if (C.kind == CXCursor_MacroInstantiation) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00001773 SourceLocation L
1774 = cxcursor::getCursorMacroInstantiation(C)->getSourceRange().getBegin();
Douglas Gregor48072312010-03-18 15:23:44 +00001775 return cxloc::translateSourceLocation(getCursorContext(C), L);
1776 }
Douglas Gregor572feb22010-03-18 18:04:21 +00001777
1778 if (C.kind == CXCursor_MacroDefinition) {
1779 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
1780 return cxloc::translateSourceLocation(getCursorContext(C), L);
1781 }
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00001782
Douglas Gregor5352ac02010-01-28 00:27:43 +00001783 if (!getCursorDecl(C))
1784 return clang_getNullLocation();
Douglas Gregor98258af2010-01-18 22:46:11 +00001785
Douglas Gregorf46034a2010-01-18 23:41:10 +00001786 Decl *D = getCursorDecl(C);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001787 SourceLocation Loc = D->getLocation();
1788 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
1789 Loc = Class->getClassLoc();
Douglas Gregor2ca54fe2010-03-22 15:53:50 +00001790 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00001791}
Douglas Gregora7bde202010-01-19 00:34:46 +00001792
1793CXSourceRange clang_getCursorExtent(CXCursor C) {
1794 if (clang_isReference(C.kind)) {
1795 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001796 case CXCursor_ObjCSuperClassRef: {
Douglas Gregora7bde202010-01-19 00:34:46 +00001797 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1798 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001799 return cxloc::translateSourceRange(P.first->getASTContext(), P.second);
Douglas Gregora7bde202010-01-19 00:34:46 +00001800 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001801
1802 case CXCursor_ObjCProtocolRef: {
Douglas Gregora7bde202010-01-19 00:34:46 +00001803 std::pair<ObjCProtocolDecl *, SourceLocation> P
1804 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001805 return cxloc::translateSourceRange(P.first->getASTContext(), P.second);
Douglas Gregora7bde202010-01-19 00:34:46 +00001806 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001807
1808 case CXCursor_ObjCClassRef: {
Douglas Gregora7bde202010-01-19 00:34:46 +00001809 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1810 = getCursorObjCClassRef(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001811
Ted Kremeneka297de22010-01-25 22:34:44 +00001812 return cxloc::translateSourceRange(P.first->getASTContext(), P.second);
Douglas Gregora7bde202010-01-19 00:34:46 +00001813 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001814
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001815 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001816 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001817 return cxloc::translateSourceRange(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001818 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001819
Douglas Gregora7bde202010-01-19 00:34:46 +00001820 default:
1821 // FIXME: Need a way to enumerate all non-reference cases.
1822 llvm_unreachable("Missed a reference kind");
1823 }
1824 }
Douglas Gregor97b98722010-01-19 23:20:36 +00001825
1826 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001827 return cxloc::translateSourceRange(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00001828 getCursorExpr(C)->getSourceRange());
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001829
1830 if (clang_isStatement(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001831 return cxloc::translateSourceRange(getCursorContext(C),
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001832 getCursorStmt(C)->getSourceRange());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001833
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00001834 if (C.kind == CXCursor_PreprocessingDirective) {
1835 SourceRange R = cxcursor::getCursorPreprocessingDirective(C);
1836 return cxloc::translateSourceRange(getCursorContext(C), R);
1837 }
Douglas Gregor48072312010-03-18 15:23:44 +00001838
1839 if (C.kind == CXCursor_MacroInstantiation) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00001840 SourceRange R = cxcursor::getCursorMacroInstantiation(C)->getSourceRange();
Douglas Gregor48072312010-03-18 15:23:44 +00001841 return cxloc::translateSourceRange(getCursorContext(C), R);
1842 }
Douglas Gregor572feb22010-03-18 18:04:21 +00001843
1844 if (C.kind == CXCursor_MacroDefinition) {
1845 SourceRange R = cxcursor::getCursorMacroDefinition(C)->getSourceRange();
1846 return cxloc::translateSourceRange(getCursorContext(C), R);
1847 }
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00001848
Douglas Gregor5352ac02010-01-28 00:27:43 +00001849 if (!getCursorDecl(C))
1850 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001851
Douglas Gregora7bde202010-01-19 00:34:46 +00001852 Decl *D = getCursorDecl(C);
Douglas Gregor2ca54fe2010-03-22 15:53:50 +00001853 return cxloc::translateSourceRange(getCursorContext(C), D->getSourceRange());
Douglas Gregora7bde202010-01-19 00:34:46 +00001854}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001855
1856CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001857 if (clang_isInvalid(C.kind))
1858 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001859
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001860 ASTUnit *CXXUnit = getCursorASTUnit(C);
Douglas Gregorb6998662010-01-19 19:34:47 +00001861 if (clang_isDeclaration(C.kind))
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001862 return C;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001863
Douglas Gregor97b98722010-01-19 23:20:36 +00001864 if (clang_isExpression(C.kind)) {
1865 Decl *D = getDeclFromExpr(getCursorExpr(C));
1866 if (D)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001867 return MakeCXCursor(D, CXXUnit);
Douglas Gregor97b98722010-01-19 23:20:36 +00001868 return clang_getNullCursor();
1869 }
1870
Douglas Gregorbf7efa22010-03-18 18:23:03 +00001871 if (C.kind == CXCursor_MacroInstantiation) {
1872 if (MacroDefinition *Def = getCursorMacroInstantiation(C)->getDefinition())
1873 return MakeMacroDefinitionCursor(Def, CXXUnit);
1874 }
1875
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001876 if (!clang_isReference(C.kind))
1877 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001878
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001879 switch (C.kind) {
1880 case CXCursor_ObjCSuperClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001881 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001882
1883 case CXCursor_ObjCProtocolRef: {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001884 return MakeCXCursor(getCursorObjCProtocolRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001885
1886 case CXCursor_ObjCClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001887 return MakeCXCursor(getCursorObjCClassRef(C).first, CXXUnit);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001888
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001889 case CXCursor_TypeRef:
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001890 return MakeCXCursor(getCursorTypeRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001891
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001892 default:
1893 // We would prefer to enumerate all non-reference cursor kinds here.
1894 llvm_unreachable("Unhandled reference cursor kind");
1895 break;
1896 }
1897 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001898
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001899 return clang_getNullCursor();
1900}
1901
Douglas Gregorb6998662010-01-19 19:34:47 +00001902CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001903 if (clang_isInvalid(C.kind))
1904 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001905
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001906 ASTUnit *CXXUnit = getCursorASTUnit(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001907
Douglas Gregorb6998662010-01-19 19:34:47 +00001908 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00001909 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00001910 C = clang_getCursorReferenced(C);
1911 WasReference = true;
1912 }
1913
Douglas Gregorbf7efa22010-03-18 18:23:03 +00001914 if (C.kind == CXCursor_MacroInstantiation)
1915 return clang_getCursorReferenced(C);
1916
Douglas Gregorb6998662010-01-19 19:34:47 +00001917 if (!clang_isDeclaration(C.kind))
1918 return clang_getNullCursor();
1919
1920 Decl *D = getCursorDecl(C);
1921 if (!D)
1922 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001923
Douglas Gregorb6998662010-01-19 19:34:47 +00001924 switch (D->getKind()) {
1925 // Declaration kinds that don't really separate the notions of
1926 // declaration and definition.
1927 case Decl::Namespace:
1928 case Decl::Typedef:
1929 case Decl::TemplateTypeParm:
1930 case Decl::EnumConstant:
1931 case Decl::Field:
1932 case Decl::ObjCIvar:
1933 case Decl::ObjCAtDefsField:
1934 case Decl::ImplicitParam:
1935 case Decl::ParmVar:
1936 case Decl::NonTypeTemplateParm:
1937 case Decl::TemplateTemplateParm:
1938 case Decl::ObjCCategoryImpl:
1939 case Decl::ObjCImplementation:
1940 case Decl::LinkageSpec:
1941 case Decl::ObjCPropertyImpl:
1942 case Decl::FileScopeAsm:
1943 case Decl::StaticAssert:
1944 case Decl::Block:
1945 return C;
1946
1947 // Declaration kinds that don't make any sense here, but are
1948 // nonetheless harmless.
1949 case Decl::TranslationUnit:
Douglas Gregorb6998662010-01-19 19:34:47 +00001950 break;
1951
1952 // Declaration kinds for which the definition is not resolvable.
1953 case Decl::UnresolvedUsingTypename:
1954 case Decl::UnresolvedUsingValue:
1955 break;
1956
1957 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001958 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
1959 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001960
1961 case Decl::NamespaceAlias:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001962 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001963
1964 case Decl::Enum:
1965 case Decl::Record:
1966 case Decl::CXXRecord:
1967 case Decl::ClassTemplateSpecialization:
1968 case Decl::ClassTemplatePartialSpecialization:
Douglas Gregor952b0172010-02-11 01:04:33 +00001969 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001970 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001971 return clang_getNullCursor();
1972
1973 case Decl::Function:
1974 case Decl::CXXMethod:
1975 case Decl::CXXConstructor:
1976 case Decl::CXXDestructor:
1977 case Decl::CXXConversion: {
1978 const FunctionDecl *Def = 0;
1979 if (cast<FunctionDecl>(D)->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001980 return MakeCXCursor(const_cast<FunctionDecl *>(Def), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001981 return clang_getNullCursor();
1982 }
1983
1984 case Decl::Var: {
Sebastian Redl31310a22010-02-01 20:16:42 +00001985 // Ask the variable if it has a definition.
1986 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
1987 return MakeCXCursor(Def, CXXUnit);
1988 return clang_getNullCursor();
Douglas Gregorb6998662010-01-19 19:34:47 +00001989 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001990
Douglas Gregorb6998662010-01-19 19:34:47 +00001991 case Decl::FunctionTemplate: {
1992 const FunctionDecl *Def = 0;
1993 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001994 return MakeCXCursor(Def->getDescribedFunctionTemplate(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001995 return clang_getNullCursor();
1996 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001997
Douglas Gregorb6998662010-01-19 19:34:47 +00001998 case Decl::ClassTemplate: {
1999 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
Douglas Gregor952b0172010-02-11 01:04:33 +00002000 ->getDefinition())
Douglas Gregorb6998662010-01-19 19:34:47 +00002001 return MakeCXCursor(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002002 cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002003 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002004 return clang_getNullCursor();
2005 }
2006
2007 case Decl::Using: {
2008 UsingDecl *Using = cast<UsingDecl>(D);
2009 CXCursor Def = clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002010 for (UsingDecl::shadow_iterator S = Using->shadow_begin(),
2011 SEnd = Using->shadow_end();
Douglas Gregorb6998662010-01-19 19:34:47 +00002012 S != SEnd; ++S) {
2013 if (Def != clang_getNullCursor()) {
2014 // FIXME: We have no way to return multiple results.
2015 return clang_getNullCursor();
2016 }
2017
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002018 Def = clang_getCursorDefinition(MakeCXCursor((*S)->getTargetDecl(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002019 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002020 }
2021
2022 return Def;
2023 }
2024
2025 case Decl::UsingShadow:
2026 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002027 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002028 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002029
2030 case Decl::ObjCMethod: {
2031 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
2032 if (Method->isThisDeclarationADefinition())
2033 return C;
2034
2035 // Dig out the method definition in the associated
2036 // @implementation, if we have it.
2037 // FIXME: The ASTs should make finding the definition easier.
2038 if (ObjCInterfaceDecl *Class
2039 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
2040 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
2041 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
2042 Method->isInstanceMethod()))
2043 if (Def->isThisDeclarationADefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002044 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002045
2046 return clang_getNullCursor();
2047 }
2048
2049 case Decl::ObjCCategory:
2050 if (ObjCCategoryImplDecl *Impl
2051 = cast<ObjCCategoryDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002052 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002053 return clang_getNullCursor();
2054
2055 case Decl::ObjCProtocol:
2056 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
2057 return C;
2058 return clang_getNullCursor();
2059
2060 case Decl::ObjCInterface:
2061 // There are two notions of a "definition" for an Objective-C
2062 // class: the interface and its implementation. When we resolved a
2063 // reference to an Objective-C class, produce the @interface as
2064 // the definition; when we were provided with the interface,
2065 // produce the @implementation as the definition.
2066 if (WasReference) {
2067 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
2068 return C;
2069 } else if (ObjCImplementationDecl *Impl
2070 = cast<ObjCInterfaceDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002071 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002072 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002073
Douglas Gregorb6998662010-01-19 19:34:47 +00002074 case Decl::ObjCProperty:
2075 // FIXME: We don't really know where to find the
2076 // ObjCPropertyImplDecls that implement this property.
2077 return clang_getNullCursor();
2078
2079 case Decl::ObjCCompatibleAlias:
2080 if (ObjCInterfaceDecl *Class
2081 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
2082 if (!Class->isForwardDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002083 return MakeCXCursor(Class, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002084
Douglas Gregorb6998662010-01-19 19:34:47 +00002085 return clang_getNullCursor();
2086
2087 case Decl::ObjCForwardProtocol: {
2088 ObjCForwardProtocolDecl *Forward = cast<ObjCForwardProtocolDecl>(D);
2089 if (Forward->protocol_size() == 1)
2090 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002091 MakeCXCursor(*Forward->protocol_begin(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002092 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002093
2094 // FIXME: Cannot return multiple definitions.
2095 return clang_getNullCursor();
2096 }
2097
2098 case Decl::ObjCClass: {
2099 ObjCClassDecl *Class = cast<ObjCClassDecl>(D);
2100 if (Class->size() == 1) {
2101 ObjCInterfaceDecl *IFace = Class->begin()->getInterface();
2102 if (!IFace->isForwardDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002103 return MakeCXCursor(IFace, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002104 return clang_getNullCursor();
2105 }
2106
2107 // FIXME: Cannot return multiple definitions.
2108 return clang_getNullCursor();
2109 }
2110
2111 case Decl::Friend:
2112 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002113 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002114 return clang_getNullCursor();
2115
2116 case Decl::FriendTemplate:
2117 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002118 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002119 return clang_getNullCursor();
2120 }
2121
2122 return clang_getNullCursor();
2123}
2124
2125unsigned clang_isCursorDefinition(CXCursor C) {
2126 if (!clang_isDeclaration(C.kind))
2127 return 0;
2128
2129 return clang_getCursorDefinition(C) == C;
2130}
2131
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002132void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00002133 const char **startBuf,
2134 const char **endBuf,
2135 unsigned *startLine,
2136 unsigned *startColumn,
2137 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002138 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00002139 assert(getCursorDecl(C) && "CXCursor has null decl");
2140 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00002141 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
2142 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002143
Steve Naroff4ade6d62009-09-23 17:52:52 +00002144 SourceManager &SM = FD->getASTContext().getSourceManager();
2145 *startBuf = SM.getCharacterData(Body->getLBracLoc());
2146 *endBuf = SM.getCharacterData(Body->getRBracLoc());
2147 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
2148 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
2149 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
2150 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
2151}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002152
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002153void clang_enableStackTraces(void) {
2154 llvm::sys::PrintStackTraceOnErrorSignal();
2155}
2156
Ted Kremenekfb480492010-01-13 21:46:36 +00002157} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00002158
Ted Kremenekfb480492010-01-13 21:46:36 +00002159//===----------------------------------------------------------------------===//
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002160// Token-based Operations.
2161//===----------------------------------------------------------------------===//
2162
2163/* CXToken layout:
2164 * int_data[0]: a CXTokenKind
2165 * int_data[1]: starting token location
2166 * int_data[2]: token length
2167 * int_data[3]: reserved
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002168 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002169 * otherwise unused.
2170 */
2171extern "C" {
2172
2173CXTokenKind clang_getTokenKind(CXToken CXTok) {
2174 return static_cast<CXTokenKind>(CXTok.int_data[0]);
2175}
2176
2177CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
2178 switch (clang_getTokenKind(CXTok)) {
2179 case CXToken_Identifier:
2180 case CXToken_Keyword:
2181 // We know we have an IdentifierInfo*, so use that.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002182 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
2183 ->getNameStart());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002184
2185 case CXToken_Literal: {
2186 // We have stashed the starting pointer in the ptr_data field. Use it.
2187 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002188 return createCXString(llvm::StringRef(Text, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002189 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002190
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002191 case CXToken_Punctuation:
2192 case CXToken_Comment:
2193 break;
2194 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002195
2196 // We have to find the starting buffer pointer the hard way, by
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002197 // deconstructing the source location.
2198 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2199 if (!CXXUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002200 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002201
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002202 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
2203 std::pair<FileID, unsigned> LocInfo
2204 = CXXUnit->getSourceManager().getDecomposedLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +00002205 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002206 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00002207 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
2208 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00002209 return createCXString("");
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002210
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002211 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002212}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002213
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002214CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
2215 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2216 if (!CXXUnit)
2217 return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002218
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002219 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
2220 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
2221}
2222
2223CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
2224 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregor5352ac02010-01-28 00:27:43 +00002225 if (!CXXUnit)
2226 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002227
2228 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002229 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
2230}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002231
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002232void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
2233 CXToken **Tokens, unsigned *NumTokens) {
2234 if (Tokens)
2235 *Tokens = 0;
2236 if (NumTokens)
2237 *NumTokens = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002238
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002239 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2240 if (!CXXUnit || !Tokens || !NumTokens)
2241 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002242
Douglas Gregorbdf60622010-03-05 21:16:25 +00002243 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
2244
Daniel Dunbar85b988f2010-02-14 08:31:57 +00002245 SourceRange R = cxloc::translateCXSourceRange(Range);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002246 if (R.isInvalid())
2247 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002248
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002249 SourceManager &SourceMgr = CXXUnit->getSourceManager();
2250 std::pair<FileID, unsigned> BeginLocInfo
2251 = SourceMgr.getDecomposedLoc(R.getBegin());
2252 std::pair<FileID, unsigned> EndLocInfo
2253 = SourceMgr.getDecomposedLoc(R.getEnd());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002254
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002255 // Cannot tokenize across files.
2256 if (BeginLocInfo.first != EndLocInfo.first)
2257 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002258
2259 // Create a lexer
Douglas Gregorf715ca12010-03-16 00:06:06 +00002260 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002261 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00002262 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
Douglas Gregor47a3fcd2010-03-16 20:26:15 +00002263 if (Invalid)
2264 return;
Douglas Gregoraea67db2010-03-15 22:54:52 +00002265
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002266 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
2267 CXXUnit->getASTContext().getLangOptions(),
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002268 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002269 Lex.SetCommentRetentionState(true);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002270
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002271 // Lex tokens until we hit the end of the range.
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002272 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002273 llvm::SmallVector<CXToken, 32> CXTokens;
2274 Token Tok;
2275 do {
2276 // Lex the next token
2277 Lex.LexFromRawLexer(Tok);
2278 if (Tok.is(tok::eof))
2279 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002280
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002281 // Initialize the CXToken.
2282 CXToken CXTok;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002283
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002284 // - Common fields
2285 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
2286 CXTok.int_data[2] = Tok.getLength();
2287 CXTok.int_data[3] = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002288
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002289 // - Kind-specific fields
2290 if (Tok.isLiteral()) {
2291 CXTok.int_data[0] = CXToken_Literal;
2292 CXTok.ptr_data = (void *)Tok.getLiteralData();
2293 } else if (Tok.is(tok::identifier)) {
Douglas Gregoraea67db2010-03-15 22:54:52 +00002294 // Lookup the identifier to determine whether we have a keyword.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002295 std::pair<FileID, unsigned> LocInfo
2296 = SourceMgr.getDecomposedLoc(Tok.getLocation());
Douglas Gregorf715ca12010-03-16 00:06:06 +00002297 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002298 llvm::StringRef Buf
Douglas Gregorf715ca12010-03-16 00:06:06 +00002299 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
2300 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00002301 return;
2302
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002303 const char *StartPos = Buf.data() + LocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002304 IdentifierInfo *II
2305 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok, StartPos);
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00002306
2307 if (II->getObjCKeywordID() != tok::objc_not_keyword) {
2308 CXTok.int_data[0] = CXToken_Keyword;
2309 }
2310 else {
2311 CXTok.int_data[0] = II->getTokenID() == tok::identifier?
2312 CXToken_Identifier
2313 : CXToken_Keyword;
2314 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002315 CXTok.ptr_data = II;
2316 } else if (Tok.is(tok::comment)) {
2317 CXTok.int_data[0] = CXToken_Comment;
2318 CXTok.ptr_data = 0;
2319 } else {
2320 CXTok.int_data[0] = CXToken_Punctuation;
2321 CXTok.ptr_data = 0;
2322 }
2323 CXTokens.push_back(CXTok);
2324 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002325
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002326 if (CXTokens.empty())
2327 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002328
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002329 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
2330 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
2331 *NumTokens = CXTokens.size();
2332}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002333
Ted Kremenek6db61092010-05-05 00:55:15 +00002334void clang_disposeTokens(CXTranslationUnit TU,
2335 CXToken *Tokens, unsigned NumTokens) {
2336 free(Tokens);
2337}
2338
2339} // end: extern "C"
2340
2341//===----------------------------------------------------------------------===//
2342// Token annotation APIs.
2343//===----------------------------------------------------------------------===//
2344
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002345typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002346static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
2347 CXCursor parent,
2348 CXClientData client_data);
Ted Kremenek6db61092010-05-05 00:55:15 +00002349namespace {
2350class AnnotateTokensWorker {
2351 AnnotateTokensData &Annotated;
Ted Kremenek11949cb2010-05-05 00:55:17 +00002352 CXToken *Tokens;
2353 CXCursor *Cursors;
2354 unsigned NumTokens;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002355 unsigned TokIdx;
2356 CursorVisitor AnnotateVis;
2357 SourceManager &SrcMgr;
2358
2359 bool MoreTokens() const { return TokIdx < NumTokens; }
2360 unsigned NextToken() const { return TokIdx; }
2361 void AdvanceToken() { ++TokIdx; }
2362 SourceLocation GetTokenLoc(unsigned tokI) {
2363 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
2364 }
2365
Ted Kremenek6db61092010-05-05 00:55:15 +00002366public:
Ted Kremenek11949cb2010-05-05 00:55:17 +00002367 AnnotateTokensWorker(AnnotateTokensData &annotated,
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002368 CXToken *tokens, CXCursor *cursors, unsigned numTokens,
2369 ASTUnit *CXXUnit, SourceRange RegionOfInterest)
Ted Kremenek11949cb2010-05-05 00:55:17 +00002370 : Annotated(annotated), Tokens(tokens), Cursors(cursors),
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002371 NumTokens(numTokens), TokIdx(0),
2372 AnnotateVis(CXXUnit, AnnotateTokensVisitor, this,
2373 Decl::MaxPCHLevel, RegionOfInterest),
2374 SrcMgr(CXXUnit->getSourceManager()) {}
Ted Kremenek11949cb2010-05-05 00:55:17 +00002375
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002376 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
Ted Kremenek6db61092010-05-05 00:55:15 +00002377 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002378 void AnnotateTokens(CXCursor parent);
Ted Kremenek6db61092010-05-05 00:55:15 +00002379};
2380}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002381
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002382void AnnotateTokensWorker::AnnotateTokens(CXCursor parent) {
2383 // Walk the AST within the region of interest, annotating tokens
2384 // along the way.
2385 VisitChildren(parent);
Ted Kremenek11949cb2010-05-05 00:55:17 +00002386
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002387 for (unsigned I = 0 ; I < TokIdx ; ++I) {
2388 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
2389 if (Pos != Annotated.end())
2390 Cursors[I] = Pos->second;
2391 }
2392
2393 // Finish up annotating any tokens left.
2394 if (!MoreTokens())
2395 return;
2396
2397 const CXCursor &C = clang_getNullCursor();
2398 for (unsigned I = TokIdx ; I < NumTokens ; ++I) {
2399 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
2400 Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second;
Ted Kremenek11949cb2010-05-05 00:55:17 +00002401 }
2402}
2403
Ted Kremenek6db61092010-05-05 00:55:15 +00002404enum CXChildVisitResult
2405AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002406 CXSourceLocation Loc = clang_getCursorLocation(cursor);
2407 // We can always annotate a preprocessing directive/macro instantiation.
2408 if (clang_isPreprocessing(cursor.kind)) {
2409 Annotated[Loc.int_data] = cursor;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002410 return CXChildVisit_Recurse;
2411 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002412
2413 CXSourceRange cursorExtent = clang_getCursorExtent(cursor);
2414 SourceRange cursorRange = cxloc::translateCXSourceRange(cursorExtent);
2415
2416 if (cursorRange.isInvalid())
2417 return CXChildVisit_Continue;
2418
2419 SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data);
2420
2421 const enum CXCursorKind K = clang_getCursorKind(parent);
2422 const CXCursor updateC =
2423 (clang_isInvalid(K) || K == CXCursor_TranslationUnit ||
2424 L.isMacroID())
2425 ? clang_getNullCursor() : parent;
2426
2427 while (MoreTokens()) {
2428 const unsigned I = NextToken();
2429 SourceLocation TokLoc = GetTokenLoc(I);
2430 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
2431 case RangeBefore:
2432 Cursors[I] = updateC;
2433 AdvanceToken();
2434 continue;
2435 case RangeAfter:
2436 return CXChildVisit_Continue;
2437 case RangeOverlap:
2438 break;
2439 }
2440 break;
2441 }
2442
2443 // Visit children to get their cursor information.
2444 const unsigned BeforeChildren = NextToken();
2445 VisitChildren(cursor);
2446 const unsigned AfterChildren = NextToken();
2447
2448 // Adjust 'Last' to the last token within the extent of the cursor.
2449 while (MoreTokens()) {
2450 const unsigned I = NextToken();
2451 SourceLocation TokLoc = GetTokenLoc(I);
2452 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
2453 case RangeBefore:
2454 assert(0 && "Infeasible");
2455 case RangeAfter:
2456 break;
2457 case RangeOverlap:
2458 Cursors[I] = updateC;
2459 AdvanceToken();
2460 continue;
2461 }
2462 break;
2463 }
2464 const unsigned Last = NextToken();
Ted Kremenek6db61092010-05-05 00:55:15 +00002465
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002466 // Scan the tokens that are at the beginning of the cursor, but are not
2467 // capture by the child cursors.
2468
2469 // For AST elements within macros, rely on a post-annotate pass to
2470 // to correctly annotate the tokens with cursors. Otherwise we can
2471 // get confusing results of having tokens that map to cursors that really
2472 // are expanded by an instantiation.
2473 if (L.isMacroID())
2474 cursor = clang_getNullCursor();
2475
2476 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
2477 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
2478 break;
2479 Cursors[I] = cursor;
2480 }
2481 // Scan the tokens that are at the end of the cursor, but are not captured
2482 // but the child cursors.
2483 for (unsigned I = AfterChildren; I != Last; ++I)
2484 Cursors[I] = cursor;
2485
2486 TokIdx = Last;
2487 return CXChildVisit_Continue;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002488}
2489
Ted Kremenek6db61092010-05-05 00:55:15 +00002490static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
2491 CXCursor parent,
2492 CXClientData client_data) {
2493 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
2494}
2495
2496extern "C" {
2497
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002498void clang_annotateTokens(CXTranslationUnit TU,
2499 CXToken *Tokens, unsigned NumTokens,
2500 CXCursor *Cursors) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002501
2502 if (NumTokens == 0 || !Tokens || !Cursors)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002503 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002504
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002505 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002506 if (!CXXUnit) {
2507 // Any token we don't specifically annotate will have a NULL cursor.
2508 const CXCursor &C = clang_getNullCursor();
2509 for (unsigned I = 0; I != NumTokens; ++I)
2510 Cursors[I] = C;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002511 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002512 }
2513
Douglas Gregorbdf60622010-03-05 21:16:25 +00002514 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002515
Douglas Gregor0396f462010-03-19 05:22:59 +00002516 // Determine the region of interest, which contains all of the tokens.
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002517 SourceRange RegionOfInterest;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002518 RegionOfInterest.setBegin(cxloc::translateSourceLocation(
2519 clang_getTokenLocation(TU, Tokens[0])));
2520
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002521 SourceLocation End
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002522 = cxloc::translateSourceLocation(clang_getTokenLocation(TU,
2523 Tokens[NumTokens - 1]));
Daniel Dunbard52864b2010-02-14 10:02:57 +00002524 RegionOfInterest.setEnd(CXXUnit->getPreprocessor().getLocForEndOfToken(End));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002525
Douglas Gregor0396f462010-03-19 05:22:59 +00002526 // A mapping from the source locations found when re-lexing or traversing the
2527 // region of interest to the corresponding cursors.
2528 AnnotateTokensData Annotated;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002529
2530 // Relex the tokens within the source range to look for preprocessing
Douglas Gregor0396f462010-03-19 05:22:59 +00002531 // directives.
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002532 SourceManager &SourceMgr = CXXUnit->getSourceManager();
2533 std::pair<FileID, unsigned> BeginLocInfo
2534 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
2535 std::pair<FileID, unsigned> EndLocInfo
2536 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002537
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002538 llvm::StringRef Buffer;
Douglas Gregor0396f462010-03-19 05:22:59 +00002539 bool Invalid = false;
2540 if (BeginLocInfo.first == EndLocInfo.first &&
2541 ((Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid)),true) &&
2542 !Invalid) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002543 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
2544 CXXUnit->getASTContext().getLangOptions(),
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002545 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002546 Buffer.end());
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002547 Lex.SetCommentRetentionState(true);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002548
2549 // Lex tokens in raw mode until we hit the end of the range, to avoid
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002550 // entering #includes or expanding macros.
Douglas Gregor48072312010-03-18 15:23:44 +00002551 while (true) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002552 Token Tok;
2553 Lex.LexFromRawLexer(Tok);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002554
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002555 reprocess:
2556 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
2557 // We have found a preprocessing directive. Gobble it up so that we
2558 // don't see it while preprocessing these tokens later, but keep track of
2559 // all of the token locations inside this preprocessing directive so that
2560 // we can annotate them appropriately.
2561 //
2562 // FIXME: Some simple tests here could identify macro definitions and
2563 // #undefs, to provide specific cursor kinds for those.
2564 std::vector<SourceLocation> Locations;
2565 do {
2566 Locations.push_back(Tok.getLocation());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002567 Lex.LexFromRawLexer(Tok);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002568 } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002569
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002570 using namespace cxcursor;
2571 CXCursor Cursor
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002572 = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
2573 Locations.back()),
Ted Kremenek6db61092010-05-05 00:55:15 +00002574 CXXUnit);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002575 for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
2576 Annotated[Locations[I].getRawEncoding()] = Cursor;
2577 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002578
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002579 if (Tok.isAtStartOfLine())
2580 goto reprocess;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002581
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002582 continue;
2583 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002584
Douglas Gregor48072312010-03-18 15:23:44 +00002585 if (Tok.is(tok::eof))
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002586 break;
2587 }
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002588 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002589
Douglas Gregor0396f462010-03-19 05:22:59 +00002590 // Annotate all of the source locations in the region of interest that map to
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002591 // a specific cursor.
2592 AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens,
2593 CXXUnit, RegionOfInterest);
2594 W.AnnotateTokens(clang_getTranslationUnitCursor(CXXUnit));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002595}
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002596} // end: extern "C"
2597
2598//===----------------------------------------------------------------------===//
Ted Kremenek16b42592010-03-03 06:36:57 +00002599// Operations for querying linkage of a cursor.
2600//===----------------------------------------------------------------------===//
2601
2602extern "C" {
2603CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
Douglas Gregor0396f462010-03-19 05:22:59 +00002604 if (!clang_isDeclaration(cursor.kind))
2605 return CXLinkage_Invalid;
2606
Ted Kremenek16b42592010-03-03 06:36:57 +00002607 Decl *D = cxcursor::getCursorDecl(cursor);
2608 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
2609 switch (ND->getLinkage()) {
2610 case NoLinkage: return CXLinkage_NoLinkage;
2611 case InternalLinkage: return CXLinkage_Internal;
2612 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
2613 case ExternalLinkage: return CXLinkage_External;
2614 };
2615
2616 return CXLinkage_Invalid;
2617}
2618} // end: extern "C"
2619
2620//===----------------------------------------------------------------------===//
Ted Kremenek45e1dae2010-04-12 21:22:16 +00002621// Operations for querying language of a cursor.
2622//===----------------------------------------------------------------------===//
2623
2624static CXLanguageKind getDeclLanguage(const Decl *D) {
2625 switch (D->getKind()) {
2626 default:
2627 break;
2628 case Decl::ImplicitParam:
2629 case Decl::ObjCAtDefsField:
2630 case Decl::ObjCCategory:
2631 case Decl::ObjCCategoryImpl:
2632 case Decl::ObjCClass:
2633 case Decl::ObjCCompatibleAlias:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00002634 case Decl::ObjCForwardProtocol:
2635 case Decl::ObjCImplementation:
2636 case Decl::ObjCInterface:
2637 case Decl::ObjCIvar:
2638 case Decl::ObjCMethod:
2639 case Decl::ObjCProperty:
2640 case Decl::ObjCPropertyImpl:
2641 case Decl::ObjCProtocol:
2642 return CXLanguage_ObjC;
2643 case Decl::CXXConstructor:
2644 case Decl::CXXConversion:
2645 case Decl::CXXDestructor:
2646 case Decl::CXXMethod:
2647 case Decl::CXXRecord:
2648 case Decl::ClassTemplate:
2649 case Decl::ClassTemplatePartialSpecialization:
2650 case Decl::ClassTemplateSpecialization:
2651 case Decl::Friend:
2652 case Decl::FriendTemplate:
2653 case Decl::FunctionTemplate:
2654 case Decl::LinkageSpec:
2655 case Decl::Namespace:
2656 case Decl::NamespaceAlias:
2657 case Decl::NonTypeTemplateParm:
2658 case Decl::StaticAssert:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00002659 case Decl::TemplateTemplateParm:
2660 case Decl::TemplateTypeParm:
2661 case Decl::UnresolvedUsingTypename:
2662 case Decl::UnresolvedUsingValue:
2663 case Decl::Using:
2664 case Decl::UsingDirective:
2665 case Decl::UsingShadow:
2666 return CXLanguage_CPlusPlus;
2667 }
2668
2669 return CXLanguage_C;
2670}
2671
2672extern "C" {
2673CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
2674 if (clang_isDeclaration(cursor.kind))
2675 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
2676
2677 return CXLanguage_Invalid;
2678}
2679} // end: extern "C"
2680
2681//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00002682// CXString Operations.
2683//===----------------------------------------------------------------------===//
2684
2685extern "C" {
2686const char *clang_getCString(CXString string) {
2687 return string.Spelling;
2688}
2689
2690void clang_disposeString(CXString string) {
2691 if (string.MustFreeString && string.Spelling)
2692 free((void*)string.Spelling);
2693}
Ted Kremenek04bb7162010-01-22 22:44:15 +00002694
Ted Kremenekfb480492010-01-13 21:46:36 +00002695} // end: extern "C"
Ted Kremenek04bb7162010-01-22 22:44:15 +00002696
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002697namespace clang { namespace cxstring {
2698CXString createCXString(const char *String, bool DupString){
2699 CXString Str;
2700 if (DupString) {
2701 Str.Spelling = strdup(String);
2702 Str.MustFreeString = 1;
2703 } else {
2704 Str.Spelling = String;
2705 Str.MustFreeString = 0;
2706 }
2707 return Str;
2708}
2709
2710CXString createCXString(llvm::StringRef String, bool DupString) {
2711 CXString Result;
2712 if (DupString || (!String.empty() && String.data()[String.size()] != 0)) {
2713 char *Spelling = (char *)malloc(String.size() + 1);
2714 memmove(Spelling, String.data(), String.size());
2715 Spelling[String.size()] = 0;
2716 Result.Spelling = Spelling;
2717 Result.MustFreeString = 1;
2718 } else {
2719 Result.Spelling = String.data();
2720 Result.MustFreeString = 0;
2721 }
2722 return Result;
2723}
2724}}
2725
Ted Kremenek04bb7162010-01-22 22:44:15 +00002726//===----------------------------------------------------------------------===//
2727// Misc. utility functions.
2728//===----------------------------------------------------------------------===//
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002729
Ted Kremenek04bb7162010-01-22 22:44:15 +00002730extern "C" {
2731
Ted Kremeneka2a9d6e2010-02-12 22:54:40 +00002732CXString clang_getClangVersion() {
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002733 return createCXString(getClangFullVersion());
Ted Kremenek04bb7162010-01-22 22:44:15 +00002734}
2735
2736} // end: extern "C"