blob: d24652b22dc6a735bb0a939df478f0b72d998c12 [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);
Ted Kremeneka0536d82010-05-07 01:04:29 +0000288 bool VisitLinkageSpecDecl(LinkageSpecDecl *D);
Ted Kremenek8f06e0e2010-05-06 23:38:21 +0000289 bool VisitNamespaceDecl(NamespaceDecl *D);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000290
291 // Type visitors
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000292 // FIXME: QualifiedTypeLoc doesn't provide any location information
293 bool VisitBuiltinTypeLoc(BuiltinTypeLoc TL);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000294 bool VisitTypedefTypeLoc(TypedefTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000295 bool VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL);
296 bool VisitTagTypeLoc(TagTypeLoc TL);
297 // FIXME: TemplateTypeParmTypeLoc doesn't provide any location information
298 bool VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL);
299 bool VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL);
300 bool VisitPointerTypeLoc(PointerTypeLoc TL);
301 bool VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL);
302 bool VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL);
303 bool VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL);
304 bool VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL);
305 bool VisitFunctionTypeLoc(FunctionTypeLoc TL);
306 bool VisitArrayTypeLoc(ArrayTypeLoc TL);
Douglas Gregor2332c112010-01-21 20:48:56 +0000307 // FIXME: Implement for TemplateSpecializationTypeLoc
308 // FIXME: Implement visitors here when the unimplemented TypeLocs get
309 // implemented
310 bool VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL);
311 bool VisitTypeOfTypeLoc(TypeOfTypeLoc TL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000312
Douglas Gregora59e3902010-01-21 23:27:09 +0000313 // Statement visitors
314 bool VisitStmt(Stmt *S);
315 bool VisitDeclStmt(DeclStmt *S);
Douglas Gregorf5bab412010-01-22 01:00:11 +0000316 // FIXME: LabelStmt label?
317 bool VisitIfStmt(IfStmt *S);
318 bool VisitSwitchStmt(SwitchStmt *S);
Douglas Gregor263b47b2010-01-25 16:12:32 +0000319 bool VisitWhileStmt(WhileStmt *S);
320 bool VisitForStmt(ForStmt *S);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000321
Douglas Gregor336fd812010-01-23 00:40:08 +0000322 // Expression visitors
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000323 bool VisitBlockExpr(BlockExpr *B);
Douglas Gregor336fd812010-01-23 00:40:08 +0000324 bool VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000325 bool VisitExplicitCastExpr(ExplicitCastExpr *E);
Douglas Gregorc2350e52010-03-08 16:40:19 +0000326 bool VisitObjCMessageExpr(ObjCMessageExpr *E);
Douglas Gregor81d34662010-04-20 15:39:42 +0000327 bool VisitObjCEncodeExpr(ObjCEncodeExpr *E);
Douglas Gregor8ecdb652010-04-28 22:16:22 +0000328 bool VisitOffsetOfExpr(OffsetOfExpr *E);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000329 bool VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E);
Steve Naroff89922f82009-08-31 00:59:03 +0000330};
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000331
Ted Kremenekab188932010-01-05 19:32:54 +0000332} // end anonymous namespace
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000333
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000334RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000335 return RangeCompare(TU->getSourceManager(), R, RegionOfInterest);
336}
337
Douglas Gregorb1373d02010-01-20 20:59:29 +0000338/// \brief Visit the given cursor and, if requested by the visitor,
339/// its children.
340///
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000341/// \param Cursor the cursor to visit.
342///
343/// \param CheckRegionOfInterest if true, then the caller already checked that
344/// this cursor is within the region of interest.
345///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000346/// \returns true if the visitation should be aborted, false if it
347/// should continue.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000348bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
Douglas Gregorb1373d02010-01-20 20:59:29 +0000349 if (clang_isInvalid(Cursor.kind))
350 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000351
Douglas Gregorb1373d02010-01-20 20:59:29 +0000352 if (clang_isDeclaration(Cursor.kind)) {
353 Decl *D = getCursorDecl(Cursor);
354 assert(D && "Invalid declaration cursor");
355 if (D->getPCHLevel() > MaxPCHLevel)
356 return false;
357
358 if (D->isImplicit())
359 return false;
360 }
361
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000362 // If we have a range of interest, and this cursor doesn't intersect with it,
363 // we're done.
364 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
Daniel Dunbarf408f322010-02-14 08:32:05 +0000365 SourceRange Range =
366 cxloc::translateCXSourceRange(clang_getCursorExtent(Cursor));
367 if (Range.isInvalid() || CompareRegionOfInterest(Range))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000368 return false;
369 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000370
Douglas Gregorb1373d02010-01-20 20:59:29 +0000371 switch (Visitor(Cursor, Parent, ClientData)) {
372 case CXChildVisit_Break:
373 return true;
374
375 case CXChildVisit_Continue:
376 return false;
377
378 case CXChildVisit_Recurse:
379 return VisitChildren(Cursor);
380 }
381
Douglas Gregorfd643772010-01-25 16:45:46 +0000382 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000383}
384
Douglas Gregor788f5a12010-03-20 00:41:21 +0000385std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
386CursorVisitor::getPreprocessedEntities() {
387 PreprocessingRecord &PPRec
388 = *TU->getPreprocessor().getPreprocessingRecord();
389
390 bool OnlyLocalDecls
391 = !TU->isMainFileAST() && TU->getOnlyLocalDecls();
392
393 // There is no region of interest; we have to walk everything.
394 if (RegionOfInterest.isInvalid())
395 return std::make_pair(PPRec.begin(OnlyLocalDecls),
396 PPRec.end(OnlyLocalDecls));
397
398 // Find the file in which the region of interest lands.
399 SourceManager &SM = TU->getSourceManager();
400 std::pair<FileID, unsigned> Begin
401 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getBegin());
402 std::pair<FileID, unsigned> End
403 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getEnd());
404
405 // The region of interest spans files; we have to walk everything.
406 if (Begin.first != End.first)
407 return std::make_pair(PPRec.begin(OnlyLocalDecls),
408 PPRec.end(OnlyLocalDecls));
409
410 ASTUnit::PreprocessedEntitiesByFileMap &ByFileMap
411 = TU->getPreprocessedEntitiesByFile();
412 if (ByFileMap.empty()) {
413 // Build the mapping from files to sets of preprocessed entities.
414 for (PreprocessingRecord::iterator E = PPRec.begin(OnlyLocalDecls),
415 EEnd = PPRec.end(OnlyLocalDecls);
416 E != EEnd; ++E) {
417 std::pair<FileID, unsigned> P
418 = SM.getDecomposedInstantiationLoc((*E)->getSourceRange().getBegin());
419 ByFileMap[P.first].push_back(*E);
420 }
421 }
422
423 return std::make_pair(ByFileMap[Begin.first].begin(),
424 ByFileMap[Begin.first].end());
425}
426
Douglas Gregorb1373d02010-01-20 20:59:29 +0000427/// \brief Visit the children of the given cursor.
428///
429/// \returns true if the visitation should be aborted, false if it
430/// should continue.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000431bool CursorVisitor::VisitChildren(CXCursor Cursor) {
Douglas Gregora59e3902010-01-21 23:27:09 +0000432 if (clang_isReference(Cursor.kind)) {
433 // By definition, references have no children.
434 return false;
435 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000436
437 // Set the Parent field to Cursor, then back to its old value once we're
Douglas Gregorb1373d02010-01-20 20:59:29 +0000438 // done.
439 class SetParentRAII {
440 CXCursor &Parent;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000441 Decl *&StmtParent;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000442 CXCursor OldParent;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000443
Douglas Gregorb1373d02010-01-20 20:59:29 +0000444 public:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000445 SetParentRAII(CXCursor &Parent, Decl *&StmtParent, CXCursor NewParent)
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000446 : Parent(Parent), StmtParent(StmtParent), OldParent(Parent)
Douglas Gregorb1373d02010-01-20 20:59:29 +0000447 {
448 Parent = NewParent;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000449 if (clang_isDeclaration(Parent.kind))
450 StmtParent = getCursorDecl(Parent);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000451 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000452
Douglas Gregorb1373d02010-01-20 20:59:29 +0000453 ~SetParentRAII() {
454 Parent = OldParent;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000455 if (clang_isDeclaration(Parent.kind))
456 StmtParent = getCursorDecl(Parent);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000457 }
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000458 } SetParent(Parent, StmtParent, Cursor);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000459
Douglas Gregorb1373d02010-01-20 20:59:29 +0000460 if (clang_isDeclaration(Cursor.kind)) {
461 Decl *D = getCursorDecl(Cursor);
462 assert(D && "Invalid declaration cursor");
Ted Kremenek539311e2010-02-18 18:47:01 +0000463 return VisitAttributes(D) || Visit(D);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000464 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000465
Douglas Gregora59e3902010-01-21 23:27:09 +0000466 if (clang_isStatement(Cursor.kind))
467 return Visit(getCursorStmt(Cursor));
468 if (clang_isExpression(Cursor.kind))
469 return Visit(getCursorExpr(Cursor));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000470
Douglas Gregorb1373d02010-01-20 20:59:29 +0000471 if (clang_isTranslationUnit(Cursor.kind)) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000472 ASTUnit *CXXUnit = getCursorASTUnit(Cursor);
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000473 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
474 RegionOfInterest.isInvalid()) {
Douglas Gregor7b691f332010-01-20 21:13:59 +0000475 const std::vector<Decl*> &TLDs = CXXUnit->getTopLevelDecls();
476 for (std::vector<Decl*>::const_iterator it = TLDs.begin(),
477 ie = TLDs.end(); it != ie; ++it) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000478 if (Visit(MakeCXCursor(*it, CXXUnit), true))
Douglas Gregor7b691f332010-01-20 21:13:59 +0000479 return true;
480 }
Douglas Gregor0396f462010-03-19 05:22:59 +0000481 } else if (VisitDeclContext(
482 CXXUnit->getASTContext().getTranslationUnitDecl()))
483 return true;
Bob Wilson3178cb62010-03-19 03:57:57 +0000484
Douglas Gregor0396f462010-03-19 05:22:59 +0000485 // Walk the preprocessing record.
Daniel Dunbar8de30ff2010-03-20 01:11:56 +0000486 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000487 // FIXME: Once we have the ability to deserialize a preprocessing record,
488 // do so.
Douglas Gregor788f5a12010-03-20 00:41:21 +0000489 PreprocessingRecord::iterator E, EEnd;
490 for (llvm::tie(E, EEnd) = getPreprocessedEntities(); E != EEnd; ++E) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000491 if (MacroInstantiation *MI = dyn_cast<MacroInstantiation>(*E)) {
492 if (Visit(MakeMacroInstantiationCursor(MI, CXXUnit)))
493 return true;
Douglas Gregor788f5a12010-03-20 00:41:21 +0000494
Douglas Gregor0396f462010-03-19 05:22:59 +0000495 continue;
496 }
497
498 if (MacroDefinition *MD = dyn_cast<MacroDefinition>(*E)) {
499 if (Visit(MakeMacroDefinitionCursor(MD, CXXUnit)))
500 return true;
501
502 continue;
503 }
504 }
505 }
Douglas Gregor7b691f332010-01-20 21:13:59 +0000506 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000507 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000508
Douglas Gregorb1373d02010-01-20 20:59:29 +0000509 // Nothing to visit at the moment.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000510 return false;
511}
512
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000513bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
514 for (BlockDecl::param_iterator I=B->param_begin(), E=B->param_end(); I!=E;++I)
515 if (Decl *D = *I)
516 if (Visit(D))
517 return true;
518
519 return Visit(MakeCXCursor(B->getBody(), StmtParent, TU));
520}
521
Douglas Gregorb1373d02010-01-20 20:59:29 +0000522bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000523 for (DeclContext::decl_iterator
Douglas Gregorb1373d02010-01-20 20:59:29 +0000524 I = DC->decls_begin(), E = DC->decls_end(); I != E; ++I) {
Ted Kremenek09dfa372010-02-18 05:46:33 +0000525
Daniel Dunbard52864b2010-02-14 10:02:57 +0000526 CXCursor Cursor = MakeCXCursor(*I, TU);
527
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000528 if (RegionOfInterest.isValid()) {
Daniel Dunbard52864b2010-02-14 10:02:57 +0000529 SourceRange Range =
530 cxloc::translateCXSourceRange(clang_getCursorExtent(Cursor));
531 if (Range.isInvalid())
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000532 continue;
Daniel Dunbard52864b2010-02-14 10:02:57 +0000533
534 switch (CompareRegionOfInterest(Range)) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000535 case RangeBefore:
536 // This declaration comes before the region of interest; skip it.
537 continue;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000538
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000539 case RangeAfter:
540 // This declaration comes after the region of interest; we're done.
541 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000542
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000543 case RangeOverlap:
544 // This declaration overlaps the region of interest; visit it.
545 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000546 }
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000547 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000548
Daniel Dunbard52864b2010-02-14 10:02:57 +0000549 if (Visit(Cursor, true))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000550 return true;
551 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000552
Douglas Gregorb1373d02010-01-20 20:59:29 +0000553 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000554}
555
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000556bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
557 llvm_unreachable("Translation units are visited directly by Visit()");
558 return false;
559}
560
561bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
562 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
563 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000564
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000565 return false;
566}
567
568bool CursorVisitor::VisitTagDecl(TagDecl *D) {
569 return VisitDeclContext(D);
570}
571
572bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
573 if (Expr *Init = D->getInitExpr())
574 return Visit(MakeCXCursor(Init, StmtParent, TU));
575 return false;
576}
577
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000578bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
579 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
580 if (Visit(TSInfo->getTypeLoc()))
581 return true;
582
583 return false;
584}
585
Douglas Gregorb1373d02010-01-20 20:59:29 +0000586bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000587 if (VisitDeclaratorDecl(ND))
588 return true;
589
Douglas Gregora59e3902010-01-21 23:27:09 +0000590 if (ND->isThisDeclarationADefinition() &&
591 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
592 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000593
Douglas Gregorb1373d02010-01-20 20:59:29 +0000594 return false;
595}
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000596
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000597bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
598 if (VisitDeclaratorDecl(D))
599 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000600
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000601 if (Expr *BitWidth = D->getBitWidth())
602 return Visit(MakeCXCursor(BitWidth, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000603
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000604 return false;
605}
606
607bool CursorVisitor::VisitVarDecl(VarDecl *D) {
608 if (VisitDeclaratorDecl(D))
609 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000610
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000611 if (Expr *Init = D->getInit())
612 return Visit(MakeCXCursor(Init, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000613
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000614 return false;
615}
616
617bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
Douglas Gregor4bc1cb62010-03-08 14:59:44 +0000618 if (TypeSourceInfo *TSInfo = ND->getResultTypeSourceInfo())
619 if (Visit(TSInfo->getTypeLoc()))
620 return true;
621
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000622 for (ObjCMethodDecl::param_iterator P = ND->param_begin(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000623 PEnd = ND->param_end();
624 P != PEnd; ++P) {
625 if (Visit(MakeCXCursor(*P, TU)))
626 return true;
627 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000628
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000629 if (ND->isThisDeclarationADefinition() &&
630 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
631 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000632
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000633 return false;
634}
635
Douglas Gregora59e3902010-01-21 23:27:09 +0000636bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
637 return VisitDeclContext(D);
638}
639
Douglas Gregorb1373d02010-01-20 20:59:29 +0000640bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000641 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
642 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000643 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000644
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000645 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
646 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
647 E = ND->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000648 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000649 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000650
Douglas Gregora59e3902010-01-21 23:27:09 +0000651 return VisitObjCContainerDecl(ND);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000652}
653
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000654bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
655 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
656 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
657 E = PID->protocol_end(); I != E; ++I, ++PL)
658 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
659 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000660
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000661 return VisitObjCContainerDecl(PID);
662}
663
Douglas Gregorb1373d02010-01-20 20:59:29 +0000664bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000665 // Issue callbacks for super class.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000666 if (D->getSuperClass() &&
667 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000668 D->getSuperClassLoc(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000669 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000670 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000671
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000672 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
673 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
674 E = D->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000675 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000676 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000677
Douglas Gregora59e3902010-01-21 23:27:09 +0000678 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000679}
680
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000681bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
682 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000683}
684
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000685bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
Ted Kremenekebfa3392010-03-19 20:39:03 +0000686 // 'ID' could be null when dealing with invalid code.
687 if (ObjCInterfaceDecl *ID = D->getClassInterface())
688 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
689 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000690
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000691 return VisitObjCImplDecl(D);
692}
693
694bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
695#if 0
696 // Issue callbacks for super class.
697 // FIXME: No source location information!
698 if (D->getSuperClass() &&
699 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000700 D->getSuperClassLoc(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000701 TU)))
702 return true;
703#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000704
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000705 return VisitObjCImplDecl(D);
706}
707
708bool CursorVisitor::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D) {
709 ObjCForwardProtocolDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
710 for (ObjCForwardProtocolDecl::protocol_iterator I = D->protocol_begin(),
711 E = D->protocol_end();
712 I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000713 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000714 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000715
716 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000717}
718
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000719bool CursorVisitor::VisitObjCClassDecl(ObjCClassDecl *D) {
720 for (ObjCClassDecl::iterator C = D->begin(), CEnd = D->end(); C != CEnd; ++C)
721 if (Visit(MakeCursorObjCClassRef(C->getInterface(), C->getLocation(), TU)))
722 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000723
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000724 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000725}
726
Ted Kremenek8f06e0e2010-05-06 23:38:21 +0000727bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
728 return VisitDeclContext(D);
729}
730
Ted Kremeneka0536d82010-05-07 01:04:29 +0000731bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
732 return VisitDeclContext(D);
733}
734
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000735bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
736 ASTContext &Context = TU->getASTContext();
737
738 // Some builtin types (such as Objective-C's "id", "sel", and
739 // "Class") have associated declarations. Create cursors for those.
740 QualType VisitType;
741 switch (TL.getType()->getAs<BuiltinType>()->getKind()) {
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000742 case BuiltinType::Void:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000743 case BuiltinType::Bool:
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000744 case BuiltinType::Char_U:
745 case BuiltinType::UChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000746 case BuiltinType::Char16:
747 case BuiltinType::Char32:
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000748 case BuiltinType::UShort:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000749 case BuiltinType::UInt:
750 case BuiltinType::ULong:
751 case BuiltinType::ULongLong:
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000752 case BuiltinType::UInt128:
753 case BuiltinType::Char_S:
754 case BuiltinType::SChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000755 case BuiltinType::WChar:
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000756 case BuiltinType::Short:
757 case BuiltinType::Int:
758 case BuiltinType::Long:
759 case BuiltinType::LongLong:
760 case BuiltinType::Int128:
761 case BuiltinType::Float:
762 case BuiltinType::Double:
763 case BuiltinType::LongDouble:
764 case BuiltinType::NullPtr:
765 case BuiltinType::Overload:
766 case BuiltinType::Dependent:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000767 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000768
769 case BuiltinType::UndeducedAuto: // FIXME: Deserves a cursor?
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000770 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000771
Ted Kremenekc4174cc2010-02-18 18:52:18 +0000772 case BuiltinType::ObjCId:
773 VisitType = Context.getObjCIdType();
774 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000775
776 case BuiltinType::ObjCClass:
777 VisitType = Context.getObjCClassType();
778 break;
779
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000780 case BuiltinType::ObjCSel:
781 VisitType = Context.getObjCSelType();
782 break;
783 }
784
785 if (!VisitType.isNull()) {
786 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000787 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000788 TU));
789 }
790
791 return false;
792}
793
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000794bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
795 return Visit(MakeCursorTypeRef(TL.getTypedefDecl(), TL.getNameLoc(), TU));
796}
797
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000798bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
799 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
800}
801
802bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
803 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
804}
805
806bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
807 if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
808 return true;
809
810 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
811 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
812 TU)))
813 return true;
814 }
815
816 return false;
817}
818
819bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
820 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseTypeLoc()))
821 return true;
822
823 if (TL.hasProtocolsAsWritten()) {
824 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000825 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I),
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000826 TL.getProtocolLoc(I),
827 TU)))
828 return true;
829 }
830 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000831
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000832 return false;
833}
834
835bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
836 return Visit(TL.getPointeeLoc());
837}
838
839bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
840 return Visit(TL.getPointeeLoc());
841}
842
843bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
844 return Visit(TL.getPointeeLoc());
845}
846
847bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000848 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000849}
850
851bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000852 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000853}
854
855bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
856 if (Visit(TL.getResultLoc()))
857 return true;
858
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000859 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
Ted Kremenek5dbacb42010-04-07 00:27:13 +0000860 if (Decl *D = TL.getArg(I))
861 if (Visit(MakeCXCursor(D, TU)))
862 return true;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000863
864 return false;
865}
866
867bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
868 if (Visit(TL.getElementLoc()))
869 return true;
870
871 if (Expr *Size = TL.getSizeExpr())
872 return Visit(MakeCXCursor(Size, StmtParent, TU));
873
874 return false;
875}
876
Douglas Gregor2332c112010-01-21 20:48:56 +0000877bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
878 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
879}
880
881bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
882 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
883 return Visit(TSInfo->getTypeLoc());
884
885 return false;
886}
887
Douglas Gregora59e3902010-01-21 23:27:09 +0000888bool CursorVisitor::VisitStmt(Stmt *S) {
889 for (Stmt::child_iterator Child = S->child_begin(), ChildEnd = S->child_end();
890 Child != ChildEnd; ++Child) {
Daniel Dunbar54d67ca2010-01-25 00:40:30 +0000891 if (*Child && Visit(MakeCXCursor(*Child, StmtParent, 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
898bool CursorVisitor::VisitDeclStmt(DeclStmt *S) {
899 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
900 D != DEnd; ++D) {
Douglas Gregor263b47b2010-01-25 16:12:32 +0000901 if (*D && Visit(MakeCXCursor(*D, TU)))
Douglas Gregora59e3902010-01-21 23:27:09 +0000902 return true;
903 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000904
Douglas Gregora59e3902010-01-21 23:27:09 +0000905 return false;
906}
907
Douglas Gregorf5bab412010-01-22 01:00:11 +0000908bool CursorVisitor::VisitIfStmt(IfStmt *S) {
909 if (VarDecl *Var = S->getConditionVariable()) {
910 if (Visit(MakeCXCursor(Var, TU)))
911 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000912 }
913
Douglas Gregor263b47b2010-01-25 16:12:32 +0000914 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
915 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +0000916 if (S->getThen() && Visit(MakeCXCursor(S->getThen(), StmtParent, TU)))
917 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +0000918 if (S->getElse() && Visit(MakeCXCursor(S->getElse(), StmtParent, TU)))
919 return true;
920
921 return false;
922}
923
924bool CursorVisitor::VisitSwitchStmt(SwitchStmt *S) {
925 if (VarDecl *Var = S->getConditionVariable()) {
926 if (Visit(MakeCXCursor(Var, TU)))
927 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000928 }
929
Douglas Gregor263b47b2010-01-25 16:12:32 +0000930 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
931 return true;
932 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
933 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000934
Douglas Gregor263b47b2010-01-25 16:12:32 +0000935 return false;
936}
937
938bool CursorVisitor::VisitWhileStmt(WhileStmt *S) {
939 if (VarDecl *Var = S->getConditionVariable()) {
940 if (Visit(MakeCXCursor(Var, TU)))
941 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000942 }
943
Douglas Gregor263b47b2010-01-25 16:12:32 +0000944 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
945 return true;
946 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
Douglas Gregorf5bab412010-01-22 01:00:11 +0000947 return true;
948
Douglas Gregor263b47b2010-01-25 16:12:32 +0000949 return false;
950}
951
952bool CursorVisitor::VisitForStmt(ForStmt *S) {
953 if (S->getInit() && Visit(MakeCXCursor(S->getInit(), StmtParent, TU)))
954 return true;
955 if (VarDecl *Var = S->getConditionVariable()) {
956 if (Visit(MakeCXCursor(Var, TU)))
957 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000958 }
959
Douglas Gregor263b47b2010-01-25 16:12:32 +0000960 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
961 return true;
962 if (S->getInc() && Visit(MakeCXCursor(S->getInc(), StmtParent, TU)))
963 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +0000964 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
965 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000966
Douglas Gregorf5bab412010-01-22 01:00:11 +0000967 return false;
968}
969
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000970bool CursorVisitor::VisitBlockExpr(BlockExpr *B) {
971 return Visit(B->getBlockDecl());
972}
973
Douglas Gregor8ecdb652010-04-28 22:16:22 +0000974bool CursorVisitor::VisitOffsetOfExpr(OffsetOfExpr *E) {
975 // FIXME: Visit fields as well?
976 if (Visit(E->getTypeSourceInfo()->getTypeLoc()))
977 return true;
978
979 return VisitExpr(E);
980}
981
Douglas Gregor336fd812010-01-23 00:40:08 +0000982bool CursorVisitor::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E) {
983 if (E->isArgumentType()) {
984 if (TypeSourceInfo *TSInfo = E->getArgumentTypeInfo())
985 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000986
Douglas Gregor336fd812010-01-23 00:40:08 +0000987 return false;
988 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000989
Douglas Gregor336fd812010-01-23 00:40:08 +0000990 return VisitExpr(E);
991}
992
993bool CursorVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
994 if (TypeSourceInfo *TSInfo = E->getTypeInfoAsWritten())
995 if (Visit(TSInfo->getTypeLoc()))
996 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000997
Douglas Gregor336fd812010-01-23 00:40:08 +0000998 return VisitCastExpr(E);
999}
1000
1001bool CursorVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
1002 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
1003 if (Visit(TSInfo->getTypeLoc()))
1004 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001005
Douglas Gregor336fd812010-01-23 00:40:08 +00001006 return VisitExpr(E);
1007}
1008
Douglas Gregorc2350e52010-03-08 16:40:19 +00001009bool CursorVisitor::VisitObjCMessageExpr(ObjCMessageExpr *E) {
Douglas Gregor04badcf2010-04-21 00:45:42 +00001010 if (TypeSourceInfo *TSInfo = E->getClassReceiverTypeInfo())
1011 if (Visit(TSInfo->getTypeLoc()))
1012 return true;
Douglas Gregorc2350e52010-03-08 16:40:19 +00001013
1014 return VisitExpr(E);
1015}
1016
Douglas Gregor81d34662010-04-20 15:39:42 +00001017bool CursorVisitor::VisitObjCEncodeExpr(ObjCEncodeExpr *E) {
1018 return Visit(E->getEncodedTypeSourceInfo()->getTypeLoc());
1019}
1020
1021
Ted Kremenek09dfa372010-02-18 05:46:33 +00001022bool CursorVisitor::VisitAttributes(Decl *D) {
1023 for (const Attr *A = D->getAttrs(); A; A = A->getNext())
1024 if (Visit(MakeCXCursor(A, D, TU)))
1025 return true;
1026
1027 return false;
1028}
1029
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00001030extern "C" {
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001031CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
1032 int displayDiagnostics) {
Douglas Gregora030b7c2010-01-22 20:35:53 +00001033 CIndexer *CIdxr = new CIndexer();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001034 if (excludeDeclarationsFromPCH)
1035 CIdxr->setOnlyLocalDecls();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001036 if (displayDiagnostics)
1037 CIdxr->setDisplayDiagnostics();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001038 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +00001039}
1040
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001041void clang_disposeIndex(CXIndex CIdx) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001042 if (CIdx)
1043 delete static_cast<CIndexer *>(CIdx);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00001044}
1045
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001046void clang_setUseExternalASTGeneration(CXIndex CIdx, int value) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001047 if (CIdx) {
1048 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
1049 CXXIdx->setUseExternalASTGeneration(value);
1050 }
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001051}
1052
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001053CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
Douglas Gregora88084b2010-02-18 18:08:43 +00001054 const char *ast_filename) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001055 if (!CIdx)
1056 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001057
Douglas Gregor7d1d49d2009-10-16 20:01:17 +00001058 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001059
Douglas Gregor28019772010-04-05 23:52:57 +00001060 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
1061 return ASTUnit::LoadFromPCHFile(ast_filename, Diags,
Douglas Gregora88084b2010-02-18 18:08:43 +00001062 CXXIdx->getOnlyLocalDecls(),
1063 0, 0, true);
Steve Naroff600866c2009-08-27 19:51:58 +00001064}
1065
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001066CXTranslationUnit
1067clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
1068 const char *source_filename,
1069 int num_command_line_args,
Douglas Gregor4db64a42010-01-23 00:14:00 +00001070 const char **command_line_args,
1071 unsigned num_unsaved_files,
Douglas Gregora88084b2010-02-18 18:08:43 +00001072 struct CXUnsavedFile *unsaved_files) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001073 if (!CIdx)
1074 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001075
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001076 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
1077
Douglas Gregor5352ac02010-01-28 00:27:43 +00001078 // Configure the diagnostics.
1079 DiagnosticOptions DiagOpts;
Douglas Gregor28019772010-04-05 23:52:57 +00001080 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
1081 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001082
Douglas Gregor4db64a42010-01-23 00:14:00 +00001083 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
1084 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattnera0a270c2010-04-05 22:42:27 +00001085 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001086 const llvm::MemoryBuffer *Buffer
Chris Lattnera0a270c2010-04-05 22:42:27 +00001087 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregor4db64a42010-01-23 00:14:00 +00001088 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
1089 Buffer));
1090 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001091
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001092 if (!CXXIdx->getUseExternalASTGeneration()) {
1093 llvm::SmallVector<const char *, 16> Args;
1094
1095 // The 'source_filename' argument is optional. If the caller does not
1096 // specify it then it is assumed that the source file is specified
1097 // in the actual argument list.
1098 if (source_filename)
1099 Args.push_back(source_filename);
1100 Args.insert(Args.end(), command_line_args,
1101 command_line_args + num_command_line_args);
Douglas Gregor94dc8f62010-03-19 16:15:56 +00001102 Args.push_back("-Xclang");
1103 Args.push_back("-detailed-preprocessing-record");
Douglas Gregor5352ac02010-01-28 00:27:43 +00001104 unsigned NumErrors = Diags->getNumErrors();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001105
Ted Kremenek29b72842010-01-07 22:49:05 +00001106#ifdef USE_CRASHTRACER
1107 ArgsCrashTracerInfo ACTI(Args);
Ted Kremenek8a8da7d2010-01-06 03:42:32 +00001108#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001109
Daniel Dunbar94220972009-12-05 02:17:18 +00001110 llvm::OwningPtr<ASTUnit> Unit(
1111 ASTUnit::LoadFromCommandLine(Args.data(), Args.data() + Args.size(),
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001112 Diags,
Daniel Dunbar869824e2009-12-13 03:46:13 +00001113 CXXIdx->getClangResourcesPath(),
Daniel Dunbar94220972009-12-05 02:17:18 +00001114 CXXIdx->getOnlyLocalDecls(),
Douglas Gregor4db64a42010-01-23 00:14:00 +00001115 RemappedFiles.data(),
Douglas Gregora88084b2010-02-18 18:08:43 +00001116 RemappedFiles.size(),
Douglas Gregor94dc8f62010-03-19 16:15:56 +00001117 /*CaptureDiagnostics=*/true));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001118
Daniel Dunbar94220972009-12-05 02:17:18 +00001119 // FIXME: Until we have broader testing, just drop the entire AST if we
1120 // encountered an error.
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001121 if (NumErrors != Diags->getNumErrors()) {
Ted Kremenek34f6a322010-03-05 22:43:29 +00001122 // Make sure to check that 'Unit' is non-NULL.
1123 if (CXXIdx->getDisplayDiagnostics() && Unit.get()) {
Douglas Gregor405634b2010-04-05 18:10:21 +00001124 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
1125 DEnd = Unit->stored_diag_end();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001126 D != DEnd; ++D) {
1127 CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOptions());
Douglas Gregor274f1902010-02-22 23:17:23 +00001128 CXString Msg = clang_formatDiagnostic(&Diag,
1129 clang_defaultDiagnosticDisplayOptions());
1130 fprintf(stderr, "%s\n", clang_getCString(Msg));
1131 clang_disposeString(Msg);
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001132 }
Douglas Gregor274f1902010-02-22 23:17:23 +00001133#ifdef LLVM_ON_WIN32
1134 // On Windows, force a flush, since there may be multiple copies of
1135 // stderr and stdout in the file system, all with different buffers
1136 // but writing to the same device.
1137 fflush(stderr);
Ted Kremenek83c51842010-03-26 01:34:51 +00001138#endif
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001139 }
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001140 }
Daniel Dunbar94220972009-12-05 02:17:18 +00001141
1142 return Unit.take();
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001143 }
1144
Ted Kremenek139ba862009-10-22 00:03:57 +00001145 // Build up the arguments for invoking 'clang'.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001146 std::vector<const char *> argv;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001147
Ted Kremenek139ba862009-10-22 00:03:57 +00001148 // First add the complete path to the 'clang' executable.
1149 llvm::sys::Path ClangPath = static_cast<CIndexer *>(CIdx)->getClangPath();
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00001150 argv.push_back(ClangPath.c_str());
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001151
Ted Kremenek139ba862009-10-22 00:03:57 +00001152 // Add the '-emit-ast' option as our execution mode for 'clang'.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001153 argv.push_back("-emit-ast");
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001154
Ted Kremenek139ba862009-10-22 00:03:57 +00001155 // The 'source_filename' argument is optional. If the caller does not
1156 // specify it then it is assumed that the source file is specified
1157 // in the actual argument list.
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001158 if (source_filename)
1159 argv.push_back(source_filename);
Ted Kremenek139ba862009-10-22 00:03:57 +00001160
Steve Naroff37b5ac22009-10-15 20:50:09 +00001161 // Generate a temporary name for the AST file.
Ted Kremenek139ba862009-10-22 00:03:57 +00001162 argv.push_back("-o");
Benjamin Kramerc2a98162010-03-13 21:22:49 +00001163 char astTmpFile[L_tmpnam];
1164 argv.push_back(tmpnam(astTmpFile));
Ted Kremenek139ba862009-10-22 00:03:57 +00001165
Douglas Gregor4db64a42010-01-23 00:14:00 +00001166 // Remap any unsaved files to temporary files.
1167 std::vector<llvm::sys::Path> TemporaryFiles;
1168 std::vector<std::string> RemapArgs;
1169 if (RemapFiles(num_unsaved_files, unsaved_files, RemapArgs, TemporaryFiles))
1170 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001171
Douglas Gregor4db64a42010-01-23 00:14:00 +00001172 // The pointers into the elements of RemapArgs are stable because we
1173 // won't be adding anything to RemapArgs after this point.
1174 for (unsigned i = 0, e = RemapArgs.size(); i != e; ++i)
1175 argv.push_back(RemapArgs[i].c_str());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001176
Ted Kremenek139ba862009-10-22 00:03:57 +00001177 // Process the compiler options, stripping off '-o', '-c', '-fsyntax-only'.
1178 for (int i = 0; i < num_command_line_args; ++i)
1179 if (const char *arg = command_line_args[i]) {
1180 if (strcmp(arg, "-o") == 0) {
1181 ++i; // Also skip the matching argument.
1182 continue;
1183 }
1184 if (strcmp(arg, "-emit-ast") == 0 ||
1185 strcmp(arg, "-c") == 0 ||
1186 strcmp(arg, "-fsyntax-only") == 0) {
1187 continue;
1188 }
1189
1190 // Keep the argument.
1191 argv.push_back(arg);
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001192 }
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001193
Douglas Gregord93256e2010-01-28 06:00:51 +00001194 // Generate a temporary name for the diagnostics file.
Benjamin Kramerc2a98162010-03-13 21:22:49 +00001195 char tmpFileResults[L_tmpnam];
1196 char *tmpResultsFileName = tmpnam(tmpFileResults);
1197 llvm::sys::Path DiagnosticsFile(tmpResultsFileName);
Douglas Gregord93256e2010-01-28 06:00:51 +00001198 TemporaryFiles.push_back(DiagnosticsFile);
1199 argv.push_back("-fdiagnostics-binary");
1200
Douglas Gregor94dc8f62010-03-19 16:15:56 +00001201 argv.push_back("-Xclang");
1202 argv.push_back("-detailed-preprocessing-record");
1203
Ted Kremenek139ba862009-10-22 00:03:57 +00001204 // Add the null terminator.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001205 argv.push_back(NULL);
1206
Ted Kremenekfeb15e32009-10-26 22:14:08 +00001207 // Invoke 'clang'.
1208 llvm::sys::Path DevNull; // leave empty, causes redirection to /dev/null
1209 // on Unix or NUL (Windows).
Ted Kremenek379afec2009-10-22 03:24:01 +00001210 std::string ErrMsg;
Douglas Gregord93256e2010-01-28 06:00:51 +00001211 const llvm::sys::Path *Redirects[] = { &DevNull, &DevNull, &DiagnosticsFile,
1212 NULL };
Ted Kremenek379afec2009-10-22 03:24:01 +00001213 llvm::sys::Program::ExecuteAndWait(ClangPath, &argv[0], /* env */ NULL,
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001214 /* redirects */ &Redirects[0],
Ted Kremenek379afec2009-10-22 03:24:01 +00001215 /* secondsToWait */ 0, /* memoryLimits */ 0, &ErrMsg);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001216
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001217 if (!ErrMsg.empty()) {
1218 std::string AllArgs;
Ted Kremenek379afec2009-10-22 03:24:01 +00001219 for (std::vector<const char*>::iterator I = argv.begin(), E = argv.end();
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001220 I != E; ++I) {
1221 AllArgs += ' ';
Ted Kremenek779e5f42009-10-26 22:08:39 +00001222 if (*I)
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001223 AllArgs += *I;
Ted Kremenek779e5f42009-10-26 22:08:39 +00001224 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001225
Daniel Dunbar32141c82010-02-23 20:23:45 +00001226 Diags->Report(diag::err_fe_invoking) << AllArgs << ErrMsg;
Ted Kremenek379afec2009-10-22 03:24:01 +00001227 }
Benjamin Kramer0829a832009-10-18 11:19:36 +00001228
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001229 ASTUnit *ATU = ASTUnit::LoadFromPCHFile(astTmpFile, Diags,
Douglas Gregor4db64a42010-01-23 00:14:00 +00001230 CXXIdx->getOnlyLocalDecls(),
Douglas Gregor4db64a42010-01-23 00:14:00 +00001231 RemappedFiles.data(),
Douglas Gregora88084b2010-02-18 18:08:43 +00001232 RemappedFiles.size(),
1233 /*CaptureDiagnostics=*/true);
Douglas Gregora88084b2010-02-18 18:08:43 +00001234 if (ATU) {
1235 LoadSerializedDiagnostics(DiagnosticsFile,
1236 num_unsaved_files, unsaved_files,
1237 ATU->getFileManager(),
1238 ATU->getSourceManager(),
Douglas Gregor405634b2010-04-05 18:10:21 +00001239 ATU->getStoredDiagnostics());
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001240 } else if (CXXIdx->getDisplayDiagnostics()) {
1241 // We failed to load the ASTUnit, but we can still deserialize the
1242 // diagnostics and emit them.
1243 FileManager FileMgr;
Douglas Gregorf715ca12010-03-16 00:06:06 +00001244 Diagnostic Diag;
1245 SourceManager SourceMgr(Diag);
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001246 // FIXME: Faked LangOpts!
1247 LangOptions LangOpts;
1248 llvm::SmallVector<StoredDiagnostic, 4> Diags;
1249 LoadSerializedDiagnostics(DiagnosticsFile,
1250 num_unsaved_files, unsaved_files,
1251 FileMgr, SourceMgr, Diags);
1252 for (llvm::SmallVector<StoredDiagnostic, 4>::iterator D = Diags.begin(),
1253 DEnd = Diags.end();
1254 D != DEnd; ++D) {
1255 CXStoredDiagnostic Diag(*D, LangOpts);
Douglas Gregor274f1902010-02-22 23:17:23 +00001256 CXString Msg = clang_formatDiagnostic(&Diag,
1257 clang_defaultDiagnosticDisplayOptions());
1258 fprintf(stderr, "%s\n", clang_getCString(Msg));
1259 clang_disposeString(Msg);
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001260 }
Douglas Gregor274f1902010-02-22 23:17:23 +00001261
1262#ifdef LLVM_ON_WIN32
1263 // On Windows, force a flush, since there may be multiple copies of
1264 // stderr and stdout in the file system, all with different buffers
1265 // but writing to the same device.
1266 fflush(stderr);
1267#endif
Douglas Gregora88084b2010-02-18 18:08:43 +00001268 }
Douglas Gregord93256e2010-01-28 06:00:51 +00001269
Douglas Gregor313e26c2010-02-18 23:35:40 +00001270 if (ATU) {
1271 // Make the translation unit responsible for destroying all temporary files.
1272 for (unsigned i = 0, e = TemporaryFiles.size(); i != e; ++i)
1273 ATU->addTemporaryFile(TemporaryFiles[i]);
1274 ATU->addTemporaryFile(llvm::sys::Path(ATU->getPCHFileName()));
1275 } else {
1276 // Destroy all of the temporary files now; they can't be referenced any
1277 // longer.
1278 llvm::sys::Path(astTmpFile).eraseFromDisk();
1279 for (unsigned i = 0, e = TemporaryFiles.size(); i != e; ++i)
1280 TemporaryFiles[i].eraseFromDisk();
1281 }
1282
Steve Naroffe19944c2009-10-15 22:23:48 +00001283 return ATU;
Steve Naroff5b7d8e22009-10-15 20:04:39 +00001284}
1285
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001286void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001287 if (CTUnit)
1288 delete static_cast<ASTUnit *>(CTUnit);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00001289}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001290
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001291CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001292 if (!CTUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001293 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001294
Steve Naroff77accc12009-09-03 18:19:54 +00001295 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001296 return createCXString(CXXUnit->getOriginalSourceFileName(), true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +00001297}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +00001298
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001299CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001300 CXCursor Result = { CXCursor_TranslationUnit, { 0, 0, TU } };
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001301 return Result;
1302}
1303
Ted Kremenekfb480492010-01-13 21:46:36 +00001304} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +00001305
Ted Kremenekfb480492010-01-13 21:46:36 +00001306//===----------------------------------------------------------------------===//
Douglas Gregor1db19de2010-01-19 21:36:55 +00001307// CXSourceLocation and CXSourceRange Operations.
1308//===----------------------------------------------------------------------===//
1309
Douglas Gregorb9790342010-01-22 21:44:22 +00001310extern "C" {
1311CXSourceLocation clang_getNullLocation() {
Douglas Gregor5352ac02010-01-28 00:27:43 +00001312 CXSourceLocation Result = { { 0, 0 }, 0 };
Douglas Gregorb9790342010-01-22 21:44:22 +00001313 return Result;
1314}
1315
1316unsigned clang_equalLocations(CXSourceLocation loc1, CXSourceLocation loc2) {
Daniel Dunbar90a6b9e2010-01-30 23:58:27 +00001317 return (loc1.ptr_data[0] == loc2.ptr_data[0] &&
1318 loc1.ptr_data[1] == loc2.ptr_data[1] &&
1319 loc1.int_data == loc2.int_data);
Douglas Gregorb9790342010-01-22 21:44:22 +00001320}
1321
1322CXSourceLocation clang_getLocation(CXTranslationUnit tu,
1323 CXFile file,
1324 unsigned line,
1325 unsigned column) {
Douglas Gregor42748ec2010-04-30 19:45:53 +00001326 if (!tu || !file)
Douglas Gregorb9790342010-01-22 21:44:22 +00001327 return clang_getNullLocation();
Douglas Gregor42748ec2010-04-30 19:45:53 +00001328
Douglas Gregorb9790342010-01-22 21:44:22 +00001329 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
1330 SourceLocation SLoc
1331 = CXXUnit->getSourceManager().getLocation(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001332 static_cast<const FileEntry *>(file),
Douglas Gregorb9790342010-01-22 21:44:22 +00001333 line, column);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001334
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00001335 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
Douglas Gregorb9790342010-01-22 21:44:22 +00001336}
1337
Douglas Gregor5352ac02010-01-28 00:27:43 +00001338CXSourceRange clang_getNullRange() {
1339 CXSourceRange Result = { { 0, 0 }, 0, 0 };
1340 return Result;
1341}
Daniel Dunbard52864b2010-02-14 10:02:57 +00001342
Douglas Gregor5352ac02010-01-28 00:27:43 +00001343CXSourceRange clang_getRange(CXSourceLocation begin, CXSourceLocation end) {
1344 if (begin.ptr_data[0] != end.ptr_data[0] ||
1345 begin.ptr_data[1] != end.ptr_data[1])
1346 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001347
1348 CXSourceRange Result = { { begin.ptr_data[0], begin.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00001349 begin.int_data, end.int_data };
Douglas Gregorb9790342010-01-22 21:44:22 +00001350 return Result;
1351}
1352
Douglas Gregor46766dc2010-01-26 19:19:08 +00001353void clang_getInstantiationLocation(CXSourceLocation location,
1354 CXFile *file,
1355 unsigned *line,
1356 unsigned *column,
1357 unsigned *offset) {
Douglas Gregor1db19de2010-01-19 21:36:55 +00001358 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
1359
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00001360 if (!location.ptr_data[0] || Loc.isInvalid()) {
Douglas Gregor46766dc2010-01-26 19:19:08 +00001361 if (file)
1362 *file = 0;
1363 if (line)
1364 *line = 0;
1365 if (column)
1366 *column = 0;
1367 if (offset)
1368 *offset = 0;
1369 return;
1370 }
1371
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00001372 const SourceManager &SM =
1373 *static_cast<const SourceManager*>(location.ptr_data[0]);
Douglas Gregor1db19de2010-01-19 21:36:55 +00001374 SourceLocation InstLoc = SM.getInstantiationLoc(Loc);
Douglas Gregor1db19de2010-01-19 21:36:55 +00001375
1376 if (file)
1377 *file = (void *)SM.getFileEntryForID(SM.getFileID(InstLoc));
1378 if (line)
1379 *line = SM.getInstantiationLineNumber(InstLoc);
1380 if (column)
1381 *column = SM.getInstantiationColumnNumber(InstLoc);
Douglas Gregore69517c2010-01-26 03:07:15 +00001382 if (offset)
Douglas Gregor46766dc2010-01-26 19:19:08 +00001383 *offset = SM.getDecomposedLoc(InstLoc).second;
Douglas Gregore69517c2010-01-26 03:07:15 +00001384}
1385
Douglas Gregor1db19de2010-01-19 21:36:55 +00001386CXSourceLocation clang_getRangeStart(CXSourceRange range) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001387 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00001388 range.begin_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00001389 return Result;
1390}
1391
1392CXSourceLocation clang_getRangeEnd(CXSourceRange range) {
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00001393 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00001394 range.end_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00001395 return Result;
1396}
1397
Douglas Gregorb9790342010-01-22 21:44:22 +00001398} // end: extern "C"
1399
Douglas Gregor1db19de2010-01-19 21:36:55 +00001400//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00001401// CXFile Operations.
1402//===----------------------------------------------------------------------===//
1403
1404extern "C" {
Ted Kremenek74844072010-02-17 00:41:20 +00001405CXString clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00001406 if (!SFile)
Ted Kremenek74844072010-02-17 00:41:20 +00001407 return createCXString(NULL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001408
Steve Naroff88145032009-10-27 14:35:18 +00001409 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Ted Kremenek74844072010-02-17 00:41:20 +00001410 return createCXString(FEnt->getName());
Steve Naroff88145032009-10-27 14:35:18 +00001411}
1412
1413time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00001414 if (!SFile)
1415 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001416
Steve Naroff88145032009-10-27 14:35:18 +00001417 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
1418 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +00001419}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001420
Douglas Gregorb9790342010-01-22 21:44:22 +00001421CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
1422 if (!tu)
1423 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001424
Douglas Gregorb9790342010-01-22 21:44:22 +00001425 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001426
Douglas Gregorb9790342010-01-22 21:44:22 +00001427 FileManager &FMgr = CXXUnit->getFileManager();
1428 const FileEntry *File = FMgr.getFile(file_name, file_name+strlen(file_name));
1429 return const_cast<FileEntry *>(File);
1430}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001431
Ted Kremenekfb480492010-01-13 21:46:36 +00001432} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +00001433
Ted Kremenekfb480492010-01-13 21:46:36 +00001434//===----------------------------------------------------------------------===//
1435// CXCursor Operations.
1436//===----------------------------------------------------------------------===//
1437
Ted Kremenekfb480492010-01-13 21:46:36 +00001438static Decl *getDeclFromExpr(Stmt *E) {
1439 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
1440 return RefExpr->getDecl();
1441 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
1442 return ME->getMemberDecl();
1443 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
1444 return RE->getDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001445
Ted Kremenekfb480492010-01-13 21:46:36 +00001446 if (CallExpr *CE = dyn_cast<CallExpr>(E))
1447 return getDeclFromExpr(CE->getCallee());
1448 if (CastExpr *CE = dyn_cast<CastExpr>(E))
1449 return getDeclFromExpr(CE->getSubExpr());
1450 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
1451 return OME->getMethodDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001452
Ted Kremenekfb480492010-01-13 21:46:36 +00001453 return 0;
1454}
1455
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00001456static SourceLocation getLocationFromExpr(Expr *E) {
1457 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
1458 return /*FIXME:*/Msg->getLeftLoc();
1459 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
1460 return DRE->getLocation();
1461 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
1462 return Member->getMemberLoc();
1463 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
1464 return Ivar->getLocation();
1465 return E->getLocStart();
1466}
1467
Ted Kremenekfb480492010-01-13 21:46:36 +00001468extern "C" {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001469
1470unsigned clang_visitChildren(CXCursor parent,
Douglas Gregorb1373d02010-01-20 20:59:29 +00001471 CXCursorVisitor visitor,
1472 CXClientData client_data) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001473 ASTUnit *CXXUnit = getCursorASTUnit(parent);
Douglas Gregorb1373d02010-01-20 20:59:29 +00001474
1475 unsigned PCHLevel = Decl::MaxPCHLevel;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001476
Douglas Gregorb1373d02010-01-20 20:59:29 +00001477 // Set the PCHLevel to filter out unwanted decls if requested.
1478 if (CXXUnit->getOnlyLocalDecls()) {
1479 PCHLevel = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001480
Douglas Gregorb1373d02010-01-20 20:59:29 +00001481 // If the main input was an AST, bump the level.
1482 if (CXXUnit->isMainFileAST())
1483 ++PCHLevel;
1484 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001485
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001486 CursorVisitor CursorVis(CXXUnit, visitor, client_data, PCHLevel);
Douglas Gregorb1373d02010-01-20 20:59:29 +00001487 return CursorVis.VisitChildren(parent);
1488}
1489
Douglas Gregor78205d42010-01-20 21:45:58 +00001490static CXString getDeclSpelling(Decl *D) {
1491 NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
1492 if (!ND)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001493 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001494
Douglas Gregor78205d42010-01-20 21:45:58 +00001495 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001496 return createCXString(OMD->getSelector().getAsString());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001497
Douglas Gregor78205d42010-01-20 21:45:58 +00001498 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
1499 // No, this isn't the same as the code below. getIdentifier() is non-virtual
1500 // and returns different names. NamedDecl returns the class name and
1501 // ObjCCategoryImplDecl returns the category name.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001502 return createCXString(CIMP->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001503
Douglas Gregor78205d42010-01-20 21:45:58 +00001504 if (ND->getIdentifier())
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001505 return createCXString(ND->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001506
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001507 return createCXString("");
Douglas Gregor78205d42010-01-20 21:45:58 +00001508}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001509
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001510CXString clang_getCursorSpelling(CXCursor C) {
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001511 if (clang_isTranslationUnit(C.kind))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001512 return clang_getTranslationUnitSpelling(C.data[2]);
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001513
Steve Narofff334b4e2009-09-02 18:26:48 +00001514 if (clang_isReference(C.kind)) {
1515 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00001516 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +00001517 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001518 return createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00001519 }
1520 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +00001521 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001522 return createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00001523 }
1524 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +00001525 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +00001526 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001527 return createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00001528 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001529 case CXCursor_TypeRef: {
1530 TypeDecl *Type = getCursorTypeRef(C).first;
1531 assert(Type && "Missing type decl");
1532
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001533 return createCXString(getCursorContext(C).getTypeDeclType(Type).
1534 getAsString());
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001535 }
1536
Daniel Dunbaracca7252009-11-30 20:42:49 +00001537 default:
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001538 return createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +00001539 }
1540 }
Douglas Gregor97b98722010-01-19 23:20:36 +00001541
1542 if (clang_isExpression(C.kind)) {
1543 Decl *D = getDeclFromExpr(getCursorExpr(C));
1544 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +00001545 return getDeclSpelling(D);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001546 return createCXString("");
Douglas Gregor97b98722010-01-19 23:20:36 +00001547 }
1548
Douglas Gregor4ae8f292010-03-18 17:52:52 +00001549 if (C.kind == CXCursor_MacroInstantiation)
1550 return createCXString(getCursorMacroInstantiation(C)->getName()
1551 ->getNameStart());
1552
Douglas Gregor572feb22010-03-18 18:04:21 +00001553 if (C.kind == CXCursor_MacroDefinition)
1554 return createCXString(getCursorMacroDefinition(C)->getName()
1555 ->getNameStart());
1556
Douglas Gregor60cbfac2010-01-25 16:56:17 +00001557 if (clang_isDeclaration(C.kind))
1558 return getDeclSpelling(getCursorDecl(C));
Ted Kremeneke68fff62010-02-17 00:41:32 +00001559
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001560 return createCXString("");
Steve Narofff334b4e2009-09-02 18:26:48 +00001561}
1562
Ted Kremeneke68fff62010-02-17 00:41:32 +00001563CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00001564 switch (Kind) {
Ted Kremeneke68fff62010-02-17 00:41:32 +00001565 case CXCursor_FunctionDecl:
1566 return createCXString("FunctionDecl");
1567 case CXCursor_TypedefDecl:
1568 return createCXString("TypedefDecl");
1569 case CXCursor_EnumDecl:
1570 return createCXString("EnumDecl");
1571 case CXCursor_EnumConstantDecl:
1572 return createCXString("EnumConstantDecl");
1573 case CXCursor_StructDecl:
1574 return createCXString("StructDecl");
1575 case CXCursor_UnionDecl:
1576 return createCXString("UnionDecl");
1577 case CXCursor_ClassDecl:
1578 return createCXString("ClassDecl");
1579 case CXCursor_FieldDecl:
1580 return createCXString("FieldDecl");
1581 case CXCursor_VarDecl:
1582 return createCXString("VarDecl");
1583 case CXCursor_ParmDecl:
1584 return createCXString("ParmDecl");
1585 case CXCursor_ObjCInterfaceDecl:
1586 return createCXString("ObjCInterfaceDecl");
1587 case CXCursor_ObjCCategoryDecl:
1588 return createCXString("ObjCCategoryDecl");
1589 case CXCursor_ObjCProtocolDecl:
1590 return createCXString("ObjCProtocolDecl");
1591 case CXCursor_ObjCPropertyDecl:
1592 return createCXString("ObjCPropertyDecl");
1593 case CXCursor_ObjCIvarDecl:
1594 return createCXString("ObjCIvarDecl");
1595 case CXCursor_ObjCInstanceMethodDecl:
1596 return createCXString("ObjCInstanceMethodDecl");
1597 case CXCursor_ObjCClassMethodDecl:
1598 return createCXString("ObjCClassMethodDecl");
1599 case CXCursor_ObjCImplementationDecl:
1600 return createCXString("ObjCImplementationDecl");
1601 case CXCursor_ObjCCategoryImplDecl:
1602 return createCXString("ObjCCategoryImplDecl");
Ted Kremenek8bd5a692010-04-13 23:39:06 +00001603 case CXCursor_CXXMethod:
1604 return createCXString("CXXMethod");
Ted Kremeneke68fff62010-02-17 00:41:32 +00001605 case CXCursor_UnexposedDecl:
1606 return createCXString("UnexposedDecl");
1607 case CXCursor_ObjCSuperClassRef:
1608 return createCXString("ObjCSuperClassRef");
1609 case CXCursor_ObjCProtocolRef:
1610 return createCXString("ObjCProtocolRef");
1611 case CXCursor_ObjCClassRef:
1612 return createCXString("ObjCClassRef");
1613 case CXCursor_TypeRef:
1614 return createCXString("TypeRef");
1615 case CXCursor_UnexposedExpr:
1616 return createCXString("UnexposedExpr");
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00001617 case CXCursor_BlockExpr:
1618 return createCXString("BlockExpr");
Ted Kremeneke68fff62010-02-17 00:41:32 +00001619 case CXCursor_DeclRefExpr:
1620 return createCXString("DeclRefExpr");
1621 case CXCursor_MemberRefExpr:
1622 return createCXString("MemberRefExpr");
1623 case CXCursor_CallExpr:
1624 return createCXString("CallExpr");
1625 case CXCursor_ObjCMessageExpr:
1626 return createCXString("ObjCMessageExpr");
1627 case CXCursor_UnexposedStmt:
1628 return createCXString("UnexposedStmt");
1629 case CXCursor_InvalidFile:
1630 return createCXString("InvalidFile");
Ted Kremenek292db642010-03-19 20:39:05 +00001631 case CXCursor_InvalidCode:
1632 return createCXString("InvalidCode");
Ted Kremeneke68fff62010-02-17 00:41:32 +00001633 case CXCursor_NoDeclFound:
1634 return createCXString("NoDeclFound");
1635 case CXCursor_NotImplemented:
1636 return createCXString("NotImplemented");
1637 case CXCursor_TranslationUnit:
1638 return createCXString("TranslationUnit");
Ted Kremeneke77f4432010-02-18 03:09:07 +00001639 case CXCursor_UnexposedAttr:
1640 return createCXString("UnexposedAttr");
1641 case CXCursor_IBActionAttr:
1642 return createCXString("attribute(ibaction)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00001643 case CXCursor_IBOutletAttr:
1644 return createCXString("attribute(iboutlet)");
1645 case CXCursor_PreprocessingDirective:
1646 return createCXString("preprocessing directive");
Douglas Gregor572feb22010-03-18 18:04:21 +00001647 case CXCursor_MacroDefinition:
1648 return createCXString("macro definition");
Douglas Gregor48072312010-03-18 15:23:44 +00001649 case CXCursor_MacroInstantiation:
1650 return createCXString("macro instantiation");
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00001651 case CXCursor_Namespace:
1652 return createCXString("Namespace");
Ted Kremeneka0536d82010-05-07 01:04:29 +00001653 case CXCursor_LinkageSpec:
1654 return createCXString("LinkageSpec");
Steve Naroff89922f82009-08-31 00:59:03 +00001655 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00001656
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00001657 llvm_unreachable("Unhandled CXCursorKind");
Ted Kremeneke68fff62010-02-17 00:41:32 +00001658 return createCXString(NULL);
Steve Naroff600866c2009-08-27 19:51:58 +00001659}
Steve Naroff89922f82009-08-31 00:59:03 +00001660
Ted Kremeneke68fff62010-02-17 00:41:32 +00001661enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
1662 CXCursor parent,
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001663 CXClientData client_data) {
1664 CXCursor *BestCursor = static_cast<CXCursor *>(client_data);
1665 *BestCursor = cursor;
1666 return CXChildVisit_Recurse;
1667}
Ted Kremeneke68fff62010-02-17 00:41:32 +00001668
Douglas Gregorb9790342010-01-22 21:44:22 +00001669CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
1670 if (!TU)
Ted Kremenekf4629892010-01-14 01:51:23 +00001671 return clang_getNullCursor();
Ted Kremeneke68fff62010-02-17 00:41:32 +00001672
Douglas Gregorb9790342010-01-22 21:44:22 +00001673 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
1674
Douglas Gregorbdf60622010-03-05 21:16:25 +00001675 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
1676
Ted Kremeneka297de22010-01-25 22:34:44 +00001677 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001678 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
1679 if (SLoc.isValid()) {
Daniel Dunbard52864b2010-02-14 10:02:57 +00001680 SourceRange RegionOfInterest(SLoc, SLoc.getFileLocWithOffset(1));
Ted Kremeneke68fff62010-02-17 00:41:32 +00001681
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001682 // FIXME: Would be great to have a "hint" cursor, then walk from that
1683 // hint cursor upward until we find a cursor whose source range encloses
1684 // the region of interest, rather than starting from the translation unit.
1685 CXCursor Parent = clang_getTranslationUnitCursor(CXXUnit);
Ted Kremeneke68fff62010-02-17 00:41:32 +00001686 CursorVisitor CursorVis(CXXUnit, GetCursorVisitor, &Result,
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001687 Decl::MaxPCHLevel, RegionOfInterest);
1688 CursorVis.VisitChildren(Parent);
Steve Naroff77128dd2009-09-15 20:25:34 +00001689 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00001690 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00001691}
1692
Ted Kremenek73885552009-11-17 19:28:59 +00001693CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00001694 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00001695}
1696
1697unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00001698 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00001699}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001700
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001701unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00001702 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
1703}
1704
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001705unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +00001706 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
1707}
Steve Naroff2d4d6292009-08-31 14:26:51 +00001708
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001709unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00001710 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
1711}
1712
Douglas Gregor97b98722010-01-19 23:20:36 +00001713unsigned clang_isExpression(enum CXCursorKind K) {
1714 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
1715}
1716
1717unsigned clang_isStatement(enum CXCursorKind K) {
1718 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
1719}
1720
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001721unsigned clang_isTranslationUnit(enum CXCursorKind K) {
1722 return K == CXCursor_TranslationUnit;
1723}
1724
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00001725unsigned clang_isPreprocessing(enum CXCursorKind K) {
1726 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
1727}
1728
Ted Kremenekad6eff62010-03-08 21:17:29 +00001729unsigned clang_isUnexposed(enum CXCursorKind K) {
1730 switch (K) {
1731 case CXCursor_UnexposedDecl:
1732 case CXCursor_UnexposedExpr:
1733 case CXCursor_UnexposedStmt:
1734 case CXCursor_UnexposedAttr:
1735 return true;
1736 default:
1737 return false;
1738 }
1739}
1740
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001741CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00001742 return C.kind;
1743}
1744
Douglas Gregor98258af2010-01-18 22:46:11 +00001745CXSourceLocation clang_getCursorLocation(CXCursor C) {
1746 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00001747 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001748 case CXCursor_ObjCSuperClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00001749 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1750 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001751 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001752 }
1753
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001754 case CXCursor_ObjCProtocolRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00001755 std::pair<ObjCProtocolDecl *, SourceLocation> P
1756 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001757 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001758 }
1759
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001760 case CXCursor_ObjCClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00001761 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1762 = getCursorObjCClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001763 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001764 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001765
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001766 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001767 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001768 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001769 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001770
Douglas Gregorf46034a2010-01-18 23:41:10 +00001771 default:
1772 // FIXME: Need a way to enumerate all non-reference cases.
1773 llvm_unreachable("Missed a reference kind");
1774 }
Douglas Gregor98258af2010-01-18 22:46:11 +00001775 }
Douglas Gregor97b98722010-01-19 23:20:36 +00001776
1777 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001778 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00001779 getLocationFromExpr(getCursorExpr(C)));
1780
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00001781 if (C.kind == CXCursor_PreprocessingDirective) {
1782 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
1783 return cxloc::translateSourceLocation(getCursorContext(C), L);
1784 }
Douglas Gregor48072312010-03-18 15:23:44 +00001785
1786 if (C.kind == CXCursor_MacroInstantiation) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00001787 SourceLocation L
1788 = cxcursor::getCursorMacroInstantiation(C)->getSourceRange().getBegin();
Douglas Gregor48072312010-03-18 15:23:44 +00001789 return cxloc::translateSourceLocation(getCursorContext(C), L);
1790 }
Douglas Gregor572feb22010-03-18 18:04:21 +00001791
1792 if (C.kind == CXCursor_MacroDefinition) {
1793 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
1794 return cxloc::translateSourceLocation(getCursorContext(C), L);
1795 }
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00001796
Ted Kremenek20f9ba72010-05-12 06:03:33 +00001797 if (!getCursorDecl(C))
Douglas Gregor5352ac02010-01-28 00:27:43 +00001798 return clang_getNullLocation();
Douglas Gregor98258af2010-01-18 22:46:11 +00001799
Douglas Gregorf46034a2010-01-18 23:41:10 +00001800 Decl *D = getCursorDecl(C);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001801 SourceLocation Loc = D->getLocation();
1802 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
1803 Loc = Class->getClassLoc();
Douglas Gregor2ca54fe2010-03-22 15:53:50 +00001804 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00001805}
Douglas Gregora7bde202010-01-19 00:34:46 +00001806
1807CXSourceRange clang_getCursorExtent(CXCursor C) {
1808 if (clang_isReference(C.kind)) {
1809 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001810 case CXCursor_ObjCSuperClassRef: {
Douglas Gregora7bde202010-01-19 00:34:46 +00001811 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1812 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001813 return cxloc::translateSourceRange(P.first->getASTContext(), P.second);
Douglas Gregora7bde202010-01-19 00:34:46 +00001814 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001815
1816 case CXCursor_ObjCProtocolRef: {
Douglas Gregora7bde202010-01-19 00:34:46 +00001817 std::pair<ObjCProtocolDecl *, SourceLocation> P
1818 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001819 return cxloc::translateSourceRange(P.first->getASTContext(), P.second);
Douglas Gregora7bde202010-01-19 00:34:46 +00001820 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001821
1822 case CXCursor_ObjCClassRef: {
Douglas Gregora7bde202010-01-19 00:34:46 +00001823 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1824 = getCursorObjCClassRef(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001825
Ted Kremeneka297de22010-01-25 22:34:44 +00001826 return cxloc::translateSourceRange(P.first->getASTContext(), P.second);
Douglas Gregora7bde202010-01-19 00:34:46 +00001827 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001828
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001829 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001830 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001831 return cxloc::translateSourceRange(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001832 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001833
Douglas Gregora7bde202010-01-19 00:34:46 +00001834 default:
1835 // FIXME: Need a way to enumerate all non-reference cases.
1836 llvm_unreachable("Missed a reference kind");
1837 }
1838 }
Douglas Gregor97b98722010-01-19 23:20:36 +00001839
1840 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001841 return cxloc::translateSourceRange(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00001842 getCursorExpr(C)->getSourceRange());
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001843
1844 if (clang_isStatement(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001845 return cxloc::translateSourceRange(getCursorContext(C),
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001846 getCursorStmt(C)->getSourceRange());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001847
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00001848 if (C.kind == CXCursor_PreprocessingDirective) {
1849 SourceRange R = cxcursor::getCursorPreprocessingDirective(C);
1850 return cxloc::translateSourceRange(getCursorContext(C), R);
1851 }
Douglas Gregor48072312010-03-18 15:23:44 +00001852
1853 if (C.kind == CXCursor_MacroInstantiation) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00001854 SourceRange R = cxcursor::getCursorMacroInstantiation(C)->getSourceRange();
Douglas Gregor48072312010-03-18 15:23:44 +00001855 return cxloc::translateSourceRange(getCursorContext(C), R);
1856 }
Douglas Gregor572feb22010-03-18 18:04:21 +00001857
1858 if (C.kind == CXCursor_MacroDefinition) {
1859 SourceRange R = cxcursor::getCursorMacroDefinition(C)->getSourceRange();
1860 return cxloc::translateSourceRange(getCursorContext(C), R);
1861 }
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00001862
Ted Kremenek20f9ba72010-05-12 06:03:33 +00001863 if (!getCursorDecl(C))
Douglas Gregor5352ac02010-01-28 00:27:43 +00001864 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001865
Douglas Gregora7bde202010-01-19 00:34:46 +00001866 Decl *D = getCursorDecl(C);
Douglas Gregor2ca54fe2010-03-22 15:53:50 +00001867 return cxloc::translateSourceRange(getCursorContext(C), D->getSourceRange());
Douglas Gregora7bde202010-01-19 00:34:46 +00001868}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001869
1870CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001871 if (clang_isInvalid(C.kind))
1872 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001873
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001874 ASTUnit *CXXUnit = getCursorASTUnit(C);
Douglas Gregorb6998662010-01-19 19:34:47 +00001875 if (clang_isDeclaration(C.kind))
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001876 return C;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001877
Douglas Gregor97b98722010-01-19 23:20:36 +00001878 if (clang_isExpression(C.kind)) {
1879 Decl *D = getDeclFromExpr(getCursorExpr(C));
1880 if (D)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001881 return MakeCXCursor(D, CXXUnit);
Douglas Gregor97b98722010-01-19 23:20:36 +00001882 return clang_getNullCursor();
1883 }
1884
Douglas Gregorbf7efa22010-03-18 18:23:03 +00001885 if (C.kind == CXCursor_MacroInstantiation) {
1886 if (MacroDefinition *Def = getCursorMacroInstantiation(C)->getDefinition())
1887 return MakeMacroDefinitionCursor(Def, CXXUnit);
1888 }
1889
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001890 if (!clang_isReference(C.kind))
1891 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001892
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001893 switch (C.kind) {
1894 case CXCursor_ObjCSuperClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001895 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001896
1897 case CXCursor_ObjCProtocolRef: {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001898 return MakeCXCursor(getCursorObjCProtocolRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001899
1900 case CXCursor_ObjCClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001901 return MakeCXCursor(getCursorObjCClassRef(C).first, CXXUnit);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001902
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001903 case CXCursor_TypeRef:
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001904 return MakeCXCursor(getCursorTypeRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001905
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001906 default:
1907 // We would prefer to enumerate all non-reference cursor kinds here.
1908 llvm_unreachable("Unhandled reference cursor kind");
1909 break;
1910 }
1911 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001912
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001913 return clang_getNullCursor();
1914}
1915
Douglas Gregorb6998662010-01-19 19:34:47 +00001916CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001917 if (clang_isInvalid(C.kind))
1918 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001919
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001920 ASTUnit *CXXUnit = getCursorASTUnit(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001921
Douglas Gregorb6998662010-01-19 19:34:47 +00001922 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00001923 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00001924 C = clang_getCursorReferenced(C);
1925 WasReference = true;
1926 }
1927
Douglas Gregorbf7efa22010-03-18 18:23:03 +00001928 if (C.kind == CXCursor_MacroInstantiation)
1929 return clang_getCursorReferenced(C);
1930
Douglas Gregorb6998662010-01-19 19:34:47 +00001931 if (!clang_isDeclaration(C.kind))
1932 return clang_getNullCursor();
1933
1934 Decl *D = getCursorDecl(C);
1935 if (!D)
1936 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001937
Douglas Gregorb6998662010-01-19 19:34:47 +00001938 switch (D->getKind()) {
1939 // Declaration kinds that don't really separate the notions of
1940 // declaration and definition.
1941 case Decl::Namespace:
1942 case Decl::Typedef:
1943 case Decl::TemplateTypeParm:
1944 case Decl::EnumConstant:
1945 case Decl::Field:
1946 case Decl::ObjCIvar:
1947 case Decl::ObjCAtDefsField:
1948 case Decl::ImplicitParam:
1949 case Decl::ParmVar:
1950 case Decl::NonTypeTemplateParm:
1951 case Decl::TemplateTemplateParm:
1952 case Decl::ObjCCategoryImpl:
1953 case Decl::ObjCImplementation:
1954 case Decl::LinkageSpec:
1955 case Decl::ObjCPropertyImpl:
1956 case Decl::FileScopeAsm:
1957 case Decl::StaticAssert:
1958 case Decl::Block:
1959 return C;
1960
1961 // Declaration kinds that don't make any sense here, but are
1962 // nonetheless harmless.
1963 case Decl::TranslationUnit:
Douglas Gregorb6998662010-01-19 19:34:47 +00001964 break;
1965
1966 // Declaration kinds for which the definition is not resolvable.
1967 case Decl::UnresolvedUsingTypename:
1968 case Decl::UnresolvedUsingValue:
1969 break;
1970
1971 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001972 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
1973 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001974
1975 case Decl::NamespaceAlias:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001976 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001977
1978 case Decl::Enum:
1979 case Decl::Record:
1980 case Decl::CXXRecord:
1981 case Decl::ClassTemplateSpecialization:
1982 case Decl::ClassTemplatePartialSpecialization:
Douglas Gregor952b0172010-02-11 01:04:33 +00001983 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001984 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001985 return clang_getNullCursor();
1986
1987 case Decl::Function:
1988 case Decl::CXXMethod:
1989 case Decl::CXXConstructor:
1990 case Decl::CXXDestructor:
1991 case Decl::CXXConversion: {
1992 const FunctionDecl *Def = 0;
1993 if (cast<FunctionDecl>(D)->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001994 return MakeCXCursor(const_cast<FunctionDecl *>(Def), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001995 return clang_getNullCursor();
1996 }
1997
1998 case Decl::Var: {
Sebastian Redl31310a22010-02-01 20:16:42 +00001999 // Ask the variable if it has a definition.
2000 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
2001 return MakeCXCursor(Def, CXXUnit);
2002 return clang_getNullCursor();
Douglas Gregorb6998662010-01-19 19:34:47 +00002003 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002004
Douglas Gregorb6998662010-01-19 19:34:47 +00002005 case Decl::FunctionTemplate: {
2006 const FunctionDecl *Def = 0;
2007 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002008 return MakeCXCursor(Def->getDescribedFunctionTemplate(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002009 return clang_getNullCursor();
2010 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002011
Douglas Gregorb6998662010-01-19 19:34:47 +00002012 case Decl::ClassTemplate: {
2013 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
Douglas Gregor952b0172010-02-11 01:04:33 +00002014 ->getDefinition())
Douglas Gregorb6998662010-01-19 19:34:47 +00002015 return MakeCXCursor(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002016 cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002017 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002018 return clang_getNullCursor();
2019 }
2020
2021 case Decl::Using: {
2022 UsingDecl *Using = cast<UsingDecl>(D);
2023 CXCursor Def = clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002024 for (UsingDecl::shadow_iterator S = Using->shadow_begin(),
2025 SEnd = Using->shadow_end();
Douglas Gregorb6998662010-01-19 19:34:47 +00002026 S != SEnd; ++S) {
2027 if (Def != clang_getNullCursor()) {
2028 // FIXME: We have no way to return multiple results.
2029 return clang_getNullCursor();
2030 }
2031
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002032 Def = clang_getCursorDefinition(MakeCXCursor((*S)->getTargetDecl(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002033 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002034 }
2035
2036 return Def;
2037 }
2038
2039 case Decl::UsingShadow:
2040 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002041 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002042 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002043
2044 case Decl::ObjCMethod: {
2045 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
2046 if (Method->isThisDeclarationADefinition())
2047 return C;
2048
2049 // Dig out the method definition in the associated
2050 // @implementation, if we have it.
2051 // FIXME: The ASTs should make finding the definition easier.
2052 if (ObjCInterfaceDecl *Class
2053 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
2054 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
2055 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
2056 Method->isInstanceMethod()))
2057 if (Def->isThisDeclarationADefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002058 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002059
2060 return clang_getNullCursor();
2061 }
2062
2063 case Decl::ObjCCategory:
2064 if (ObjCCategoryImplDecl *Impl
2065 = cast<ObjCCategoryDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002066 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002067 return clang_getNullCursor();
2068
2069 case Decl::ObjCProtocol:
2070 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
2071 return C;
2072 return clang_getNullCursor();
2073
2074 case Decl::ObjCInterface:
2075 // There are two notions of a "definition" for an Objective-C
2076 // class: the interface and its implementation. When we resolved a
2077 // reference to an Objective-C class, produce the @interface as
2078 // the definition; when we were provided with the interface,
2079 // produce the @implementation as the definition.
2080 if (WasReference) {
2081 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
2082 return C;
2083 } else if (ObjCImplementationDecl *Impl
2084 = cast<ObjCInterfaceDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002085 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002086 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002087
Douglas Gregorb6998662010-01-19 19:34:47 +00002088 case Decl::ObjCProperty:
2089 // FIXME: We don't really know where to find the
2090 // ObjCPropertyImplDecls that implement this property.
2091 return clang_getNullCursor();
2092
2093 case Decl::ObjCCompatibleAlias:
2094 if (ObjCInterfaceDecl *Class
2095 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
2096 if (!Class->isForwardDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002097 return MakeCXCursor(Class, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002098
Douglas Gregorb6998662010-01-19 19:34:47 +00002099 return clang_getNullCursor();
2100
2101 case Decl::ObjCForwardProtocol: {
2102 ObjCForwardProtocolDecl *Forward = cast<ObjCForwardProtocolDecl>(D);
2103 if (Forward->protocol_size() == 1)
2104 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002105 MakeCXCursor(*Forward->protocol_begin(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002106 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002107
2108 // FIXME: Cannot return multiple definitions.
2109 return clang_getNullCursor();
2110 }
2111
2112 case Decl::ObjCClass: {
2113 ObjCClassDecl *Class = cast<ObjCClassDecl>(D);
2114 if (Class->size() == 1) {
2115 ObjCInterfaceDecl *IFace = Class->begin()->getInterface();
2116 if (!IFace->isForwardDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002117 return MakeCXCursor(IFace, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002118 return clang_getNullCursor();
2119 }
2120
2121 // FIXME: Cannot return multiple definitions.
2122 return clang_getNullCursor();
2123 }
2124
2125 case Decl::Friend:
2126 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002127 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002128 return clang_getNullCursor();
2129
2130 case Decl::FriendTemplate:
2131 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002132 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002133 return clang_getNullCursor();
2134 }
2135
2136 return clang_getNullCursor();
2137}
2138
2139unsigned clang_isCursorDefinition(CXCursor C) {
2140 if (!clang_isDeclaration(C.kind))
2141 return 0;
2142
2143 return clang_getCursorDefinition(C) == C;
2144}
2145
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002146void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00002147 const char **startBuf,
2148 const char **endBuf,
2149 unsigned *startLine,
2150 unsigned *startColumn,
2151 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002152 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00002153 assert(getCursorDecl(C) && "CXCursor has null decl");
2154 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00002155 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
2156 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002157
Steve Naroff4ade6d62009-09-23 17:52:52 +00002158 SourceManager &SM = FD->getASTContext().getSourceManager();
2159 *startBuf = SM.getCharacterData(Body->getLBracLoc());
2160 *endBuf = SM.getCharacterData(Body->getRBracLoc());
2161 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
2162 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
2163 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
2164 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
2165}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002166
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002167void clang_enableStackTraces(void) {
2168 llvm::sys::PrintStackTraceOnErrorSignal();
2169}
2170
Ted Kremenekfb480492010-01-13 21:46:36 +00002171} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00002172
Ted Kremenekfb480492010-01-13 21:46:36 +00002173//===----------------------------------------------------------------------===//
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002174// Token-based Operations.
2175//===----------------------------------------------------------------------===//
2176
2177/* CXToken layout:
2178 * int_data[0]: a CXTokenKind
2179 * int_data[1]: starting token location
2180 * int_data[2]: token length
2181 * int_data[3]: reserved
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002182 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002183 * otherwise unused.
2184 */
2185extern "C" {
2186
2187CXTokenKind clang_getTokenKind(CXToken CXTok) {
2188 return static_cast<CXTokenKind>(CXTok.int_data[0]);
2189}
2190
2191CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
2192 switch (clang_getTokenKind(CXTok)) {
2193 case CXToken_Identifier:
2194 case CXToken_Keyword:
2195 // We know we have an IdentifierInfo*, so use that.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002196 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
2197 ->getNameStart());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002198
2199 case CXToken_Literal: {
2200 // We have stashed the starting pointer in the ptr_data field. Use it.
2201 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002202 return createCXString(llvm::StringRef(Text, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002203 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002204
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002205 case CXToken_Punctuation:
2206 case CXToken_Comment:
2207 break;
2208 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002209
2210 // We have to find the starting buffer pointer the hard way, by
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002211 // deconstructing the source location.
2212 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2213 if (!CXXUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002214 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002215
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002216 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
2217 std::pair<FileID, unsigned> LocInfo
2218 = CXXUnit->getSourceManager().getDecomposedLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +00002219 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002220 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00002221 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
2222 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00002223 return createCXString("");
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002224
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002225 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002226}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002227
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002228CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
2229 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2230 if (!CXXUnit)
2231 return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002232
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002233 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
2234 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
2235}
2236
2237CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
2238 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregor5352ac02010-01-28 00:27:43 +00002239 if (!CXXUnit)
2240 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002241
2242 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002243 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
2244}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002245
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002246void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
2247 CXToken **Tokens, unsigned *NumTokens) {
2248 if (Tokens)
2249 *Tokens = 0;
2250 if (NumTokens)
2251 *NumTokens = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002252
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002253 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2254 if (!CXXUnit || !Tokens || !NumTokens)
2255 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002256
Douglas Gregorbdf60622010-03-05 21:16:25 +00002257 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
2258
Daniel Dunbar85b988f2010-02-14 08:31:57 +00002259 SourceRange R = cxloc::translateCXSourceRange(Range);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002260 if (R.isInvalid())
2261 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002262
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002263 SourceManager &SourceMgr = CXXUnit->getSourceManager();
2264 std::pair<FileID, unsigned> BeginLocInfo
2265 = SourceMgr.getDecomposedLoc(R.getBegin());
2266 std::pair<FileID, unsigned> EndLocInfo
2267 = SourceMgr.getDecomposedLoc(R.getEnd());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002268
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002269 // Cannot tokenize across files.
2270 if (BeginLocInfo.first != EndLocInfo.first)
2271 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002272
2273 // Create a lexer
Douglas Gregorf715ca12010-03-16 00:06:06 +00002274 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002275 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00002276 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
Douglas Gregor47a3fcd2010-03-16 20:26:15 +00002277 if (Invalid)
2278 return;
Douglas Gregoraea67db2010-03-15 22:54:52 +00002279
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002280 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
2281 CXXUnit->getASTContext().getLangOptions(),
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002282 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002283 Lex.SetCommentRetentionState(true);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002284
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002285 // Lex tokens until we hit the end of the range.
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002286 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002287 llvm::SmallVector<CXToken, 32> CXTokens;
2288 Token Tok;
2289 do {
2290 // Lex the next token
2291 Lex.LexFromRawLexer(Tok);
2292 if (Tok.is(tok::eof))
2293 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002294
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002295 // Initialize the CXToken.
2296 CXToken CXTok;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002297
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002298 // - Common fields
2299 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
2300 CXTok.int_data[2] = Tok.getLength();
2301 CXTok.int_data[3] = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002302
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002303 // - Kind-specific fields
2304 if (Tok.isLiteral()) {
2305 CXTok.int_data[0] = CXToken_Literal;
2306 CXTok.ptr_data = (void *)Tok.getLiteralData();
2307 } else if (Tok.is(tok::identifier)) {
Douglas Gregoraea67db2010-03-15 22:54:52 +00002308 // Lookup the identifier to determine whether we have a keyword.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002309 std::pair<FileID, unsigned> LocInfo
2310 = SourceMgr.getDecomposedLoc(Tok.getLocation());
Douglas Gregorf715ca12010-03-16 00:06:06 +00002311 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002312 llvm::StringRef Buf
Douglas Gregorf715ca12010-03-16 00:06:06 +00002313 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
2314 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00002315 return;
2316
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002317 const char *StartPos = Buf.data() + LocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002318 IdentifierInfo *II
2319 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok, StartPos);
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00002320
2321 if (II->getObjCKeywordID() != tok::objc_not_keyword) {
2322 CXTok.int_data[0] = CXToken_Keyword;
2323 }
2324 else {
2325 CXTok.int_data[0] = II->getTokenID() == tok::identifier?
2326 CXToken_Identifier
2327 : CXToken_Keyword;
2328 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002329 CXTok.ptr_data = II;
2330 } else if (Tok.is(tok::comment)) {
2331 CXTok.int_data[0] = CXToken_Comment;
2332 CXTok.ptr_data = 0;
2333 } else {
2334 CXTok.int_data[0] = CXToken_Punctuation;
2335 CXTok.ptr_data = 0;
2336 }
2337 CXTokens.push_back(CXTok);
2338 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002339
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002340 if (CXTokens.empty())
2341 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002342
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002343 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
2344 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
2345 *NumTokens = CXTokens.size();
2346}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002347
Ted Kremenek6db61092010-05-05 00:55:15 +00002348void clang_disposeTokens(CXTranslationUnit TU,
2349 CXToken *Tokens, unsigned NumTokens) {
2350 free(Tokens);
2351}
2352
2353} // end: extern "C"
2354
2355//===----------------------------------------------------------------------===//
2356// Token annotation APIs.
2357//===----------------------------------------------------------------------===//
2358
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002359typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002360static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
2361 CXCursor parent,
2362 CXClientData client_data);
Ted Kremenek6db61092010-05-05 00:55:15 +00002363namespace {
2364class AnnotateTokensWorker {
2365 AnnotateTokensData &Annotated;
Ted Kremenek11949cb2010-05-05 00:55:17 +00002366 CXToken *Tokens;
2367 CXCursor *Cursors;
2368 unsigned NumTokens;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002369 unsigned TokIdx;
2370 CursorVisitor AnnotateVis;
2371 SourceManager &SrcMgr;
2372
2373 bool MoreTokens() const { return TokIdx < NumTokens; }
2374 unsigned NextToken() const { return TokIdx; }
2375 void AdvanceToken() { ++TokIdx; }
2376 SourceLocation GetTokenLoc(unsigned tokI) {
2377 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
2378 }
2379
Ted Kremenek6db61092010-05-05 00:55:15 +00002380public:
Ted Kremenek11949cb2010-05-05 00:55:17 +00002381 AnnotateTokensWorker(AnnotateTokensData &annotated,
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002382 CXToken *tokens, CXCursor *cursors, unsigned numTokens,
2383 ASTUnit *CXXUnit, SourceRange RegionOfInterest)
Ted Kremenek11949cb2010-05-05 00:55:17 +00002384 : Annotated(annotated), Tokens(tokens), Cursors(cursors),
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002385 NumTokens(numTokens), TokIdx(0),
2386 AnnotateVis(CXXUnit, AnnotateTokensVisitor, this,
2387 Decl::MaxPCHLevel, RegionOfInterest),
2388 SrcMgr(CXXUnit->getSourceManager()) {}
Ted Kremenek11949cb2010-05-05 00:55:17 +00002389
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002390 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
Ted Kremenek6db61092010-05-05 00:55:15 +00002391 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002392 void AnnotateTokens(CXCursor parent);
Ted Kremenek6db61092010-05-05 00:55:15 +00002393};
2394}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002395
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002396void AnnotateTokensWorker::AnnotateTokens(CXCursor parent) {
2397 // Walk the AST within the region of interest, annotating tokens
2398 // along the way.
2399 VisitChildren(parent);
Ted Kremenek11949cb2010-05-05 00:55:17 +00002400
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002401 for (unsigned I = 0 ; I < TokIdx ; ++I) {
2402 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
2403 if (Pos != Annotated.end())
2404 Cursors[I] = Pos->second;
2405 }
2406
2407 // Finish up annotating any tokens left.
2408 if (!MoreTokens())
2409 return;
2410
2411 const CXCursor &C = clang_getNullCursor();
2412 for (unsigned I = TokIdx ; I < NumTokens ; ++I) {
2413 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
2414 Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second;
Ted Kremenek11949cb2010-05-05 00:55:17 +00002415 }
2416}
2417
Ted Kremenek6db61092010-05-05 00:55:15 +00002418enum CXChildVisitResult
2419AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002420 CXSourceLocation Loc = clang_getCursorLocation(cursor);
2421 // We can always annotate a preprocessing directive/macro instantiation.
2422 if (clang_isPreprocessing(cursor.kind)) {
2423 Annotated[Loc.int_data] = cursor;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002424 return CXChildVisit_Recurse;
2425 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002426
2427 CXSourceRange cursorExtent = clang_getCursorExtent(cursor);
2428 SourceRange cursorRange = cxloc::translateCXSourceRange(cursorExtent);
Ted Kremeneka333c662010-05-12 05:29:33 +00002429
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002430 if (cursorRange.isInvalid())
2431 return CXChildVisit_Continue;
Ted Kremeneka333c662010-05-12 05:29:33 +00002432
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002433 SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data);
2434
Ted Kremeneka333c662010-05-12 05:29:33 +00002435 // Adjust the annotated range based specific declarations.
2436 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
2437 if (cursorK >= CXCursor_FirstDecl && cursorK <= CXCursor_LastDecl) {
2438 if (const DeclaratorDecl *DD =
2439 dyn_cast<DeclaratorDecl>(cxcursor::getCursorDecl(cursor))) {
2440 if (TypeSourceInfo *TI = DD->getTypeSourceInfo()) {
2441 TypeLoc TL = TI->getTypeLoc();
2442 SourceLocation TLoc = TL.getFullSourceRange().getBegin();
Ted Kremeneka333c662010-05-12 05:29:33 +00002443 if (TLoc.isValid()) {
2444 assert(SrcMgr.isBeforeInTranslationUnit(TLoc, L));
2445 cursorRange.setBegin(TLoc);
2446 }
2447 }
2448 }
2449 }
2450
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002451 const enum CXCursorKind K = clang_getCursorKind(parent);
2452 const CXCursor updateC =
2453 (clang_isInvalid(K) || K == CXCursor_TranslationUnit ||
2454 L.isMacroID())
2455 ? clang_getNullCursor() : parent;
2456
2457 while (MoreTokens()) {
2458 const unsigned I = NextToken();
2459 SourceLocation TokLoc = GetTokenLoc(I);
2460 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
2461 case RangeBefore:
2462 Cursors[I] = updateC;
2463 AdvanceToken();
2464 continue;
2465 case RangeAfter:
2466 return CXChildVisit_Continue;
2467 case RangeOverlap:
2468 break;
2469 }
2470 break;
2471 }
2472
2473 // Visit children to get their cursor information.
2474 const unsigned BeforeChildren = NextToken();
2475 VisitChildren(cursor);
2476 const unsigned AfterChildren = NextToken();
2477
2478 // Adjust 'Last' to the last token within the extent of the cursor.
2479 while (MoreTokens()) {
2480 const unsigned I = NextToken();
2481 SourceLocation TokLoc = GetTokenLoc(I);
2482 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
2483 case RangeBefore:
2484 assert(0 && "Infeasible");
2485 case RangeAfter:
2486 break;
2487 case RangeOverlap:
2488 Cursors[I] = updateC;
2489 AdvanceToken();
2490 continue;
2491 }
2492 break;
2493 }
2494 const unsigned Last = NextToken();
Ted Kremenek6db61092010-05-05 00:55:15 +00002495
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002496 // Scan the tokens that are at the beginning of the cursor, but are not
2497 // capture by the child cursors.
2498
2499 // For AST elements within macros, rely on a post-annotate pass to
2500 // to correctly annotate the tokens with cursors. Otherwise we can
2501 // get confusing results of having tokens that map to cursors that really
2502 // are expanded by an instantiation.
2503 if (L.isMacroID())
2504 cursor = clang_getNullCursor();
2505
2506 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
2507 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
2508 break;
2509 Cursors[I] = cursor;
2510 }
2511 // Scan the tokens that are at the end of the cursor, but are not captured
2512 // but the child cursors.
2513 for (unsigned I = AfterChildren; I != Last; ++I)
2514 Cursors[I] = cursor;
2515
2516 TokIdx = Last;
2517 return CXChildVisit_Continue;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002518}
2519
Ted Kremenek6db61092010-05-05 00:55:15 +00002520static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
2521 CXCursor parent,
2522 CXClientData client_data) {
2523 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
2524}
2525
2526extern "C" {
2527
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002528void clang_annotateTokens(CXTranslationUnit TU,
2529 CXToken *Tokens, unsigned NumTokens,
2530 CXCursor *Cursors) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002531
2532 if (NumTokens == 0 || !Tokens || !Cursors)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002533 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002534
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002535 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002536 if (!CXXUnit) {
2537 // Any token we don't specifically annotate will have a NULL cursor.
2538 const CXCursor &C = clang_getNullCursor();
2539 for (unsigned I = 0; I != NumTokens; ++I)
2540 Cursors[I] = C;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002541 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002542 }
2543
Douglas Gregorbdf60622010-03-05 21:16:25 +00002544 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002545
Douglas Gregor0396f462010-03-19 05:22:59 +00002546 // Determine the region of interest, which contains all of the tokens.
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002547 SourceRange RegionOfInterest;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002548 RegionOfInterest.setBegin(cxloc::translateSourceLocation(
2549 clang_getTokenLocation(TU, Tokens[0])));
2550
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002551 SourceLocation End
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002552 = cxloc::translateSourceLocation(clang_getTokenLocation(TU,
2553 Tokens[NumTokens - 1]));
Daniel Dunbard52864b2010-02-14 10:02:57 +00002554 RegionOfInterest.setEnd(CXXUnit->getPreprocessor().getLocForEndOfToken(End));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002555
Douglas Gregor0396f462010-03-19 05:22:59 +00002556 // A mapping from the source locations found when re-lexing or traversing the
2557 // region of interest to the corresponding cursors.
2558 AnnotateTokensData Annotated;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002559
2560 // Relex the tokens within the source range to look for preprocessing
Douglas Gregor0396f462010-03-19 05:22:59 +00002561 // directives.
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002562 SourceManager &SourceMgr = CXXUnit->getSourceManager();
2563 std::pair<FileID, unsigned> BeginLocInfo
2564 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
2565 std::pair<FileID, unsigned> EndLocInfo
2566 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002567
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002568 llvm::StringRef Buffer;
Douglas Gregor0396f462010-03-19 05:22:59 +00002569 bool Invalid = false;
2570 if (BeginLocInfo.first == EndLocInfo.first &&
2571 ((Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid)),true) &&
2572 !Invalid) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002573 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
2574 CXXUnit->getASTContext().getLangOptions(),
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002575 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002576 Buffer.end());
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002577 Lex.SetCommentRetentionState(true);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002578
2579 // Lex tokens in raw mode until we hit the end of the range, to avoid
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002580 // entering #includes or expanding macros.
Douglas Gregor48072312010-03-18 15:23:44 +00002581 while (true) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002582 Token Tok;
2583 Lex.LexFromRawLexer(Tok);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002584
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002585 reprocess:
2586 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
2587 // We have found a preprocessing directive. Gobble it up so that we
2588 // don't see it while preprocessing these tokens later, but keep track of
2589 // all of the token locations inside this preprocessing directive so that
2590 // we can annotate them appropriately.
2591 //
2592 // FIXME: Some simple tests here could identify macro definitions and
2593 // #undefs, to provide specific cursor kinds for those.
2594 std::vector<SourceLocation> Locations;
2595 do {
2596 Locations.push_back(Tok.getLocation());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002597 Lex.LexFromRawLexer(Tok);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002598 } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002599
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002600 using namespace cxcursor;
2601 CXCursor Cursor
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002602 = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
2603 Locations.back()),
Ted Kremenek6db61092010-05-05 00:55:15 +00002604 CXXUnit);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002605 for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
2606 Annotated[Locations[I].getRawEncoding()] = Cursor;
2607 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002608
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002609 if (Tok.isAtStartOfLine())
2610 goto reprocess;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002611
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002612 continue;
2613 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002614
Douglas Gregor48072312010-03-18 15:23:44 +00002615 if (Tok.is(tok::eof))
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002616 break;
2617 }
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002618 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002619
Douglas Gregor0396f462010-03-19 05:22:59 +00002620 // Annotate all of the source locations in the region of interest that map to
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002621 // a specific cursor.
2622 AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens,
2623 CXXUnit, RegionOfInterest);
2624 W.AnnotateTokens(clang_getTranslationUnitCursor(CXXUnit));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002625}
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002626} // end: extern "C"
2627
2628//===----------------------------------------------------------------------===//
Ted Kremenek16b42592010-03-03 06:36:57 +00002629// Operations for querying linkage of a cursor.
2630//===----------------------------------------------------------------------===//
2631
2632extern "C" {
2633CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
Douglas Gregor0396f462010-03-19 05:22:59 +00002634 if (!clang_isDeclaration(cursor.kind))
2635 return CXLinkage_Invalid;
2636
Ted Kremenek16b42592010-03-03 06:36:57 +00002637 Decl *D = cxcursor::getCursorDecl(cursor);
2638 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
2639 switch (ND->getLinkage()) {
2640 case NoLinkage: return CXLinkage_NoLinkage;
2641 case InternalLinkage: return CXLinkage_Internal;
2642 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
2643 case ExternalLinkage: return CXLinkage_External;
2644 };
2645
2646 return CXLinkage_Invalid;
2647}
2648} // end: extern "C"
2649
2650//===----------------------------------------------------------------------===//
Ted Kremenek45e1dae2010-04-12 21:22:16 +00002651// Operations for querying language of a cursor.
2652//===----------------------------------------------------------------------===//
2653
2654static CXLanguageKind getDeclLanguage(const Decl *D) {
2655 switch (D->getKind()) {
2656 default:
2657 break;
2658 case Decl::ImplicitParam:
2659 case Decl::ObjCAtDefsField:
2660 case Decl::ObjCCategory:
2661 case Decl::ObjCCategoryImpl:
2662 case Decl::ObjCClass:
2663 case Decl::ObjCCompatibleAlias:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00002664 case Decl::ObjCForwardProtocol:
2665 case Decl::ObjCImplementation:
2666 case Decl::ObjCInterface:
2667 case Decl::ObjCIvar:
2668 case Decl::ObjCMethod:
2669 case Decl::ObjCProperty:
2670 case Decl::ObjCPropertyImpl:
2671 case Decl::ObjCProtocol:
2672 return CXLanguage_ObjC;
2673 case Decl::CXXConstructor:
2674 case Decl::CXXConversion:
2675 case Decl::CXXDestructor:
2676 case Decl::CXXMethod:
2677 case Decl::CXXRecord:
2678 case Decl::ClassTemplate:
2679 case Decl::ClassTemplatePartialSpecialization:
2680 case Decl::ClassTemplateSpecialization:
2681 case Decl::Friend:
2682 case Decl::FriendTemplate:
2683 case Decl::FunctionTemplate:
2684 case Decl::LinkageSpec:
2685 case Decl::Namespace:
2686 case Decl::NamespaceAlias:
2687 case Decl::NonTypeTemplateParm:
2688 case Decl::StaticAssert:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00002689 case Decl::TemplateTemplateParm:
2690 case Decl::TemplateTypeParm:
2691 case Decl::UnresolvedUsingTypename:
2692 case Decl::UnresolvedUsingValue:
2693 case Decl::Using:
2694 case Decl::UsingDirective:
2695 case Decl::UsingShadow:
2696 return CXLanguage_CPlusPlus;
2697 }
2698
2699 return CXLanguage_C;
2700}
2701
2702extern "C" {
2703CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
2704 if (clang_isDeclaration(cursor.kind))
2705 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
2706
2707 return CXLanguage_Invalid;
2708}
2709} // end: extern "C"
2710
2711//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00002712// CXString Operations.
2713//===----------------------------------------------------------------------===//
2714
2715extern "C" {
2716const char *clang_getCString(CXString string) {
2717 return string.Spelling;
2718}
2719
2720void clang_disposeString(CXString string) {
2721 if (string.MustFreeString && string.Spelling)
2722 free((void*)string.Spelling);
2723}
Ted Kremenek04bb7162010-01-22 22:44:15 +00002724
Ted Kremenekfb480492010-01-13 21:46:36 +00002725} // end: extern "C"
Ted Kremenek04bb7162010-01-22 22:44:15 +00002726
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002727namespace clang { namespace cxstring {
2728CXString createCXString(const char *String, bool DupString){
2729 CXString Str;
2730 if (DupString) {
2731 Str.Spelling = strdup(String);
2732 Str.MustFreeString = 1;
2733 } else {
2734 Str.Spelling = String;
2735 Str.MustFreeString = 0;
2736 }
2737 return Str;
2738}
2739
2740CXString createCXString(llvm::StringRef String, bool DupString) {
2741 CXString Result;
2742 if (DupString || (!String.empty() && String.data()[String.size()] != 0)) {
2743 char *Spelling = (char *)malloc(String.size() + 1);
2744 memmove(Spelling, String.data(), String.size());
2745 Spelling[String.size()] = 0;
2746 Result.Spelling = Spelling;
2747 Result.MustFreeString = 1;
2748 } else {
2749 Result.Spelling = String.data();
2750 Result.MustFreeString = 0;
2751 }
2752 return Result;
2753}
2754}}
2755
Ted Kremenek04bb7162010-01-22 22:44:15 +00002756//===----------------------------------------------------------------------===//
2757// Misc. utility functions.
2758//===----------------------------------------------------------------------===//
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002759
Ted Kremenek04bb7162010-01-22 22:44:15 +00002760extern "C" {
2761
Ted Kremeneka2a9d6e2010-02-12 22:54:40 +00002762CXString clang_getClangVersion() {
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002763 return createCXString(getClangFullVersion());
Ted Kremenek04bb7162010-01-22 22:44:15 +00002764}
2765
2766} // end: extern "C"