blob: f221d16af293334864e9217940a7433254dcfeaa [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 Kremenek8f06e0e2010-05-06 23:38:21 +0000288 bool VisitNamespaceDecl(NamespaceDecl *D);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000289
290 // Type visitors
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000291 // FIXME: QualifiedTypeLoc doesn't provide any location information
292 bool VisitBuiltinTypeLoc(BuiltinTypeLoc TL);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000293 bool VisitTypedefTypeLoc(TypedefTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000294 bool VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL);
295 bool VisitTagTypeLoc(TagTypeLoc TL);
296 // FIXME: TemplateTypeParmTypeLoc doesn't provide any location information
297 bool VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL);
298 bool VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL);
299 bool VisitPointerTypeLoc(PointerTypeLoc TL);
300 bool VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL);
301 bool VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL);
302 bool VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL);
303 bool VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL);
304 bool VisitFunctionTypeLoc(FunctionTypeLoc TL);
305 bool VisitArrayTypeLoc(ArrayTypeLoc TL);
Douglas Gregor2332c112010-01-21 20:48:56 +0000306 // FIXME: Implement for TemplateSpecializationTypeLoc
307 // FIXME: Implement visitors here when the unimplemented TypeLocs get
308 // implemented
309 bool VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL);
310 bool VisitTypeOfTypeLoc(TypeOfTypeLoc TL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000311
Douglas Gregora59e3902010-01-21 23:27:09 +0000312 // Statement visitors
313 bool VisitStmt(Stmt *S);
314 bool VisitDeclStmt(DeclStmt *S);
Douglas Gregorf5bab412010-01-22 01:00:11 +0000315 // FIXME: LabelStmt label?
316 bool VisitIfStmt(IfStmt *S);
317 bool VisitSwitchStmt(SwitchStmt *S);
Douglas Gregor263b47b2010-01-25 16:12:32 +0000318 bool VisitWhileStmt(WhileStmt *S);
319 bool VisitForStmt(ForStmt *S);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000320
Douglas Gregor336fd812010-01-23 00:40:08 +0000321 // Expression visitors
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000322 bool VisitBlockExpr(BlockExpr *B);
Douglas Gregor336fd812010-01-23 00:40:08 +0000323 bool VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000324 bool VisitExplicitCastExpr(ExplicitCastExpr *E);
Douglas Gregorc2350e52010-03-08 16:40:19 +0000325 bool VisitObjCMessageExpr(ObjCMessageExpr *E);
Douglas Gregor81d34662010-04-20 15:39:42 +0000326 bool VisitObjCEncodeExpr(ObjCEncodeExpr *E);
Douglas Gregor8ecdb652010-04-28 22:16:22 +0000327 bool VisitOffsetOfExpr(OffsetOfExpr *E);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000328 bool VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E);
Steve Naroff89922f82009-08-31 00:59:03 +0000329};
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000330
Ted Kremenekab188932010-01-05 19:32:54 +0000331} // end anonymous namespace
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000332
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000333RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000334 return RangeCompare(TU->getSourceManager(), R, RegionOfInterest);
335}
336
Douglas Gregorb1373d02010-01-20 20:59:29 +0000337/// \brief Visit the given cursor and, if requested by the visitor,
338/// its children.
339///
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000340/// \param Cursor the cursor to visit.
341///
342/// \param CheckRegionOfInterest if true, then the caller already checked that
343/// this cursor is within the region of interest.
344///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000345/// \returns true if the visitation should be aborted, false if it
346/// should continue.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000347bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
Douglas Gregorb1373d02010-01-20 20:59:29 +0000348 if (clang_isInvalid(Cursor.kind))
349 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000350
Douglas Gregorb1373d02010-01-20 20:59:29 +0000351 if (clang_isDeclaration(Cursor.kind)) {
352 Decl *D = getCursorDecl(Cursor);
353 assert(D && "Invalid declaration cursor");
354 if (D->getPCHLevel() > MaxPCHLevel)
355 return false;
356
357 if (D->isImplicit())
358 return false;
359 }
360
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000361 // If we have a range of interest, and this cursor doesn't intersect with it,
362 // we're done.
363 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
Daniel Dunbarf408f322010-02-14 08:32:05 +0000364 SourceRange Range =
365 cxloc::translateCXSourceRange(clang_getCursorExtent(Cursor));
366 if (Range.isInvalid() || CompareRegionOfInterest(Range))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000367 return false;
368 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000369
Douglas Gregorb1373d02010-01-20 20:59:29 +0000370 switch (Visitor(Cursor, Parent, ClientData)) {
371 case CXChildVisit_Break:
372 return true;
373
374 case CXChildVisit_Continue:
375 return false;
376
377 case CXChildVisit_Recurse:
378 return VisitChildren(Cursor);
379 }
380
Douglas Gregorfd643772010-01-25 16:45:46 +0000381 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000382}
383
Douglas Gregor788f5a12010-03-20 00:41:21 +0000384std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
385CursorVisitor::getPreprocessedEntities() {
386 PreprocessingRecord &PPRec
387 = *TU->getPreprocessor().getPreprocessingRecord();
388
389 bool OnlyLocalDecls
390 = !TU->isMainFileAST() && TU->getOnlyLocalDecls();
391
392 // There is no region of interest; we have to walk everything.
393 if (RegionOfInterest.isInvalid())
394 return std::make_pair(PPRec.begin(OnlyLocalDecls),
395 PPRec.end(OnlyLocalDecls));
396
397 // Find the file in which the region of interest lands.
398 SourceManager &SM = TU->getSourceManager();
399 std::pair<FileID, unsigned> Begin
400 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getBegin());
401 std::pair<FileID, unsigned> End
402 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getEnd());
403
404 // The region of interest spans files; we have to walk everything.
405 if (Begin.first != End.first)
406 return std::make_pair(PPRec.begin(OnlyLocalDecls),
407 PPRec.end(OnlyLocalDecls));
408
409 ASTUnit::PreprocessedEntitiesByFileMap &ByFileMap
410 = TU->getPreprocessedEntitiesByFile();
411 if (ByFileMap.empty()) {
412 // Build the mapping from files to sets of preprocessed entities.
413 for (PreprocessingRecord::iterator E = PPRec.begin(OnlyLocalDecls),
414 EEnd = PPRec.end(OnlyLocalDecls);
415 E != EEnd; ++E) {
416 std::pair<FileID, unsigned> P
417 = SM.getDecomposedInstantiationLoc((*E)->getSourceRange().getBegin());
418 ByFileMap[P.first].push_back(*E);
419 }
420 }
421
422 return std::make_pair(ByFileMap[Begin.first].begin(),
423 ByFileMap[Begin.first].end());
424}
425
Douglas Gregorb1373d02010-01-20 20:59:29 +0000426/// \brief Visit the children of the given cursor.
427///
428/// \returns true if the visitation should be aborted, false if it
429/// should continue.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000430bool CursorVisitor::VisitChildren(CXCursor Cursor) {
Douglas Gregora59e3902010-01-21 23:27:09 +0000431 if (clang_isReference(Cursor.kind)) {
432 // By definition, references have no children.
433 return false;
434 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000435
436 // Set the Parent field to Cursor, then back to its old value once we're
Douglas Gregorb1373d02010-01-20 20:59:29 +0000437 // done.
438 class SetParentRAII {
439 CXCursor &Parent;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000440 Decl *&StmtParent;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000441 CXCursor OldParent;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000442
Douglas Gregorb1373d02010-01-20 20:59:29 +0000443 public:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000444 SetParentRAII(CXCursor &Parent, Decl *&StmtParent, CXCursor NewParent)
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000445 : Parent(Parent), StmtParent(StmtParent), OldParent(Parent)
Douglas Gregorb1373d02010-01-20 20:59:29 +0000446 {
447 Parent = NewParent;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000448 if (clang_isDeclaration(Parent.kind))
449 StmtParent = getCursorDecl(Parent);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000450 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000451
Douglas Gregorb1373d02010-01-20 20:59:29 +0000452 ~SetParentRAII() {
453 Parent = OldParent;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000454 if (clang_isDeclaration(Parent.kind))
455 StmtParent = getCursorDecl(Parent);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000456 }
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000457 } SetParent(Parent, StmtParent, Cursor);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000458
Douglas Gregorb1373d02010-01-20 20:59:29 +0000459 if (clang_isDeclaration(Cursor.kind)) {
460 Decl *D = getCursorDecl(Cursor);
461 assert(D && "Invalid declaration cursor");
Ted Kremenek539311e2010-02-18 18:47:01 +0000462 return VisitAttributes(D) || Visit(D);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000463 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000464
Douglas Gregora59e3902010-01-21 23:27:09 +0000465 if (clang_isStatement(Cursor.kind))
466 return Visit(getCursorStmt(Cursor));
467 if (clang_isExpression(Cursor.kind))
468 return Visit(getCursorExpr(Cursor));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000469
Douglas Gregorb1373d02010-01-20 20:59:29 +0000470 if (clang_isTranslationUnit(Cursor.kind)) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000471 ASTUnit *CXXUnit = getCursorASTUnit(Cursor);
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000472 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
473 RegionOfInterest.isInvalid()) {
Douglas Gregor7b691f332010-01-20 21:13:59 +0000474 const std::vector<Decl*> &TLDs = CXXUnit->getTopLevelDecls();
475 for (std::vector<Decl*>::const_iterator it = TLDs.begin(),
476 ie = TLDs.end(); it != ie; ++it) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000477 if (Visit(MakeCXCursor(*it, CXXUnit), true))
Douglas Gregor7b691f332010-01-20 21:13:59 +0000478 return true;
479 }
Douglas Gregor0396f462010-03-19 05:22:59 +0000480 } else if (VisitDeclContext(
481 CXXUnit->getASTContext().getTranslationUnitDecl()))
482 return true;
Bob Wilson3178cb62010-03-19 03:57:57 +0000483
Douglas Gregor0396f462010-03-19 05:22:59 +0000484 // Walk the preprocessing record.
Daniel Dunbar8de30ff2010-03-20 01:11:56 +0000485 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000486 // FIXME: Once we have the ability to deserialize a preprocessing record,
487 // do so.
Douglas Gregor788f5a12010-03-20 00:41:21 +0000488 PreprocessingRecord::iterator E, EEnd;
489 for (llvm::tie(E, EEnd) = getPreprocessedEntities(); E != EEnd; ++E) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000490 if (MacroInstantiation *MI = dyn_cast<MacroInstantiation>(*E)) {
491 if (Visit(MakeMacroInstantiationCursor(MI, CXXUnit)))
492 return true;
Douglas Gregor788f5a12010-03-20 00:41:21 +0000493
Douglas Gregor0396f462010-03-19 05:22:59 +0000494 continue;
495 }
496
497 if (MacroDefinition *MD = dyn_cast<MacroDefinition>(*E)) {
498 if (Visit(MakeMacroDefinitionCursor(MD, CXXUnit)))
499 return true;
500
501 continue;
502 }
503 }
504 }
Douglas Gregor7b691f332010-01-20 21:13:59 +0000505 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000506 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000507
Douglas Gregorb1373d02010-01-20 20:59:29 +0000508 // Nothing to visit at the moment.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000509 return false;
510}
511
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000512bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
513 for (BlockDecl::param_iterator I=B->param_begin(), E=B->param_end(); I!=E;++I)
514 if (Decl *D = *I)
515 if (Visit(D))
516 return true;
517
518 return Visit(MakeCXCursor(B->getBody(), StmtParent, TU));
519}
520
Douglas Gregorb1373d02010-01-20 20:59:29 +0000521bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000522 for (DeclContext::decl_iterator
Douglas Gregorb1373d02010-01-20 20:59:29 +0000523 I = DC->decls_begin(), E = DC->decls_end(); I != E; ++I) {
Ted Kremenek09dfa372010-02-18 05:46:33 +0000524
Daniel Dunbard52864b2010-02-14 10:02:57 +0000525 CXCursor Cursor = MakeCXCursor(*I, TU);
526
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000527 if (RegionOfInterest.isValid()) {
Daniel Dunbard52864b2010-02-14 10:02:57 +0000528 SourceRange Range =
529 cxloc::translateCXSourceRange(clang_getCursorExtent(Cursor));
530 if (Range.isInvalid())
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000531 continue;
Daniel Dunbard52864b2010-02-14 10:02:57 +0000532
533 switch (CompareRegionOfInterest(Range)) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000534 case RangeBefore:
535 // This declaration comes before the region of interest; skip it.
536 continue;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000537
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000538 case RangeAfter:
539 // This declaration comes after the region of interest; we're done.
540 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000541
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000542 case RangeOverlap:
543 // This declaration overlaps the region of interest; visit it.
544 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000545 }
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000546 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000547
Daniel Dunbard52864b2010-02-14 10:02:57 +0000548 if (Visit(Cursor, true))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000549 return true;
550 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000551
Douglas Gregorb1373d02010-01-20 20:59:29 +0000552 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000553}
554
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000555bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
556 llvm_unreachable("Translation units are visited directly by Visit()");
557 return false;
558}
559
560bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
561 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
562 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000563
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000564 return false;
565}
566
567bool CursorVisitor::VisitTagDecl(TagDecl *D) {
568 return VisitDeclContext(D);
569}
570
571bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
572 if (Expr *Init = D->getInitExpr())
573 return Visit(MakeCXCursor(Init, StmtParent, TU));
574 return false;
575}
576
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000577bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
578 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
579 if (Visit(TSInfo->getTypeLoc()))
580 return true;
581
582 return false;
583}
584
Douglas Gregorb1373d02010-01-20 20:59:29 +0000585bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000586 if (VisitDeclaratorDecl(ND))
587 return true;
588
Douglas Gregora59e3902010-01-21 23:27:09 +0000589 if (ND->isThisDeclarationADefinition() &&
590 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
591 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000592
Douglas Gregorb1373d02010-01-20 20:59:29 +0000593 return false;
594}
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000595
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000596bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
597 if (VisitDeclaratorDecl(D))
598 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000599
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000600 if (Expr *BitWidth = D->getBitWidth())
601 return Visit(MakeCXCursor(BitWidth, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000602
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000603 return false;
604}
605
606bool CursorVisitor::VisitVarDecl(VarDecl *D) {
607 if (VisitDeclaratorDecl(D))
608 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000609
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000610 if (Expr *Init = D->getInit())
611 return Visit(MakeCXCursor(Init, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000612
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000613 return false;
614}
615
616bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
Douglas Gregor4bc1cb62010-03-08 14:59:44 +0000617 if (TypeSourceInfo *TSInfo = ND->getResultTypeSourceInfo())
618 if (Visit(TSInfo->getTypeLoc()))
619 return true;
620
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000621 for (ObjCMethodDecl::param_iterator P = ND->param_begin(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000622 PEnd = ND->param_end();
623 P != PEnd; ++P) {
624 if (Visit(MakeCXCursor(*P, TU)))
625 return true;
626 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000627
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000628 if (ND->isThisDeclarationADefinition() &&
629 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
630 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000631
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000632 return false;
633}
634
Douglas Gregora59e3902010-01-21 23:27:09 +0000635bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
636 return VisitDeclContext(D);
637}
638
Douglas Gregorb1373d02010-01-20 20:59:29 +0000639bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000640 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
641 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000642 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000643
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000644 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
645 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
646 E = ND->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000647 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000648 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000649
Douglas Gregora59e3902010-01-21 23:27:09 +0000650 return VisitObjCContainerDecl(ND);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000651}
652
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000653bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
654 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
655 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
656 E = PID->protocol_end(); I != E; ++I, ++PL)
657 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
658 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000659
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000660 return VisitObjCContainerDecl(PID);
661}
662
Douglas Gregorb1373d02010-01-20 20:59:29 +0000663bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000664 // Issue callbacks for super class.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000665 if (D->getSuperClass() &&
666 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000667 D->getSuperClassLoc(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000668 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000669 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000670
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000671 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
672 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
673 E = D->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000674 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000675 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000676
Douglas Gregora59e3902010-01-21 23:27:09 +0000677 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000678}
679
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000680bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
681 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000682}
683
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000684bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
Ted Kremenekebfa3392010-03-19 20:39:03 +0000685 // 'ID' could be null when dealing with invalid code.
686 if (ObjCInterfaceDecl *ID = D->getClassInterface())
687 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
688 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000689
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000690 return VisitObjCImplDecl(D);
691}
692
693bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
694#if 0
695 // Issue callbacks for super class.
696 // FIXME: No source location information!
697 if (D->getSuperClass() &&
698 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000699 D->getSuperClassLoc(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000700 TU)))
701 return true;
702#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000703
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000704 return VisitObjCImplDecl(D);
705}
706
707bool CursorVisitor::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D) {
708 ObjCForwardProtocolDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
709 for (ObjCForwardProtocolDecl::protocol_iterator I = D->protocol_begin(),
710 E = D->protocol_end();
711 I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000712 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000713 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000714
715 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000716}
717
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000718bool CursorVisitor::VisitObjCClassDecl(ObjCClassDecl *D) {
719 for (ObjCClassDecl::iterator C = D->begin(), CEnd = D->end(); C != CEnd; ++C)
720 if (Visit(MakeCursorObjCClassRef(C->getInterface(), C->getLocation(), TU)))
721 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000722
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000723 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000724}
725
Ted Kremenek8f06e0e2010-05-06 23:38:21 +0000726bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
727 return VisitDeclContext(D);
728}
729
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000730bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
731 ASTContext &Context = TU->getASTContext();
732
733 // Some builtin types (such as Objective-C's "id", "sel", and
734 // "Class") have associated declarations. Create cursors for those.
735 QualType VisitType;
736 switch (TL.getType()->getAs<BuiltinType>()->getKind()) {
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000737 case BuiltinType::Void:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000738 case BuiltinType::Bool:
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000739 case BuiltinType::Char_U:
740 case BuiltinType::UChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000741 case BuiltinType::Char16:
742 case BuiltinType::Char32:
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000743 case BuiltinType::UShort:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000744 case BuiltinType::UInt:
745 case BuiltinType::ULong:
746 case BuiltinType::ULongLong:
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000747 case BuiltinType::UInt128:
748 case BuiltinType::Char_S:
749 case BuiltinType::SChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000750 case BuiltinType::WChar:
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000751 case BuiltinType::Short:
752 case BuiltinType::Int:
753 case BuiltinType::Long:
754 case BuiltinType::LongLong:
755 case BuiltinType::Int128:
756 case BuiltinType::Float:
757 case BuiltinType::Double:
758 case BuiltinType::LongDouble:
759 case BuiltinType::NullPtr:
760 case BuiltinType::Overload:
761 case BuiltinType::Dependent:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000762 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000763
764 case BuiltinType::UndeducedAuto: // FIXME: Deserves a cursor?
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000765 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000766
Ted Kremenekc4174cc2010-02-18 18:52:18 +0000767 case BuiltinType::ObjCId:
768 VisitType = Context.getObjCIdType();
769 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000770
771 case BuiltinType::ObjCClass:
772 VisitType = Context.getObjCClassType();
773 break;
774
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000775 case BuiltinType::ObjCSel:
776 VisitType = Context.getObjCSelType();
777 break;
778 }
779
780 if (!VisitType.isNull()) {
781 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000782 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000783 TU));
784 }
785
786 return false;
787}
788
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000789bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
790 return Visit(MakeCursorTypeRef(TL.getTypedefDecl(), TL.getNameLoc(), TU));
791}
792
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000793bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
794 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
795}
796
797bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
798 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
799}
800
801bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
802 if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
803 return true;
804
805 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
806 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
807 TU)))
808 return true;
809 }
810
811 return false;
812}
813
814bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
815 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseTypeLoc()))
816 return true;
817
818 if (TL.hasProtocolsAsWritten()) {
819 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000820 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I),
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000821 TL.getProtocolLoc(I),
822 TU)))
823 return true;
824 }
825 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000826
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000827 return false;
828}
829
830bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
831 return Visit(TL.getPointeeLoc());
832}
833
834bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
835 return Visit(TL.getPointeeLoc());
836}
837
838bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
839 return Visit(TL.getPointeeLoc());
840}
841
842bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000843 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000844}
845
846bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000847 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000848}
849
850bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
851 if (Visit(TL.getResultLoc()))
852 return true;
853
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000854 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
Ted Kremenek5dbacb42010-04-07 00:27:13 +0000855 if (Decl *D = TL.getArg(I))
856 if (Visit(MakeCXCursor(D, TU)))
857 return true;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000858
859 return false;
860}
861
862bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
863 if (Visit(TL.getElementLoc()))
864 return true;
865
866 if (Expr *Size = TL.getSizeExpr())
867 return Visit(MakeCXCursor(Size, StmtParent, TU));
868
869 return false;
870}
871
Douglas Gregor2332c112010-01-21 20:48:56 +0000872bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
873 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
874}
875
876bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
877 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
878 return Visit(TSInfo->getTypeLoc());
879
880 return false;
881}
882
Douglas Gregora59e3902010-01-21 23:27:09 +0000883bool CursorVisitor::VisitStmt(Stmt *S) {
884 for (Stmt::child_iterator Child = S->child_begin(), ChildEnd = S->child_end();
885 Child != ChildEnd; ++Child) {
Daniel Dunbar54d67ca2010-01-25 00:40:30 +0000886 if (*Child && Visit(MakeCXCursor(*Child, StmtParent, TU)))
Douglas Gregora59e3902010-01-21 23:27:09 +0000887 return true;
888 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000889
Douglas Gregora59e3902010-01-21 23:27:09 +0000890 return false;
891}
892
893bool CursorVisitor::VisitDeclStmt(DeclStmt *S) {
894 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
895 D != DEnd; ++D) {
Douglas Gregor263b47b2010-01-25 16:12:32 +0000896 if (*D && Visit(MakeCXCursor(*D, TU)))
Douglas Gregora59e3902010-01-21 23:27:09 +0000897 return true;
898 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000899
Douglas Gregora59e3902010-01-21 23:27:09 +0000900 return false;
901}
902
Douglas Gregorf5bab412010-01-22 01:00:11 +0000903bool CursorVisitor::VisitIfStmt(IfStmt *S) {
904 if (VarDecl *Var = S->getConditionVariable()) {
905 if (Visit(MakeCXCursor(Var, TU)))
906 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000907 }
908
Douglas Gregor263b47b2010-01-25 16:12:32 +0000909 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
910 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +0000911 if (S->getThen() && Visit(MakeCXCursor(S->getThen(), StmtParent, TU)))
912 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +0000913 if (S->getElse() && Visit(MakeCXCursor(S->getElse(), StmtParent, TU)))
914 return true;
915
916 return false;
917}
918
919bool CursorVisitor::VisitSwitchStmt(SwitchStmt *S) {
920 if (VarDecl *Var = S->getConditionVariable()) {
921 if (Visit(MakeCXCursor(Var, TU)))
922 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000923 }
924
Douglas Gregor263b47b2010-01-25 16:12:32 +0000925 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
926 return true;
927 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
928 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000929
Douglas Gregor263b47b2010-01-25 16:12:32 +0000930 return false;
931}
932
933bool CursorVisitor::VisitWhileStmt(WhileStmt *S) {
934 if (VarDecl *Var = S->getConditionVariable()) {
935 if (Visit(MakeCXCursor(Var, TU)))
936 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000937 }
938
Douglas Gregor263b47b2010-01-25 16:12:32 +0000939 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
940 return true;
941 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
Douglas Gregorf5bab412010-01-22 01:00:11 +0000942 return true;
943
Douglas Gregor263b47b2010-01-25 16:12:32 +0000944 return false;
945}
946
947bool CursorVisitor::VisitForStmt(ForStmt *S) {
948 if (S->getInit() && Visit(MakeCXCursor(S->getInit(), StmtParent, TU)))
949 return true;
950 if (VarDecl *Var = S->getConditionVariable()) {
951 if (Visit(MakeCXCursor(Var, TU)))
952 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000953 }
954
Douglas Gregor263b47b2010-01-25 16:12:32 +0000955 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
956 return true;
957 if (S->getInc() && Visit(MakeCXCursor(S->getInc(), StmtParent, TU)))
958 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +0000959 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
960 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000961
Douglas Gregorf5bab412010-01-22 01:00:11 +0000962 return false;
963}
964
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000965bool CursorVisitor::VisitBlockExpr(BlockExpr *B) {
966 return Visit(B->getBlockDecl());
967}
968
Douglas Gregor8ecdb652010-04-28 22:16:22 +0000969bool CursorVisitor::VisitOffsetOfExpr(OffsetOfExpr *E) {
970 // FIXME: Visit fields as well?
971 if (Visit(E->getTypeSourceInfo()->getTypeLoc()))
972 return true;
973
974 return VisitExpr(E);
975}
976
Douglas Gregor336fd812010-01-23 00:40:08 +0000977bool CursorVisitor::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E) {
978 if (E->isArgumentType()) {
979 if (TypeSourceInfo *TSInfo = E->getArgumentTypeInfo())
980 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000981
Douglas Gregor336fd812010-01-23 00:40:08 +0000982 return false;
983 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000984
Douglas Gregor336fd812010-01-23 00:40:08 +0000985 return VisitExpr(E);
986}
987
988bool CursorVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
989 if (TypeSourceInfo *TSInfo = E->getTypeInfoAsWritten())
990 if (Visit(TSInfo->getTypeLoc()))
991 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000992
Douglas Gregor336fd812010-01-23 00:40:08 +0000993 return VisitCastExpr(E);
994}
995
996bool CursorVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
997 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
998 if (Visit(TSInfo->getTypeLoc()))
999 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001000
Douglas Gregor336fd812010-01-23 00:40:08 +00001001 return VisitExpr(E);
1002}
1003
Douglas Gregorc2350e52010-03-08 16:40:19 +00001004bool CursorVisitor::VisitObjCMessageExpr(ObjCMessageExpr *E) {
Douglas Gregor04badcf2010-04-21 00:45:42 +00001005 if (TypeSourceInfo *TSInfo = E->getClassReceiverTypeInfo())
1006 if (Visit(TSInfo->getTypeLoc()))
1007 return true;
Douglas Gregorc2350e52010-03-08 16:40:19 +00001008
1009 return VisitExpr(E);
1010}
1011
Douglas Gregor81d34662010-04-20 15:39:42 +00001012bool CursorVisitor::VisitObjCEncodeExpr(ObjCEncodeExpr *E) {
1013 return Visit(E->getEncodedTypeSourceInfo()->getTypeLoc());
1014}
1015
1016
Ted Kremenek09dfa372010-02-18 05:46:33 +00001017bool CursorVisitor::VisitAttributes(Decl *D) {
1018 for (const Attr *A = D->getAttrs(); A; A = A->getNext())
1019 if (Visit(MakeCXCursor(A, D, TU)))
1020 return true;
1021
1022 return false;
1023}
1024
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00001025extern "C" {
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001026CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
1027 int displayDiagnostics) {
Douglas Gregora030b7c2010-01-22 20:35:53 +00001028 CIndexer *CIdxr = new CIndexer();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001029 if (excludeDeclarationsFromPCH)
1030 CIdxr->setOnlyLocalDecls();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001031 if (displayDiagnostics)
1032 CIdxr->setDisplayDiagnostics();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001033 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +00001034}
1035
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001036void clang_disposeIndex(CXIndex CIdx) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001037 if (CIdx)
1038 delete static_cast<CIndexer *>(CIdx);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00001039}
1040
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001041void clang_setUseExternalASTGeneration(CXIndex CIdx, int value) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001042 if (CIdx) {
1043 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
1044 CXXIdx->setUseExternalASTGeneration(value);
1045 }
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001046}
1047
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001048CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
Douglas Gregora88084b2010-02-18 18:08:43 +00001049 const char *ast_filename) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001050 if (!CIdx)
1051 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001052
Douglas Gregor7d1d49d2009-10-16 20:01:17 +00001053 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001054
Douglas Gregor28019772010-04-05 23:52:57 +00001055 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
1056 return ASTUnit::LoadFromPCHFile(ast_filename, Diags,
Douglas Gregora88084b2010-02-18 18:08:43 +00001057 CXXIdx->getOnlyLocalDecls(),
1058 0, 0, true);
Steve Naroff600866c2009-08-27 19:51:58 +00001059}
1060
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001061CXTranslationUnit
1062clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
1063 const char *source_filename,
1064 int num_command_line_args,
Douglas Gregor4db64a42010-01-23 00:14:00 +00001065 const char **command_line_args,
1066 unsigned num_unsaved_files,
Douglas Gregora88084b2010-02-18 18:08:43 +00001067 struct CXUnsavedFile *unsaved_files) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001068 if (!CIdx)
1069 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001070
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001071 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
1072
Douglas Gregor5352ac02010-01-28 00:27:43 +00001073 // Configure the diagnostics.
1074 DiagnosticOptions DiagOpts;
Douglas Gregor28019772010-04-05 23:52:57 +00001075 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
1076 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001077
Douglas Gregor4db64a42010-01-23 00:14:00 +00001078 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
1079 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattnera0a270c2010-04-05 22:42:27 +00001080 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001081 const llvm::MemoryBuffer *Buffer
Chris Lattnera0a270c2010-04-05 22:42:27 +00001082 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregor4db64a42010-01-23 00:14:00 +00001083 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
1084 Buffer));
1085 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001086
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001087 if (!CXXIdx->getUseExternalASTGeneration()) {
1088 llvm::SmallVector<const char *, 16> Args;
1089
1090 // The 'source_filename' argument is optional. If the caller does not
1091 // specify it then it is assumed that the source file is specified
1092 // in the actual argument list.
1093 if (source_filename)
1094 Args.push_back(source_filename);
1095 Args.insert(Args.end(), command_line_args,
1096 command_line_args + num_command_line_args);
Douglas Gregor94dc8f62010-03-19 16:15:56 +00001097 Args.push_back("-Xclang");
1098 Args.push_back("-detailed-preprocessing-record");
Douglas Gregor5352ac02010-01-28 00:27:43 +00001099 unsigned NumErrors = Diags->getNumErrors();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001100
Ted Kremenek29b72842010-01-07 22:49:05 +00001101#ifdef USE_CRASHTRACER
1102 ArgsCrashTracerInfo ACTI(Args);
Ted Kremenek8a8da7d2010-01-06 03:42:32 +00001103#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001104
Daniel Dunbar94220972009-12-05 02:17:18 +00001105 llvm::OwningPtr<ASTUnit> Unit(
1106 ASTUnit::LoadFromCommandLine(Args.data(), Args.data() + Args.size(),
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001107 Diags,
Daniel Dunbar869824e2009-12-13 03:46:13 +00001108 CXXIdx->getClangResourcesPath(),
Daniel Dunbar94220972009-12-05 02:17:18 +00001109 CXXIdx->getOnlyLocalDecls(),
Douglas Gregor4db64a42010-01-23 00:14:00 +00001110 RemappedFiles.data(),
Douglas Gregora88084b2010-02-18 18:08:43 +00001111 RemappedFiles.size(),
Douglas Gregor94dc8f62010-03-19 16:15:56 +00001112 /*CaptureDiagnostics=*/true));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001113
Daniel Dunbar94220972009-12-05 02:17:18 +00001114 // FIXME: Until we have broader testing, just drop the entire AST if we
1115 // encountered an error.
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001116 if (NumErrors != Diags->getNumErrors()) {
Ted Kremenek34f6a322010-03-05 22:43:29 +00001117 // Make sure to check that 'Unit' is non-NULL.
1118 if (CXXIdx->getDisplayDiagnostics() && Unit.get()) {
Douglas Gregor405634b2010-04-05 18:10:21 +00001119 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
1120 DEnd = Unit->stored_diag_end();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001121 D != DEnd; ++D) {
1122 CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOptions());
Douglas Gregor274f1902010-02-22 23:17:23 +00001123 CXString Msg = clang_formatDiagnostic(&Diag,
1124 clang_defaultDiagnosticDisplayOptions());
1125 fprintf(stderr, "%s\n", clang_getCString(Msg));
1126 clang_disposeString(Msg);
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001127 }
Douglas Gregor274f1902010-02-22 23:17:23 +00001128#ifdef LLVM_ON_WIN32
1129 // On Windows, force a flush, since there may be multiple copies of
1130 // stderr and stdout in the file system, all with different buffers
1131 // but writing to the same device.
1132 fflush(stderr);
Ted Kremenek83c51842010-03-26 01:34:51 +00001133#endif
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001134 }
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001135 }
Daniel Dunbar94220972009-12-05 02:17:18 +00001136
1137 return Unit.take();
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001138 }
1139
Ted Kremenek139ba862009-10-22 00:03:57 +00001140 // Build up the arguments for invoking 'clang'.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001141 std::vector<const char *> argv;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001142
Ted Kremenek139ba862009-10-22 00:03:57 +00001143 // First add the complete path to the 'clang' executable.
1144 llvm::sys::Path ClangPath = static_cast<CIndexer *>(CIdx)->getClangPath();
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00001145 argv.push_back(ClangPath.c_str());
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001146
Ted Kremenek139ba862009-10-22 00:03:57 +00001147 // Add the '-emit-ast' option as our execution mode for 'clang'.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001148 argv.push_back("-emit-ast");
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001149
Ted Kremenek139ba862009-10-22 00:03:57 +00001150 // The 'source_filename' argument is optional. If the caller does not
1151 // specify it then it is assumed that the source file is specified
1152 // in the actual argument list.
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001153 if (source_filename)
1154 argv.push_back(source_filename);
Ted Kremenek139ba862009-10-22 00:03:57 +00001155
Steve Naroff37b5ac22009-10-15 20:50:09 +00001156 // Generate a temporary name for the AST file.
Ted Kremenek139ba862009-10-22 00:03:57 +00001157 argv.push_back("-o");
Benjamin Kramerc2a98162010-03-13 21:22:49 +00001158 char astTmpFile[L_tmpnam];
1159 argv.push_back(tmpnam(astTmpFile));
Ted Kremenek139ba862009-10-22 00:03:57 +00001160
Douglas Gregor4db64a42010-01-23 00:14:00 +00001161 // Remap any unsaved files to temporary files.
1162 std::vector<llvm::sys::Path> TemporaryFiles;
1163 std::vector<std::string> RemapArgs;
1164 if (RemapFiles(num_unsaved_files, unsaved_files, RemapArgs, TemporaryFiles))
1165 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001166
Douglas Gregor4db64a42010-01-23 00:14:00 +00001167 // The pointers into the elements of RemapArgs are stable because we
1168 // won't be adding anything to RemapArgs after this point.
1169 for (unsigned i = 0, e = RemapArgs.size(); i != e; ++i)
1170 argv.push_back(RemapArgs[i].c_str());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001171
Ted Kremenek139ba862009-10-22 00:03:57 +00001172 // Process the compiler options, stripping off '-o', '-c', '-fsyntax-only'.
1173 for (int i = 0; i < num_command_line_args; ++i)
1174 if (const char *arg = command_line_args[i]) {
1175 if (strcmp(arg, "-o") == 0) {
1176 ++i; // Also skip the matching argument.
1177 continue;
1178 }
1179 if (strcmp(arg, "-emit-ast") == 0 ||
1180 strcmp(arg, "-c") == 0 ||
1181 strcmp(arg, "-fsyntax-only") == 0) {
1182 continue;
1183 }
1184
1185 // Keep the argument.
1186 argv.push_back(arg);
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001187 }
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001188
Douglas Gregord93256e2010-01-28 06:00:51 +00001189 // Generate a temporary name for the diagnostics file.
Benjamin Kramerc2a98162010-03-13 21:22:49 +00001190 char tmpFileResults[L_tmpnam];
1191 char *tmpResultsFileName = tmpnam(tmpFileResults);
1192 llvm::sys::Path DiagnosticsFile(tmpResultsFileName);
Douglas Gregord93256e2010-01-28 06:00:51 +00001193 TemporaryFiles.push_back(DiagnosticsFile);
1194 argv.push_back("-fdiagnostics-binary");
1195
Douglas Gregor94dc8f62010-03-19 16:15:56 +00001196 argv.push_back("-Xclang");
1197 argv.push_back("-detailed-preprocessing-record");
1198
Ted Kremenek139ba862009-10-22 00:03:57 +00001199 // Add the null terminator.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001200 argv.push_back(NULL);
1201
Ted Kremenekfeb15e32009-10-26 22:14:08 +00001202 // Invoke 'clang'.
1203 llvm::sys::Path DevNull; // leave empty, causes redirection to /dev/null
1204 // on Unix or NUL (Windows).
Ted Kremenek379afec2009-10-22 03:24:01 +00001205 std::string ErrMsg;
Douglas Gregord93256e2010-01-28 06:00:51 +00001206 const llvm::sys::Path *Redirects[] = { &DevNull, &DevNull, &DiagnosticsFile,
1207 NULL };
Ted Kremenek379afec2009-10-22 03:24:01 +00001208 llvm::sys::Program::ExecuteAndWait(ClangPath, &argv[0], /* env */ NULL,
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001209 /* redirects */ &Redirects[0],
Ted Kremenek379afec2009-10-22 03:24:01 +00001210 /* secondsToWait */ 0, /* memoryLimits */ 0, &ErrMsg);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001211
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001212 if (!ErrMsg.empty()) {
1213 std::string AllArgs;
Ted Kremenek379afec2009-10-22 03:24:01 +00001214 for (std::vector<const char*>::iterator I = argv.begin(), E = argv.end();
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001215 I != E; ++I) {
1216 AllArgs += ' ';
Ted Kremenek779e5f42009-10-26 22:08:39 +00001217 if (*I)
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001218 AllArgs += *I;
Ted Kremenek779e5f42009-10-26 22:08:39 +00001219 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001220
Daniel Dunbar32141c82010-02-23 20:23:45 +00001221 Diags->Report(diag::err_fe_invoking) << AllArgs << ErrMsg;
Ted Kremenek379afec2009-10-22 03:24:01 +00001222 }
Benjamin Kramer0829a832009-10-18 11:19:36 +00001223
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001224 ASTUnit *ATU = ASTUnit::LoadFromPCHFile(astTmpFile, Diags,
Douglas Gregor4db64a42010-01-23 00:14:00 +00001225 CXXIdx->getOnlyLocalDecls(),
Douglas Gregor4db64a42010-01-23 00:14:00 +00001226 RemappedFiles.data(),
Douglas Gregora88084b2010-02-18 18:08:43 +00001227 RemappedFiles.size(),
1228 /*CaptureDiagnostics=*/true);
Douglas Gregora88084b2010-02-18 18:08:43 +00001229 if (ATU) {
1230 LoadSerializedDiagnostics(DiagnosticsFile,
1231 num_unsaved_files, unsaved_files,
1232 ATU->getFileManager(),
1233 ATU->getSourceManager(),
Douglas Gregor405634b2010-04-05 18:10:21 +00001234 ATU->getStoredDiagnostics());
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001235 } else if (CXXIdx->getDisplayDiagnostics()) {
1236 // We failed to load the ASTUnit, but we can still deserialize the
1237 // diagnostics and emit them.
1238 FileManager FileMgr;
Douglas Gregorf715ca12010-03-16 00:06:06 +00001239 Diagnostic Diag;
1240 SourceManager SourceMgr(Diag);
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001241 // FIXME: Faked LangOpts!
1242 LangOptions LangOpts;
1243 llvm::SmallVector<StoredDiagnostic, 4> Diags;
1244 LoadSerializedDiagnostics(DiagnosticsFile,
1245 num_unsaved_files, unsaved_files,
1246 FileMgr, SourceMgr, Diags);
1247 for (llvm::SmallVector<StoredDiagnostic, 4>::iterator D = Diags.begin(),
1248 DEnd = Diags.end();
1249 D != DEnd; ++D) {
1250 CXStoredDiagnostic Diag(*D, LangOpts);
Douglas Gregor274f1902010-02-22 23:17:23 +00001251 CXString Msg = clang_formatDiagnostic(&Diag,
1252 clang_defaultDiagnosticDisplayOptions());
1253 fprintf(stderr, "%s\n", clang_getCString(Msg));
1254 clang_disposeString(Msg);
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001255 }
Douglas Gregor274f1902010-02-22 23:17:23 +00001256
1257#ifdef LLVM_ON_WIN32
1258 // On Windows, force a flush, since there may be multiple copies of
1259 // stderr and stdout in the file system, all with different buffers
1260 // but writing to the same device.
1261 fflush(stderr);
1262#endif
Douglas Gregora88084b2010-02-18 18:08:43 +00001263 }
Douglas Gregord93256e2010-01-28 06:00:51 +00001264
Douglas Gregor313e26c2010-02-18 23:35:40 +00001265 if (ATU) {
1266 // Make the translation unit responsible for destroying all temporary files.
1267 for (unsigned i = 0, e = TemporaryFiles.size(); i != e; ++i)
1268 ATU->addTemporaryFile(TemporaryFiles[i]);
1269 ATU->addTemporaryFile(llvm::sys::Path(ATU->getPCHFileName()));
1270 } else {
1271 // Destroy all of the temporary files now; they can't be referenced any
1272 // longer.
1273 llvm::sys::Path(astTmpFile).eraseFromDisk();
1274 for (unsigned i = 0, e = TemporaryFiles.size(); i != e; ++i)
1275 TemporaryFiles[i].eraseFromDisk();
1276 }
1277
Steve Naroffe19944c2009-10-15 22:23:48 +00001278 return ATU;
Steve Naroff5b7d8e22009-10-15 20:04:39 +00001279}
1280
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001281void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001282 if (CTUnit)
1283 delete static_cast<ASTUnit *>(CTUnit);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00001284}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001285
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001286CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001287 if (!CTUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001288 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001289
Steve Naroff77accc12009-09-03 18:19:54 +00001290 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001291 return createCXString(CXXUnit->getOriginalSourceFileName(), true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +00001292}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +00001293
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001294CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001295 CXCursor Result = { CXCursor_TranslationUnit, { 0, 0, TU } };
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001296 return Result;
1297}
1298
Ted Kremenekfb480492010-01-13 21:46:36 +00001299} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +00001300
Ted Kremenekfb480492010-01-13 21:46:36 +00001301//===----------------------------------------------------------------------===//
Douglas Gregor1db19de2010-01-19 21:36:55 +00001302// CXSourceLocation and CXSourceRange Operations.
1303//===----------------------------------------------------------------------===//
1304
Douglas Gregorb9790342010-01-22 21:44:22 +00001305extern "C" {
1306CXSourceLocation clang_getNullLocation() {
Douglas Gregor5352ac02010-01-28 00:27:43 +00001307 CXSourceLocation Result = { { 0, 0 }, 0 };
Douglas Gregorb9790342010-01-22 21:44:22 +00001308 return Result;
1309}
1310
1311unsigned clang_equalLocations(CXSourceLocation loc1, CXSourceLocation loc2) {
Daniel Dunbar90a6b9e2010-01-30 23:58:27 +00001312 return (loc1.ptr_data[0] == loc2.ptr_data[0] &&
1313 loc1.ptr_data[1] == loc2.ptr_data[1] &&
1314 loc1.int_data == loc2.int_data);
Douglas Gregorb9790342010-01-22 21:44:22 +00001315}
1316
1317CXSourceLocation clang_getLocation(CXTranslationUnit tu,
1318 CXFile file,
1319 unsigned line,
1320 unsigned column) {
Douglas Gregor42748ec2010-04-30 19:45:53 +00001321 if (!tu || !file)
Douglas Gregorb9790342010-01-22 21:44:22 +00001322 return clang_getNullLocation();
Douglas Gregor42748ec2010-04-30 19:45:53 +00001323
Douglas Gregorb9790342010-01-22 21:44:22 +00001324 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
1325 SourceLocation SLoc
1326 = CXXUnit->getSourceManager().getLocation(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001327 static_cast<const FileEntry *>(file),
Douglas Gregorb9790342010-01-22 21:44:22 +00001328 line, column);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001329
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00001330 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
Douglas Gregorb9790342010-01-22 21:44:22 +00001331}
1332
Douglas Gregor5352ac02010-01-28 00:27:43 +00001333CXSourceRange clang_getNullRange() {
1334 CXSourceRange Result = { { 0, 0 }, 0, 0 };
1335 return Result;
1336}
Daniel Dunbard52864b2010-02-14 10:02:57 +00001337
Douglas Gregor5352ac02010-01-28 00:27:43 +00001338CXSourceRange clang_getRange(CXSourceLocation begin, CXSourceLocation end) {
1339 if (begin.ptr_data[0] != end.ptr_data[0] ||
1340 begin.ptr_data[1] != end.ptr_data[1])
1341 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001342
1343 CXSourceRange Result = { { begin.ptr_data[0], begin.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00001344 begin.int_data, end.int_data };
Douglas Gregorb9790342010-01-22 21:44:22 +00001345 return Result;
1346}
1347
Douglas Gregor46766dc2010-01-26 19:19:08 +00001348void clang_getInstantiationLocation(CXSourceLocation location,
1349 CXFile *file,
1350 unsigned *line,
1351 unsigned *column,
1352 unsigned *offset) {
Douglas Gregor1db19de2010-01-19 21:36:55 +00001353 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
1354
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00001355 if (!location.ptr_data[0] || Loc.isInvalid()) {
Douglas Gregor46766dc2010-01-26 19:19:08 +00001356 if (file)
1357 *file = 0;
1358 if (line)
1359 *line = 0;
1360 if (column)
1361 *column = 0;
1362 if (offset)
1363 *offset = 0;
1364 return;
1365 }
1366
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00001367 const SourceManager &SM =
1368 *static_cast<const SourceManager*>(location.ptr_data[0]);
Douglas Gregor1db19de2010-01-19 21:36:55 +00001369 SourceLocation InstLoc = SM.getInstantiationLoc(Loc);
Douglas Gregor1db19de2010-01-19 21:36:55 +00001370
1371 if (file)
1372 *file = (void *)SM.getFileEntryForID(SM.getFileID(InstLoc));
1373 if (line)
1374 *line = SM.getInstantiationLineNumber(InstLoc);
1375 if (column)
1376 *column = SM.getInstantiationColumnNumber(InstLoc);
Douglas Gregore69517c2010-01-26 03:07:15 +00001377 if (offset)
Douglas Gregor46766dc2010-01-26 19:19:08 +00001378 *offset = SM.getDecomposedLoc(InstLoc).second;
Douglas Gregore69517c2010-01-26 03:07:15 +00001379}
1380
Douglas Gregor1db19de2010-01-19 21:36:55 +00001381CXSourceLocation clang_getRangeStart(CXSourceRange range) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001382 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00001383 range.begin_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00001384 return Result;
1385}
1386
1387CXSourceLocation clang_getRangeEnd(CXSourceRange range) {
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00001388 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00001389 range.end_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00001390 return Result;
1391}
1392
Douglas Gregorb9790342010-01-22 21:44:22 +00001393} // end: extern "C"
1394
Douglas Gregor1db19de2010-01-19 21:36:55 +00001395//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00001396// CXFile Operations.
1397//===----------------------------------------------------------------------===//
1398
1399extern "C" {
Ted Kremenek74844072010-02-17 00:41:20 +00001400CXString clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00001401 if (!SFile)
Ted Kremenek74844072010-02-17 00:41:20 +00001402 return createCXString(NULL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001403
Steve Naroff88145032009-10-27 14:35:18 +00001404 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Ted Kremenek74844072010-02-17 00:41:20 +00001405 return createCXString(FEnt->getName());
Steve Naroff88145032009-10-27 14:35:18 +00001406}
1407
1408time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00001409 if (!SFile)
1410 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001411
Steve Naroff88145032009-10-27 14:35:18 +00001412 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
1413 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +00001414}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001415
Douglas Gregorb9790342010-01-22 21:44:22 +00001416CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
1417 if (!tu)
1418 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001419
Douglas Gregorb9790342010-01-22 21:44:22 +00001420 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001421
Douglas Gregorb9790342010-01-22 21:44:22 +00001422 FileManager &FMgr = CXXUnit->getFileManager();
1423 const FileEntry *File = FMgr.getFile(file_name, file_name+strlen(file_name));
1424 return const_cast<FileEntry *>(File);
1425}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001426
Ted Kremenekfb480492010-01-13 21:46:36 +00001427} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +00001428
Ted Kremenekfb480492010-01-13 21:46:36 +00001429//===----------------------------------------------------------------------===//
1430// CXCursor Operations.
1431//===----------------------------------------------------------------------===//
1432
Ted Kremenekfb480492010-01-13 21:46:36 +00001433static Decl *getDeclFromExpr(Stmt *E) {
1434 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
1435 return RefExpr->getDecl();
1436 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
1437 return ME->getMemberDecl();
1438 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
1439 return RE->getDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001440
Ted Kremenekfb480492010-01-13 21:46:36 +00001441 if (CallExpr *CE = dyn_cast<CallExpr>(E))
1442 return getDeclFromExpr(CE->getCallee());
1443 if (CastExpr *CE = dyn_cast<CastExpr>(E))
1444 return getDeclFromExpr(CE->getSubExpr());
1445 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
1446 return OME->getMethodDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001447
Ted Kremenekfb480492010-01-13 21:46:36 +00001448 return 0;
1449}
1450
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00001451static SourceLocation getLocationFromExpr(Expr *E) {
1452 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
1453 return /*FIXME:*/Msg->getLeftLoc();
1454 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
1455 return DRE->getLocation();
1456 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
1457 return Member->getMemberLoc();
1458 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
1459 return Ivar->getLocation();
1460 return E->getLocStart();
1461}
1462
Ted Kremenekfb480492010-01-13 21:46:36 +00001463extern "C" {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001464
1465unsigned clang_visitChildren(CXCursor parent,
Douglas Gregorb1373d02010-01-20 20:59:29 +00001466 CXCursorVisitor visitor,
1467 CXClientData client_data) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001468 ASTUnit *CXXUnit = getCursorASTUnit(parent);
Douglas Gregorb1373d02010-01-20 20:59:29 +00001469
1470 unsigned PCHLevel = Decl::MaxPCHLevel;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001471
Douglas Gregorb1373d02010-01-20 20:59:29 +00001472 // Set the PCHLevel to filter out unwanted decls if requested.
1473 if (CXXUnit->getOnlyLocalDecls()) {
1474 PCHLevel = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001475
Douglas Gregorb1373d02010-01-20 20:59:29 +00001476 // If the main input was an AST, bump the level.
1477 if (CXXUnit->isMainFileAST())
1478 ++PCHLevel;
1479 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001480
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001481 CursorVisitor CursorVis(CXXUnit, visitor, client_data, PCHLevel);
Douglas Gregorb1373d02010-01-20 20:59:29 +00001482 return CursorVis.VisitChildren(parent);
1483}
1484
Douglas Gregor78205d42010-01-20 21:45:58 +00001485static CXString getDeclSpelling(Decl *D) {
1486 NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
1487 if (!ND)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001488 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001489
Douglas Gregor78205d42010-01-20 21:45:58 +00001490 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001491 return createCXString(OMD->getSelector().getAsString());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001492
Douglas Gregor78205d42010-01-20 21:45:58 +00001493 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
1494 // No, this isn't the same as the code below. getIdentifier() is non-virtual
1495 // and returns different names. NamedDecl returns the class name and
1496 // ObjCCategoryImplDecl returns the category name.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001497 return createCXString(CIMP->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001498
Douglas Gregor78205d42010-01-20 21:45:58 +00001499 if (ND->getIdentifier())
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001500 return createCXString(ND->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001501
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001502 return createCXString("");
Douglas Gregor78205d42010-01-20 21:45:58 +00001503}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001504
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001505CXString clang_getCursorSpelling(CXCursor C) {
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001506 if (clang_isTranslationUnit(C.kind))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001507 return clang_getTranslationUnitSpelling(C.data[2]);
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001508
Steve Narofff334b4e2009-09-02 18:26:48 +00001509 if (clang_isReference(C.kind)) {
1510 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00001511 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +00001512 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001513 return createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00001514 }
1515 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +00001516 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001517 return createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00001518 }
1519 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +00001520 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +00001521 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001522 return createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00001523 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001524 case CXCursor_TypeRef: {
1525 TypeDecl *Type = getCursorTypeRef(C).first;
1526 assert(Type && "Missing type decl");
1527
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001528 return createCXString(getCursorContext(C).getTypeDeclType(Type).
1529 getAsString());
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001530 }
1531
Daniel Dunbaracca7252009-11-30 20:42:49 +00001532 default:
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001533 return createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +00001534 }
1535 }
Douglas Gregor97b98722010-01-19 23:20:36 +00001536
1537 if (clang_isExpression(C.kind)) {
1538 Decl *D = getDeclFromExpr(getCursorExpr(C));
1539 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +00001540 return getDeclSpelling(D);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001541 return createCXString("");
Douglas Gregor97b98722010-01-19 23:20:36 +00001542 }
1543
Douglas Gregor4ae8f292010-03-18 17:52:52 +00001544 if (C.kind == CXCursor_MacroInstantiation)
1545 return createCXString(getCursorMacroInstantiation(C)->getName()
1546 ->getNameStart());
1547
Douglas Gregor572feb22010-03-18 18:04:21 +00001548 if (C.kind == CXCursor_MacroDefinition)
1549 return createCXString(getCursorMacroDefinition(C)->getName()
1550 ->getNameStart());
1551
Douglas Gregor60cbfac2010-01-25 16:56:17 +00001552 if (clang_isDeclaration(C.kind))
1553 return getDeclSpelling(getCursorDecl(C));
Ted Kremeneke68fff62010-02-17 00:41:32 +00001554
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001555 return createCXString("");
Steve Narofff334b4e2009-09-02 18:26:48 +00001556}
1557
Ted Kremeneke68fff62010-02-17 00:41:32 +00001558CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00001559 switch (Kind) {
Ted Kremeneke68fff62010-02-17 00:41:32 +00001560 case CXCursor_FunctionDecl:
1561 return createCXString("FunctionDecl");
1562 case CXCursor_TypedefDecl:
1563 return createCXString("TypedefDecl");
1564 case CXCursor_EnumDecl:
1565 return createCXString("EnumDecl");
1566 case CXCursor_EnumConstantDecl:
1567 return createCXString("EnumConstantDecl");
1568 case CXCursor_StructDecl:
1569 return createCXString("StructDecl");
1570 case CXCursor_UnionDecl:
1571 return createCXString("UnionDecl");
1572 case CXCursor_ClassDecl:
1573 return createCXString("ClassDecl");
1574 case CXCursor_FieldDecl:
1575 return createCXString("FieldDecl");
1576 case CXCursor_VarDecl:
1577 return createCXString("VarDecl");
1578 case CXCursor_ParmDecl:
1579 return createCXString("ParmDecl");
1580 case CXCursor_ObjCInterfaceDecl:
1581 return createCXString("ObjCInterfaceDecl");
1582 case CXCursor_ObjCCategoryDecl:
1583 return createCXString("ObjCCategoryDecl");
1584 case CXCursor_ObjCProtocolDecl:
1585 return createCXString("ObjCProtocolDecl");
1586 case CXCursor_ObjCPropertyDecl:
1587 return createCXString("ObjCPropertyDecl");
1588 case CXCursor_ObjCIvarDecl:
1589 return createCXString("ObjCIvarDecl");
1590 case CXCursor_ObjCInstanceMethodDecl:
1591 return createCXString("ObjCInstanceMethodDecl");
1592 case CXCursor_ObjCClassMethodDecl:
1593 return createCXString("ObjCClassMethodDecl");
1594 case CXCursor_ObjCImplementationDecl:
1595 return createCXString("ObjCImplementationDecl");
1596 case CXCursor_ObjCCategoryImplDecl:
1597 return createCXString("ObjCCategoryImplDecl");
Ted Kremenek8bd5a692010-04-13 23:39:06 +00001598 case CXCursor_CXXMethod:
1599 return createCXString("CXXMethod");
Ted Kremeneke68fff62010-02-17 00:41:32 +00001600 case CXCursor_UnexposedDecl:
1601 return createCXString("UnexposedDecl");
1602 case CXCursor_ObjCSuperClassRef:
1603 return createCXString("ObjCSuperClassRef");
1604 case CXCursor_ObjCProtocolRef:
1605 return createCXString("ObjCProtocolRef");
1606 case CXCursor_ObjCClassRef:
1607 return createCXString("ObjCClassRef");
1608 case CXCursor_TypeRef:
1609 return createCXString("TypeRef");
1610 case CXCursor_UnexposedExpr:
1611 return createCXString("UnexposedExpr");
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00001612 case CXCursor_BlockExpr:
1613 return createCXString("BlockExpr");
Ted Kremeneke68fff62010-02-17 00:41:32 +00001614 case CXCursor_DeclRefExpr:
1615 return createCXString("DeclRefExpr");
1616 case CXCursor_MemberRefExpr:
1617 return createCXString("MemberRefExpr");
1618 case CXCursor_CallExpr:
1619 return createCXString("CallExpr");
1620 case CXCursor_ObjCMessageExpr:
1621 return createCXString("ObjCMessageExpr");
1622 case CXCursor_UnexposedStmt:
1623 return createCXString("UnexposedStmt");
1624 case CXCursor_InvalidFile:
1625 return createCXString("InvalidFile");
Ted Kremenek292db642010-03-19 20:39:05 +00001626 case CXCursor_InvalidCode:
1627 return createCXString("InvalidCode");
Ted Kremeneke68fff62010-02-17 00:41:32 +00001628 case CXCursor_NoDeclFound:
1629 return createCXString("NoDeclFound");
1630 case CXCursor_NotImplemented:
1631 return createCXString("NotImplemented");
1632 case CXCursor_TranslationUnit:
1633 return createCXString("TranslationUnit");
Ted Kremeneke77f4432010-02-18 03:09:07 +00001634 case CXCursor_UnexposedAttr:
1635 return createCXString("UnexposedAttr");
1636 case CXCursor_IBActionAttr:
1637 return createCXString("attribute(ibaction)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00001638 case CXCursor_IBOutletAttr:
1639 return createCXString("attribute(iboutlet)");
1640 case CXCursor_PreprocessingDirective:
1641 return createCXString("preprocessing directive");
Douglas Gregor572feb22010-03-18 18:04:21 +00001642 case CXCursor_MacroDefinition:
1643 return createCXString("macro definition");
Douglas Gregor48072312010-03-18 15:23:44 +00001644 case CXCursor_MacroInstantiation:
1645 return createCXString("macro instantiation");
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00001646 case CXCursor_Namespace:
1647 return createCXString("Namespace");
Steve Naroff89922f82009-08-31 00:59:03 +00001648 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00001649
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00001650 llvm_unreachable("Unhandled CXCursorKind");
Ted Kremeneke68fff62010-02-17 00:41:32 +00001651 return createCXString(NULL);
Steve Naroff600866c2009-08-27 19:51:58 +00001652}
Steve Naroff89922f82009-08-31 00:59:03 +00001653
Ted Kremeneke68fff62010-02-17 00:41:32 +00001654enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
1655 CXCursor parent,
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001656 CXClientData client_data) {
1657 CXCursor *BestCursor = static_cast<CXCursor *>(client_data);
1658 *BestCursor = cursor;
1659 return CXChildVisit_Recurse;
1660}
Ted Kremeneke68fff62010-02-17 00:41:32 +00001661
Douglas Gregorb9790342010-01-22 21:44:22 +00001662CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
1663 if (!TU)
Ted Kremenekf4629892010-01-14 01:51:23 +00001664 return clang_getNullCursor();
Ted Kremeneke68fff62010-02-17 00:41:32 +00001665
Douglas Gregorb9790342010-01-22 21:44:22 +00001666 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
1667
Douglas Gregorbdf60622010-03-05 21:16:25 +00001668 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
1669
Ted Kremeneka297de22010-01-25 22:34:44 +00001670 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001671 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
1672 if (SLoc.isValid()) {
Daniel Dunbard52864b2010-02-14 10:02:57 +00001673 SourceRange RegionOfInterest(SLoc, SLoc.getFileLocWithOffset(1));
Ted Kremeneke68fff62010-02-17 00:41:32 +00001674
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001675 // FIXME: Would be great to have a "hint" cursor, then walk from that
1676 // hint cursor upward until we find a cursor whose source range encloses
1677 // the region of interest, rather than starting from the translation unit.
1678 CXCursor Parent = clang_getTranslationUnitCursor(CXXUnit);
Ted Kremeneke68fff62010-02-17 00:41:32 +00001679 CursorVisitor CursorVis(CXXUnit, GetCursorVisitor, &Result,
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001680 Decl::MaxPCHLevel, RegionOfInterest);
1681 CursorVis.VisitChildren(Parent);
Steve Naroff77128dd2009-09-15 20:25:34 +00001682 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00001683 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00001684}
1685
Ted Kremenek73885552009-11-17 19:28:59 +00001686CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00001687 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00001688}
1689
1690unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00001691 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00001692}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001693
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001694unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00001695 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
1696}
1697
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001698unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +00001699 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
1700}
Steve Naroff2d4d6292009-08-31 14:26:51 +00001701
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001702unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00001703 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
1704}
1705
Douglas Gregor97b98722010-01-19 23:20:36 +00001706unsigned clang_isExpression(enum CXCursorKind K) {
1707 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
1708}
1709
1710unsigned clang_isStatement(enum CXCursorKind K) {
1711 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
1712}
1713
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001714unsigned clang_isTranslationUnit(enum CXCursorKind K) {
1715 return K == CXCursor_TranslationUnit;
1716}
1717
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00001718unsigned clang_isPreprocessing(enum CXCursorKind K) {
1719 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
1720}
1721
Ted Kremenekad6eff62010-03-08 21:17:29 +00001722unsigned clang_isUnexposed(enum CXCursorKind K) {
1723 switch (K) {
1724 case CXCursor_UnexposedDecl:
1725 case CXCursor_UnexposedExpr:
1726 case CXCursor_UnexposedStmt:
1727 case CXCursor_UnexposedAttr:
1728 return true;
1729 default:
1730 return false;
1731 }
1732}
1733
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001734CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00001735 return C.kind;
1736}
1737
Douglas Gregor98258af2010-01-18 22:46:11 +00001738CXSourceLocation clang_getCursorLocation(CXCursor C) {
1739 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00001740 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001741 case CXCursor_ObjCSuperClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00001742 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1743 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001744 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001745 }
1746
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001747 case CXCursor_ObjCProtocolRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00001748 std::pair<ObjCProtocolDecl *, SourceLocation> P
1749 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001750 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001751 }
1752
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001753 case CXCursor_ObjCClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00001754 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1755 = getCursorObjCClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001756 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001757 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001758
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001759 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001760 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001761 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001762 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001763
Douglas Gregorf46034a2010-01-18 23:41:10 +00001764 default:
1765 // FIXME: Need a way to enumerate all non-reference cases.
1766 llvm_unreachable("Missed a reference kind");
1767 }
Douglas Gregor98258af2010-01-18 22:46:11 +00001768 }
Douglas Gregor97b98722010-01-19 23:20:36 +00001769
1770 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001771 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00001772 getLocationFromExpr(getCursorExpr(C)));
1773
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00001774 if (C.kind == CXCursor_PreprocessingDirective) {
1775 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
1776 return cxloc::translateSourceLocation(getCursorContext(C), L);
1777 }
Douglas Gregor48072312010-03-18 15:23:44 +00001778
1779 if (C.kind == CXCursor_MacroInstantiation) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00001780 SourceLocation L
1781 = cxcursor::getCursorMacroInstantiation(C)->getSourceRange().getBegin();
Douglas Gregor48072312010-03-18 15:23:44 +00001782 return cxloc::translateSourceLocation(getCursorContext(C), L);
1783 }
Douglas Gregor572feb22010-03-18 18:04:21 +00001784
1785 if (C.kind == CXCursor_MacroDefinition) {
1786 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
1787 return cxloc::translateSourceLocation(getCursorContext(C), L);
1788 }
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00001789
Douglas Gregor5352ac02010-01-28 00:27:43 +00001790 if (!getCursorDecl(C))
1791 return clang_getNullLocation();
Douglas Gregor98258af2010-01-18 22:46:11 +00001792
Douglas Gregorf46034a2010-01-18 23:41:10 +00001793 Decl *D = getCursorDecl(C);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001794 SourceLocation Loc = D->getLocation();
1795 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
1796 Loc = Class->getClassLoc();
Douglas Gregor2ca54fe2010-03-22 15:53:50 +00001797 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00001798}
Douglas Gregora7bde202010-01-19 00:34:46 +00001799
1800CXSourceRange clang_getCursorExtent(CXCursor C) {
1801 if (clang_isReference(C.kind)) {
1802 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001803 case CXCursor_ObjCSuperClassRef: {
Douglas Gregora7bde202010-01-19 00:34:46 +00001804 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1805 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001806 return cxloc::translateSourceRange(P.first->getASTContext(), P.second);
Douglas Gregora7bde202010-01-19 00:34:46 +00001807 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001808
1809 case CXCursor_ObjCProtocolRef: {
Douglas Gregora7bde202010-01-19 00:34:46 +00001810 std::pair<ObjCProtocolDecl *, SourceLocation> P
1811 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001812 return cxloc::translateSourceRange(P.first->getASTContext(), P.second);
Douglas Gregora7bde202010-01-19 00:34:46 +00001813 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001814
1815 case CXCursor_ObjCClassRef: {
Douglas Gregora7bde202010-01-19 00:34:46 +00001816 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1817 = getCursorObjCClassRef(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001818
Ted Kremeneka297de22010-01-25 22:34:44 +00001819 return cxloc::translateSourceRange(P.first->getASTContext(), P.second);
Douglas Gregora7bde202010-01-19 00:34:46 +00001820 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001821
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001822 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001823 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001824 return cxloc::translateSourceRange(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001825 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001826
Douglas Gregora7bde202010-01-19 00:34:46 +00001827 default:
1828 // FIXME: Need a way to enumerate all non-reference cases.
1829 llvm_unreachable("Missed a reference kind");
1830 }
1831 }
Douglas Gregor97b98722010-01-19 23:20:36 +00001832
1833 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001834 return cxloc::translateSourceRange(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00001835 getCursorExpr(C)->getSourceRange());
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001836
1837 if (clang_isStatement(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001838 return cxloc::translateSourceRange(getCursorContext(C),
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001839 getCursorStmt(C)->getSourceRange());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001840
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00001841 if (C.kind == CXCursor_PreprocessingDirective) {
1842 SourceRange R = cxcursor::getCursorPreprocessingDirective(C);
1843 return cxloc::translateSourceRange(getCursorContext(C), R);
1844 }
Douglas Gregor48072312010-03-18 15:23:44 +00001845
1846 if (C.kind == CXCursor_MacroInstantiation) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00001847 SourceRange R = cxcursor::getCursorMacroInstantiation(C)->getSourceRange();
Douglas Gregor48072312010-03-18 15:23:44 +00001848 return cxloc::translateSourceRange(getCursorContext(C), R);
1849 }
Douglas Gregor572feb22010-03-18 18:04:21 +00001850
1851 if (C.kind == CXCursor_MacroDefinition) {
1852 SourceRange R = cxcursor::getCursorMacroDefinition(C)->getSourceRange();
1853 return cxloc::translateSourceRange(getCursorContext(C), R);
1854 }
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00001855
Douglas Gregor5352ac02010-01-28 00:27:43 +00001856 if (!getCursorDecl(C))
1857 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001858
Douglas Gregora7bde202010-01-19 00:34:46 +00001859 Decl *D = getCursorDecl(C);
Douglas Gregor2ca54fe2010-03-22 15:53:50 +00001860 return cxloc::translateSourceRange(getCursorContext(C), D->getSourceRange());
Douglas Gregora7bde202010-01-19 00:34:46 +00001861}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001862
1863CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001864 if (clang_isInvalid(C.kind))
1865 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001866
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001867 ASTUnit *CXXUnit = getCursorASTUnit(C);
Douglas Gregorb6998662010-01-19 19:34:47 +00001868 if (clang_isDeclaration(C.kind))
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001869 return C;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001870
Douglas Gregor97b98722010-01-19 23:20:36 +00001871 if (clang_isExpression(C.kind)) {
1872 Decl *D = getDeclFromExpr(getCursorExpr(C));
1873 if (D)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001874 return MakeCXCursor(D, CXXUnit);
Douglas Gregor97b98722010-01-19 23:20:36 +00001875 return clang_getNullCursor();
1876 }
1877
Douglas Gregorbf7efa22010-03-18 18:23:03 +00001878 if (C.kind == CXCursor_MacroInstantiation) {
1879 if (MacroDefinition *Def = getCursorMacroInstantiation(C)->getDefinition())
1880 return MakeMacroDefinitionCursor(Def, CXXUnit);
1881 }
1882
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001883 if (!clang_isReference(C.kind))
1884 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001885
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001886 switch (C.kind) {
1887 case CXCursor_ObjCSuperClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001888 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001889
1890 case CXCursor_ObjCProtocolRef: {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001891 return MakeCXCursor(getCursorObjCProtocolRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001892
1893 case CXCursor_ObjCClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001894 return MakeCXCursor(getCursorObjCClassRef(C).first, CXXUnit);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001895
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001896 case CXCursor_TypeRef:
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001897 return MakeCXCursor(getCursorTypeRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001898
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001899 default:
1900 // We would prefer to enumerate all non-reference cursor kinds here.
1901 llvm_unreachable("Unhandled reference cursor kind");
1902 break;
1903 }
1904 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001905
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001906 return clang_getNullCursor();
1907}
1908
Douglas Gregorb6998662010-01-19 19:34:47 +00001909CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001910 if (clang_isInvalid(C.kind))
1911 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001912
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001913 ASTUnit *CXXUnit = getCursorASTUnit(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001914
Douglas Gregorb6998662010-01-19 19:34:47 +00001915 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00001916 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00001917 C = clang_getCursorReferenced(C);
1918 WasReference = true;
1919 }
1920
Douglas Gregorbf7efa22010-03-18 18:23:03 +00001921 if (C.kind == CXCursor_MacroInstantiation)
1922 return clang_getCursorReferenced(C);
1923
Douglas Gregorb6998662010-01-19 19:34:47 +00001924 if (!clang_isDeclaration(C.kind))
1925 return clang_getNullCursor();
1926
1927 Decl *D = getCursorDecl(C);
1928 if (!D)
1929 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001930
Douglas Gregorb6998662010-01-19 19:34:47 +00001931 switch (D->getKind()) {
1932 // Declaration kinds that don't really separate the notions of
1933 // declaration and definition.
1934 case Decl::Namespace:
1935 case Decl::Typedef:
1936 case Decl::TemplateTypeParm:
1937 case Decl::EnumConstant:
1938 case Decl::Field:
1939 case Decl::ObjCIvar:
1940 case Decl::ObjCAtDefsField:
1941 case Decl::ImplicitParam:
1942 case Decl::ParmVar:
1943 case Decl::NonTypeTemplateParm:
1944 case Decl::TemplateTemplateParm:
1945 case Decl::ObjCCategoryImpl:
1946 case Decl::ObjCImplementation:
1947 case Decl::LinkageSpec:
1948 case Decl::ObjCPropertyImpl:
1949 case Decl::FileScopeAsm:
1950 case Decl::StaticAssert:
1951 case Decl::Block:
1952 return C;
1953
1954 // Declaration kinds that don't make any sense here, but are
1955 // nonetheless harmless.
1956 case Decl::TranslationUnit:
Douglas Gregorb6998662010-01-19 19:34:47 +00001957 break;
1958
1959 // Declaration kinds for which the definition is not resolvable.
1960 case Decl::UnresolvedUsingTypename:
1961 case Decl::UnresolvedUsingValue:
1962 break;
1963
1964 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001965 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
1966 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001967
1968 case Decl::NamespaceAlias:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001969 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001970
1971 case Decl::Enum:
1972 case Decl::Record:
1973 case Decl::CXXRecord:
1974 case Decl::ClassTemplateSpecialization:
1975 case Decl::ClassTemplatePartialSpecialization:
Douglas Gregor952b0172010-02-11 01:04:33 +00001976 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001977 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001978 return clang_getNullCursor();
1979
1980 case Decl::Function:
1981 case Decl::CXXMethod:
1982 case Decl::CXXConstructor:
1983 case Decl::CXXDestructor:
1984 case Decl::CXXConversion: {
1985 const FunctionDecl *Def = 0;
1986 if (cast<FunctionDecl>(D)->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001987 return MakeCXCursor(const_cast<FunctionDecl *>(Def), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001988 return clang_getNullCursor();
1989 }
1990
1991 case Decl::Var: {
Sebastian Redl31310a22010-02-01 20:16:42 +00001992 // Ask the variable if it has a definition.
1993 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
1994 return MakeCXCursor(Def, CXXUnit);
1995 return clang_getNullCursor();
Douglas Gregorb6998662010-01-19 19:34:47 +00001996 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001997
Douglas Gregorb6998662010-01-19 19:34:47 +00001998 case Decl::FunctionTemplate: {
1999 const FunctionDecl *Def = 0;
2000 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002001 return MakeCXCursor(Def->getDescribedFunctionTemplate(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002002 return clang_getNullCursor();
2003 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002004
Douglas Gregorb6998662010-01-19 19:34:47 +00002005 case Decl::ClassTemplate: {
2006 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
Douglas Gregor952b0172010-02-11 01:04:33 +00002007 ->getDefinition())
Douglas Gregorb6998662010-01-19 19:34:47 +00002008 return MakeCXCursor(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002009 cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002010 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002011 return clang_getNullCursor();
2012 }
2013
2014 case Decl::Using: {
2015 UsingDecl *Using = cast<UsingDecl>(D);
2016 CXCursor Def = clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002017 for (UsingDecl::shadow_iterator S = Using->shadow_begin(),
2018 SEnd = Using->shadow_end();
Douglas Gregorb6998662010-01-19 19:34:47 +00002019 S != SEnd; ++S) {
2020 if (Def != clang_getNullCursor()) {
2021 // FIXME: We have no way to return multiple results.
2022 return clang_getNullCursor();
2023 }
2024
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002025 Def = clang_getCursorDefinition(MakeCXCursor((*S)->getTargetDecl(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002026 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002027 }
2028
2029 return Def;
2030 }
2031
2032 case Decl::UsingShadow:
2033 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002034 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002035 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002036
2037 case Decl::ObjCMethod: {
2038 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
2039 if (Method->isThisDeclarationADefinition())
2040 return C;
2041
2042 // Dig out the method definition in the associated
2043 // @implementation, if we have it.
2044 // FIXME: The ASTs should make finding the definition easier.
2045 if (ObjCInterfaceDecl *Class
2046 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
2047 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
2048 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
2049 Method->isInstanceMethod()))
2050 if (Def->isThisDeclarationADefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002051 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002052
2053 return clang_getNullCursor();
2054 }
2055
2056 case Decl::ObjCCategory:
2057 if (ObjCCategoryImplDecl *Impl
2058 = cast<ObjCCategoryDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002059 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002060 return clang_getNullCursor();
2061
2062 case Decl::ObjCProtocol:
2063 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
2064 return C;
2065 return clang_getNullCursor();
2066
2067 case Decl::ObjCInterface:
2068 // There are two notions of a "definition" for an Objective-C
2069 // class: the interface and its implementation. When we resolved a
2070 // reference to an Objective-C class, produce the @interface as
2071 // the definition; when we were provided with the interface,
2072 // produce the @implementation as the definition.
2073 if (WasReference) {
2074 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
2075 return C;
2076 } else if (ObjCImplementationDecl *Impl
2077 = cast<ObjCInterfaceDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002078 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002079 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002080
Douglas Gregorb6998662010-01-19 19:34:47 +00002081 case Decl::ObjCProperty:
2082 // FIXME: We don't really know where to find the
2083 // ObjCPropertyImplDecls that implement this property.
2084 return clang_getNullCursor();
2085
2086 case Decl::ObjCCompatibleAlias:
2087 if (ObjCInterfaceDecl *Class
2088 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
2089 if (!Class->isForwardDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002090 return MakeCXCursor(Class, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002091
Douglas Gregorb6998662010-01-19 19:34:47 +00002092 return clang_getNullCursor();
2093
2094 case Decl::ObjCForwardProtocol: {
2095 ObjCForwardProtocolDecl *Forward = cast<ObjCForwardProtocolDecl>(D);
2096 if (Forward->protocol_size() == 1)
2097 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002098 MakeCXCursor(*Forward->protocol_begin(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002099 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002100
2101 // FIXME: Cannot return multiple definitions.
2102 return clang_getNullCursor();
2103 }
2104
2105 case Decl::ObjCClass: {
2106 ObjCClassDecl *Class = cast<ObjCClassDecl>(D);
2107 if (Class->size() == 1) {
2108 ObjCInterfaceDecl *IFace = Class->begin()->getInterface();
2109 if (!IFace->isForwardDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002110 return MakeCXCursor(IFace, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002111 return clang_getNullCursor();
2112 }
2113
2114 // FIXME: Cannot return multiple definitions.
2115 return clang_getNullCursor();
2116 }
2117
2118 case Decl::Friend:
2119 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002120 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002121 return clang_getNullCursor();
2122
2123 case Decl::FriendTemplate:
2124 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002125 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002126 return clang_getNullCursor();
2127 }
2128
2129 return clang_getNullCursor();
2130}
2131
2132unsigned clang_isCursorDefinition(CXCursor C) {
2133 if (!clang_isDeclaration(C.kind))
2134 return 0;
2135
2136 return clang_getCursorDefinition(C) == C;
2137}
2138
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002139void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00002140 const char **startBuf,
2141 const char **endBuf,
2142 unsigned *startLine,
2143 unsigned *startColumn,
2144 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002145 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00002146 assert(getCursorDecl(C) && "CXCursor has null decl");
2147 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00002148 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
2149 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002150
Steve Naroff4ade6d62009-09-23 17:52:52 +00002151 SourceManager &SM = FD->getASTContext().getSourceManager();
2152 *startBuf = SM.getCharacterData(Body->getLBracLoc());
2153 *endBuf = SM.getCharacterData(Body->getRBracLoc());
2154 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
2155 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
2156 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
2157 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
2158}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002159
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002160void clang_enableStackTraces(void) {
2161 llvm::sys::PrintStackTraceOnErrorSignal();
2162}
2163
Ted Kremenekfb480492010-01-13 21:46:36 +00002164} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00002165
Ted Kremenekfb480492010-01-13 21:46:36 +00002166//===----------------------------------------------------------------------===//
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002167// Token-based Operations.
2168//===----------------------------------------------------------------------===//
2169
2170/* CXToken layout:
2171 * int_data[0]: a CXTokenKind
2172 * int_data[1]: starting token location
2173 * int_data[2]: token length
2174 * int_data[3]: reserved
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002175 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002176 * otherwise unused.
2177 */
2178extern "C" {
2179
2180CXTokenKind clang_getTokenKind(CXToken CXTok) {
2181 return static_cast<CXTokenKind>(CXTok.int_data[0]);
2182}
2183
2184CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
2185 switch (clang_getTokenKind(CXTok)) {
2186 case CXToken_Identifier:
2187 case CXToken_Keyword:
2188 // We know we have an IdentifierInfo*, so use that.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002189 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
2190 ->getNameStart());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002191
2192 case CXToken_Literal: {
2193 // We have stashed the starting pointer in the ptr_data field. Use it.
2194 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002195 return createCXString(llvm::StringRef(Text, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002196 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002197
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002198 case CXToken_Punctuation:
2199 case CXToken_Comment:
2200 break;
2201 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002202
2203 // We have to find the starting buffer pointer the hard way, by
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002204 // deconstructing the source location.
2205 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2206 if (!CXXUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002207 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002208
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002209 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
2210 std::pair<FileID, unsigned> LocInfo
2211 = CXXUnit->getSourceManager().getDecomposedLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +00002212 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002213 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00002214 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
2215 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00002216 return createCXString("");
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002217
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002218 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002219}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002220
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002221CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
2222 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2223 if (!CXXUnit)
2224 return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002225
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002226 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
2227 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
2228}
2229
2230CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
2231 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregor5352ac02010-01-28 00:27:43 +00002232 if (!CXXUnit)
2233 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002234
2235 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002236 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
2237}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002238
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002239void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
2240 CXToken **Tokens, unsigned *NumTokens) {
2241 if (Tokens)
2242 *Tokens = 0;
2243 if (NumTokens)
2244 *NumTokens = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002245
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002246 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2247 if (!CXXUnit || !Tokens || !NumTokens)
2248 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002249
Douglas Gregorbdf60622010-03-05 21:16:25 +00002250 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
2251
Daniel Dunbar85b988f2010-02-14 08:31:57 +00002252 SourceRange R = cxloc::translateCXSourceRange(Range);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002253 if (R.isInvalid())
2254 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002255
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002256 SourceManager &SourceMgr = CXXUnit->getSourceManager();
2257 std::pair<FileID, unsigned> BeginLocInfo
2258 = SourceMgr.getDecomposedLoc(R.getBegin());
2259 std::pair<FileID, unsigned> EndLocInfo
2260 = SourceMgr.getDecomposedLoc(R.getEnd());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002261
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002262 // Cannot tokenize across files.
2263 if (BeginLocInfo.first != EndLocInfo.first)
2264 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002265
2266 // Create a lexer
Douglas Gregorf715ca12010-03-16 00:06:06 +00002267 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002268 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00002269 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
Douglas Gregor47a3fcd2010-03-16 20:26:15 +00002270 if (Invalid)
2271 return;
Douglas Gregoraea67db2010-03-15 22:54:52 +00002272
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002273 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
2274 CXXUnit->getASTContext().getLangOptions(),
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002275 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002276 Lex.SetCommentRetentionState(true);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002277
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002278 // Lex tokens until we hit the end of the range.
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002279 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002280 llvm::SmallVector<CXToken, 32> CXTokens;
2281 Token Tok;
2282 do {
2283 // Lex the next token
2284 Lex.LexFromRawLexer(Tok);
2285 if (Tok.is(tok::eof))
2286 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002287
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002288 // Initialize the CXToken.
2289 CXToken CXTok;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002290
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002291 // - Common fields
2292 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
2293 CXTok.int_data[2] = Tok.getLength();
2294 CXTok.int_data[3] = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002295
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002296 // - Kind-specific fields
2297 if (Tok.isLiteral()) {
2298 CXTok.int_data[0] = CXToken_Literal;
2299 CXTok.ptr_data = (void *)Tok.getLiteralData();
2300 } else if (Tok.is(tok::identifier)) {
Douglas Gregoraea67db2010-03-15 22:54:52 +00002301 // Lookup the identifier to determine whether we have a keyword.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002302 std::pair<FileID, unsigned> LocInfo
2303 = SourceMgr.getDecomposedLoc(Tok.getLocation());
Douglas Gregorf715ca12010-03-16 00:06:06 +00002304 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002305 llvm::StringRef Buf
Douglas Gregorf715ca12010-03-16 00:06:06 +00002306 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
2307 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00002308 return;
2309
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002310 const char *StartPos = Buf.data() + LocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002311 IdentifierInfo *II
2312 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok, StartPos);
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00002313
2314 if (II->getObjCKeywordID() != tok::objc_not_keyword) {
2315 CXTok.int_data[0] = CXToken_Keyword;
2316 }
2317 else {
2318 CXTok.int_data[0] = II->getTokenID() == tok::identifier?
2319 CXToken_Identifier
2320 : CXToken_Keyword;
2321 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002322 CXTok.ptr_data = II;
2323 } else if (Tok.is(tok::comment)) {
2324 CXTok.int_data[0] = CXToken_Comment;
2325 CXTok.ptr_data = 0;
2326 } else {
2327 CXTok.int_data[0] = CXToken_Punctuation;
2328 CXTok.ptr_data = 0;
2329 }
2330 CXTokens.push_back(CXTok);
2331 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002332
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002333 if (CXTokens.empty())
2334 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002335
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002336 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
2337 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
2338 *NumTokens = CXTokens.size();
2339}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002340
Ted Kremenek6db61092010-05-05 00:55:15 +00002341void clang_disposeTokens(CXTranslationUnit TU,
2342 CXToken *Tokens, unsigned NumTokens) {
2343 free(Tokens);
2344}
2345
2346} // end: extern "C"
2347
2348//===----------------------------------------------------------------------===//
2349// Token annotation APIs.
2350//===----------------------------------------------------------------------===//
2351
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002352typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002353static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
2354 CXCursor parent,
2355 CXClientData client_data);
Ted Kremenek6db61092010-05-05 00:55:15 +00002356namespace {
2357class AnnotateTokensWorker {
2358 AnnotateTokensData &Annotated;
Ted Kremenek11949cb2010-05-05 00:55:17 +00002359 CXToken *Tokens;
2360 CXCursor *Cursors;
2361 unsigned NumTokens;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002362 unsigned TokIdx;
2363 CursorVisitor AnnotateVis;
2364 SourceManager &SrcMgr;
2365
2366 bool MoreTokens() const { return TokIdx < NumTokens; }
2367 unsigned NextToken() const { return TokIdx; }
2368 void AdvanceToken() { ++TokIdx; }
2369 SourceLocation GetTokenLoc(unsigned tokI) {
2370 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
2371 }
2372
Ted Kremenek6db61092010-05-05 00:55:15 +00002373public:
Ted Kremenek11949cb2010-05-05 00:55:17 +00002374 AnnotateTokensWorker(AnnotateTokensData &annotated,
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002375 CXToken *tokens, CXCursor *cursors, unsigned numTokens,
2376 ASTUnit *CXXUnit, SourceRange RegionOfInterest)
Ted Kremenek11949cb2010-05-05 00:55:17 +00002377 : Annotated(annotated), Tokens(tokens), Cursors(cursors),
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002378 NumTokens(numTokens), TokIdx(0),
2379 AnnotateVis(CXXUnit, AnnotateTokensVisitor, this,
2380 Decl::MaxPCHLevel, RegionOfInterest),
2381 SrcMgr(CXXUnit->getSourceManager()) {}
Ted Kremenek11949cb2010-05-05 00:55:17 +00002382
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002383 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
Ted Kremenek6db61092010-05-05 00:55:15 +00002384 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002385 void AnnotateTokens(CXCursor parent);
Ted Kremenek6db61092010-05-05 00:55:15 +00002386};
2387}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002388
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002389void AnnotateTokensWorker::AnnotateTokens(CXCursor parent) {
2390 // Walk the AST within the region of interest, annotating tokens
2391 // along the way.
2392 VisitChildren(parent);
Ted Kremenek11949cb2010-05-05 00:55:17 +00002393
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002394 for (unsigned I = 0 ; I < TokIdx ; ++I) {
2395 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
2396 if (Pos != Annotated.end())
2397 Cursors[I] = Pos->second;
2398 }
2399
2400 // Finish up annotating any tokens left.
2401 if (!MoreTokens())
2402 return;
2403
2404 const CXCursor &C = clang_getNullCursor();
2405 for (unsigned I = TokIdx ; I < NumTokens ; ++I) {
2406 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
2407 Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second;
Ted Kremenek11949cb2010-05-05 00:55:17 +00002408 }
2409}
2410
Ted Kremenek6db61092010-05-05 00:55:15 +00002411enum CXChildVisitResult
2412AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002413 CXSourceLocation Loc = clang_getCursorLocation(cursor);
2414 // We can always annotate a preprocessing directive/macro instantiation.
2415 if (clang_isPreprocessing(cursor.kind)) {
2416 Annotated[Loc.int_data] = cursor;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002417 return CXChildVisit_Recurse;
2418 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002419
2420 CXSourceRange cursorExtent = clang_getCursorExtent(cursor);
2421 SourceRange cursorRange = cxloc::translateCXSourceRange(cursorExtent);
2422
2423 if (cursorRange.isInvalid())
2424 return CXChildVisit_Continue;
2425
2426 SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data);
2427
2428 const enum CXCursorKind K = clang_getCursorKind(parent);
2429 const CXCursor updateC =
2430 (clang_isInvalid(K) || K == CXCursor_TranslationUnit ||
2431 L.isMacroID())
2432 ? clang_getNullCursor() : parent;
2433
2434 while (MoreTokens()) {
2435 const unsigned I = NextToken();
2436 SourceLocation TokLoc = GetTokenLoc(I);
2437 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
2438 case RangeBefore:
2439 Cursors[I] = updateC;
2440 AdvanceToken();
2441 continue;
2442 case RangeAfter:
2443 return CXChildVisit_Continue;
2444 case RangeOverlap:
2445 break;
2446 }
2447 break;
2448 }
2449
2450 // Visit children to get their cursor information.
2451 const unsigned BeforeChildren = NextToken();
2452 VisitChildren(cursor);
2453 const unsigned AfterChildren = NextToken();
2454
2455 // Adjust 'Last' to the last token within the extent of the cursor.
2456 while (MoreTokens()) {
2457 const unsigned I = NextToken();
2458 SourceLocation TokLoc = GetTokenLoc(I);
2459 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
2460 case RangeBefore:
2461 assert(0 && "Infeasible");
2462 case RangeAfter:
2463 break;
2464 case RangeOverlap:
2465 Cursors[I] = updateC;
2466 AdvanceToken();
2467 continue;
2468 }
2469 break;
2470 }
2471 const unsigned Last = NextToken();
Ted Kremenek6db61092010-05-05 00:55:15 +00002472
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002473 // Scan the tokens that are at the beginning of the cursor, but are not
2474 // capture by the child cursors.
2475
2476 // For AST elements within macros, rely on a post-annotate pass to
2477 // to correctly annotate the tokens with cursors. Otherwise we can
2478 // get confusing results of having tokens that map to cursors that really
2479 // are expanded by an instantiation.
2480 if (L.isMacroID())
2481 cursor = clang_getNullCursor();
2482
2483 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
2484 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
2485 break;
2486 Cursors[I] = cursor;
2487 }
2488 // Scan the tokens that are at the end of the cursor, but are not captured
2489 // but the child cursors.
2490 for (unsigned I = AfterChildren; I != Last; ++I)
2491 Cursors[I] = cursor;
2492
2493 TokIdx = Last;
2494 return CXChildVisit_Continue;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002495}
2496
Ted Kremenek6db61092010-05-05 00:55:15 +00002497static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
2498 CXCursor parent,
2499 CXClientData client_data) {
2500 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
2501}
2502
2503extern "C" {
2504
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002505void clang_annotateTokens(CXTranslationUnit TU,
2506 CXToken *Tokens, unsigned NumTokens,
2507 CXCursor *Cursors) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002508
2509 if (NumTokens == 0 || !Tokens || !Cursors)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002510 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002511
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002512 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002513 if (!CXXUnit) {
2514 // Any token we don't specifically annotate will have a NULL cursor.
2515 const CXCursor &C = clang_getNullCursor();
2516 for (unsigned I = 0; I != NumTokens; ++I)
2517 Cursors[I] = C;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002518 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002519 }
2520
Douglas Gregorbdf60622010-03-05 21:16:25 +00002521 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002522
Douglas Gregor0396f462010-03-19 05:22:59 +00002523 // Determine the region of interest, which contains all of the tokens.
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002524 SourceRange RegionOfInterest;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002525 RegionOfInterest.setBegin(cxloc::translateSourceLocation(
2526 clang_getTokenLocation(TU, Tokens[0])));
2527
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002528 SourceLocation End
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002529 = cxloc::translateSourceLocation(clang_getTokenLocation(TU,
2530 Tokens[NumTokens - 1]));
Daniel Dunbard52864b2010-02-14 10:02:57 +00002531 RegionOfInterest.setEnd(CXXUnit->getPreprocessor().getLocForEndOfToken(End));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002532
Douglas Gregor0396f462010-03-19 05:22:59 +00002533 // A mapping from the source locations found when re-lexing or traversing the
2534 // region of interest to the corresponding cursors.
2535 AnnotateTokensData Annotated;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002536
2537 // Relex the tokens within the source range to look for preprocessing
Douglas Gregor0396f462010-03-19 05:22:59 +00002538 // directives.
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002539 SourceManager &SourceMgr = CXXUnit->getSourceManager();
2540 std::pair<FileID, unsigned> BeginLocInfo
2541 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
2542 std::pair<FileID, unsigned> EndLocInfo
2543 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002544
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002545 llvm::StringRef Buffer;
Douglas Gregor0396f462010-03-19 05:22:59 +00002546 bool Invalid = false;
2547 if (BeginLocInfo.first == EndLocInfo.first &&
2548 ((Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid)),true) &&
2549 !Invalid) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002550 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
2551 CXXUnit->getASTContext().getLangOptions(),
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002552 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002553 Buffer.end());
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002554 Lex.SetCommentRetentionState(true);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002555
2556 // Lex tokens in raw mode until we hit the end of the range, to avoid
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002557 // entering #includes or expanding macros.
Douglas Gregor48072312010-03-18 15:23:44 +00002558 while (true) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002559 Token Tok;
2560 Lex.LexFromRawLexer(Tok);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002561
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002562 reprocess:
2563 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
2564 // We have found a preprocessing directive. Gobble it up so that we
2565 // don't see it while preprocessing these tokens later, but keep track of
2566 // all of the token locations inside this preprocessing directive so that
2567 // we can annotate them appropriately.
2568 //
2569 // FIXME: Some simple tests here could identify macro definitions and
2570 // #undefs, to provide specific cursor kinds for those.
2571 std::vector<SourceLocation> Locations;
2572 do {
2573 Locations.push_back(Tok.getLocation());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002574 Lex.LexFromRawLexer(Tok);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002575 } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002576
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002577 using namespace cxcursor;
2578 CXCursor Cursor
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002579 = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
2580 Locations.back()),
Ted Kremenek6db61092010-05-05 00:55:15 +00002581 CXXUnit);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002582 for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
2583 Annotated[Locations[I].getRawEncoding()] = Cursor;
2584 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002585
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002586 if (Tok.isAtStartOfLine())
2587 goto reprocess;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002588
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002589 continue;
2590 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002591
Douglas Gregor48072312010-03-18 15:23:44 +00002592 if (Tok.is(tok::eof))
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002593 break;
2594 }
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002595 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002596
Douglas Gregor0396f462010-03-19 05:22:59 +00002597 // Annotate all of the source locations in the region of interest that map to
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002598 // a specific cursor.
2599 AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens,
2600 CXXUnit, RegionOfInterest);
2601 W.AnnotateTokens(clang_getTranslationUnitCursor(CXXUnit));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002602}
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002603} // end: extern "C"
2604
2605//===----------------------------------------------------------------------===//
Ted Kremenek16b42592010-03-03 06:36:57 +00002606// Operations for querying linkage of a cursor.
2607//===----------------------------------------------------------------------===//
2608
2609extern "C" {
2610CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
Douglas Gregor0396f462010-03-19 05:22:59 +00002611 if (!clang_isDeclaration(cursor.kind))
2612 return CXLinkage_Invalid;
2613
Ted Kremenek16b42592010-03-03 06:36:57 +00002614 Decl *D = cxcursor::getCursorDecl(cursor);
2615 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
2616 switch (ND->getLinkage()) {
2617 case NoLinkage: return CXLinkage_NoLinkage;
2618 case InternalLinkage: return CXLinkage_Internal;
2619 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
2620 case ExternalLinkage: return CXLinkage_External;
2621 };
2622
2623 return CXLinkage_Invalid;
2624}
2625} // end: extern "C"
2626
2627//===----------------------------------------------------------------------===//
Ted Kremenek45e1dae2010-04-12 21:22:16 +00002628// Operations for querying language of a cursor.
2629//===----------------------------------------------------------------------===//
2630
2631static CXLanguageKind getDeclLanguage(const Decl *D) {
2632 switch (D->getKind()) {
2633 default:
2634 break;
2635 case Decl::ImplicitParam:
2636 case Decl::ObjCAtDefsField:
2637 case Decl::ObjCCategory:
2638 case Decl::ObjCCategoryImpl:
2639 case Decl::ObjCClass:
2640 case Decl::ObjCCompatibleAlias:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00002641 case Decl::ObjCForwardProtocol:
2642 case Decl::ObjCImplementation:
2643 case Decl::ObjCInterface:
2644 case Decl::ObjCIvar:
2645 case Decl::ObjCMethod:
2646 case Decl::ObjCProperty:
2647 case Decl::ObjCPropertyImpl:
2648 case Decl::ObjCProtocol:
2649 return CXLanguage_ObjC;
2650 case Decl::CXXConstructor:
2651 case Decl::CXXConversion:
2652 case Decl::CXXDestructor:
2653 case Decl::CXXMethod:
2654 case Decl::CXXRecord:
2655 case Decl::ClassTemplate:
2656 case Decl::ClassTemplatePartialSpecialization:
2657 case Decl::ClassTemplateSpecialization:
2658 case Decl::Friend:
2659 case Decl::FriendTemplate:
2660 case Decl::FunctionTemplate:
2661 case Decl::LinkageSpec:
2662 case Decl::Namespace:
2663 case Decl::NamespaceAlias:
2664 case Decl::NonTypeTemplateParm:
2665 case Decl::StaticAssert:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00002666 case Decl::TemplateTemplateParm:
2667 case Decl::TemplateTypeParm:
2668 case Decl::UnresolvedUsingTypename:
2669 case Decl::UnresolvedUsingValue:
2670 case Decl::Using:
2671 case Decl::UsingDirective:
2672 case Decl::UsingShadow:
2673 return CXLanguage_CPlusPlus;
2674 }
2675
2676 return CXLanguage_C;
2677}
2678
2679extern "C" {
2680CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
2681 if (clang_isDeclaration(cursor.kind))
2682 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
2683
2684 return CXLanguage_Invalid;
2685}
2686} // end: extern "C"
2687
2688//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00002689// CXString Operations.
2690//===----------------------------------------------------------------------===//
2691
2692extern "C" {
2693const char *clang_getCString(CXString string) {
2694 return string.Spelling;
2695}
2696
2697void clang_disposeString(CXString string) {
2698 if (string.MustFreeString && string.Spelling)
2699 free((void*)string.Spelling);
2700}
Ted Kremenek04bb7162010-01-22 22:44:15 +00002701
Ted Kremenekfb480492010-01-13 21:46:36 +00002702} // end: extern "C"
Ted Kremenek04bb7162010-01-22 22:44:15 +00002703
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002704namespace clang { namespace cxstring {
2705CXString createCXString(const char *String, bool DupString){
2706 CXString Str;
2707 if (DupString) {
2708 Str.Spelling = strdup(String);
2709 Str.MustFreeString = 1;
2710 } else {
2711 Str.Spelling = String;
2712 Str.MustFreeString = 0;
2713 }
2714 return Str;
2715}
2716
2717CXString createCXString(llvm::StringRef String, bool DupString) {
2718 CXString Result;
2719 if (DupString || (!String.empty() && String.data()[String.size()] != 0)) {
2720 char *Spelling = (char *)malloc(String.size() + 1);
2721 memmove(Spelling, String.data(), String.size());
2722 Spelling[String.size()] = 0;
2723 Result.Spelling = Spelling;
2724 Result.MustFreeString = 1;
2725 } else {
2726 Result.Spelling = String.data();
2727 Result.MustFreeString = 0;
2728 }
2729 return Result;
2730}
2731}}
2732
Ted Kremenek04bb7162010-01-22 22:44:15 +00002733//===----------------------------------------------------------------------===//
2734// Misc. utility functions.
2735//===----------------------------------------------------------------------===//
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002736
Ted Kremenek04bb7162010-01-22 22:44:15 +00002737extern "C" {
2738
Ted Kremeneka2a9d6e2010-02-12 22:54:40 +00002739CXString clang_getClangVersion() {
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002740 return createCXString(getClangFullVersion());
Ted Kremenek04bb7162010-01-22 22:44:15 +00002741}
2742
2743} // end: extern "C"