blob: d7b6f39bbe56752a0ba3911b475050fefc9ab864 [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
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000155/// \brief Translate a Clang source range into a CIndex source range.
156///
157/// Clang internally represents ranges where the end location points to the
158/// start of the token at the end. However, for external clients it is more
159/// useful to have a CXSourceRange be a proper half-open interval. This routine
160/// does the appropriate translation.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000161CXSourceRange cxloc::translateSourceRange(const SourceManager &SM,
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000162 const LangOptions &LangOpts,
163 SourceRange R) {
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000164 // We want the last character in this location, so we will adjust the
Douglas Gregor6a5a23f2010-03-19 21:51:54 +0000165 // location accordingly.
166 // FIXME: How do do this with a macro instantiation location?
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000167 SourceLocation EndLoc = R.getEnd();
Douglas Gregor6a5a23f2010-03-19 21:51:54 +0000168 if (!EndLoc.isInvalid() && EndLoc.isFileID()) {
169 unsigned Length = Lexer::MeasureTokenLength(EndLoc, SM, LangOpts);
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000170 EndLoc = EndLoc.getFileLocWithOffset(Length);
171 }
172
173 CXSourceRange Result = { { (void *)&SM, (void *)&LangOpts },
174 R.getBegin().getRawEncoding(),
175 EndLoc.getRawEncoding() };
176 return Result;
177}
Douglas Gregor1db19de2010-01-19 21:36:55 +0000178
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000179//===----------------------------------------------------------------------===//
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000180// Cursor visitor.
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000181//===----------------------------------------------------------------------===//
182
Steve Naroff89922f82009-08-31 00:59:03 +0000183namespace {
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000184
Douglas Gregorb1373d02010-01-20 20:59:29 +0000185// Cursor visitor.
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000186class CursorVisitor : public DeclVisitor<CursorVisitor, bool>,
Douglas Gregora59e3902010-01-21 23:27:09 +0000187 public TypeLocVisitor<CursorVisitor, bool>,
188 public StmtVisitor<CursorVisitor, bool>
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000189{
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000190 /// \brief The translation unit we are traversing.
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000191 ASTUnit *TU;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000192
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000193 /// \brief The parent cursor whose children we are traversing.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000194 CXCursor Parent;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000195
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000196 /// \brief The declaration that serves at the parent of any statement or
197 /// expression nodes.
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000198 Decl *StmtParent;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000199
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000200 /// \brief The visitor function.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000201 CXCursorVisitor Visitor;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000202
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000203 /// \brief The opaque client data, to be passed along to the visitor.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000204 CXClientData ClientData;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000205
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000206 // MaxPCHLevel - the maximum PCH level of declarations that we will pass on
207 // to the visitor. Declarations with a PCH level greater than this value will
208 // be suppressed.
209 unsigned MaxPCHLevel;
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000210
211 /// \brief When valid, a source range to which the cursor should restrict
212 /// its search.
213 SourceRange RegionOfInterest;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000214
Douglas Gregorb1373d02010-01-20 20:59:29 +0000215 using DeclVisitor<CursorVisitor, bool>::Visit;
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000216 using TypeLocVisitor<CursorVisitor, bool>::Visit;
Douglas Gregora59e3902010-01-21 23:27:09 +0000217 using StmtVisitor<CursorVisitor, bool>::Visit;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000218
219 /// \brief Determine whether this particular source range comes before, comes
220 /// after, or overlaps the region of interest.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000221 ///
Daniel Dunbard52864b2010-02-14 10:02:57 +0000222 /// \param R a half-open source range retrieved from the abstract syntax tree.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000223 RangeComparisonResult CompareRegionOfInterest(SourceRange R);
224
Steve Naroff89922f82009-08-31 00:59:03 +0000225public:
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000226 CursorVisitor(ASTUnit *TU, CXCursorVisitor Visitor, CXClientData ClientData,
227 unsigned MaxPCHLevel,
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000228 SourceRange RegionOfInterest = SourceRange())
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000229 : TU(TU), Visitor(Visitor), ClientData(ClientData),
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000230 MaxPCHLevel(MaxPCHLevel), RegionOfInterest(RegionOfInterest)
Douglas Gregorb1373d02010-01-20 20:59:29 +0000231 {
232 Parent.kind = CXCursor_NoDeclFound;
233 Parent.data[0] = 0;
234 Parent.data[1] = 0;
235 Parent.data[2] = 0;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000236 StmtParent = 0;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000237 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000238
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000239 bool Visit(CXCursor Cursor, bool CheckedRegionOfInterest = false);
Douglas Gregor788f5a12010-03-20 00:41:21 +0000240
241 std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
242 getPreprocessedEntities();
243
Douglas Gregorb1373d02010-01-20 20:59:29 +0000244 bool VisitChildren(CXCursor Parent);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000245
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000246 // Declaration visitors
Ted Kremenek09dfa372010-02-18 05:46:33 +0000247 bool VisitAttributes(Decl *D);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000248 bool VisitBlockDecl(BlockDecl *B);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000249 bool VisitDeclContext(DeclContext *DC);
Ted Kremenek4540c9c2010-02-18 18:47:08 +0000250 bool VisitTranslationUnitDecl(TranslationUnitDecl *D);
251 bool VisitTypedefDecl(TypedefDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000252 bool VisitTagDecl(TagDecl *D);
253 bool VisitEnumConstantDecl(EnumConstantDecl *D);
254 bool VisitDeclaratorDecl(DeclaratorDecl *DD);
255 bool VisitFunctionDecl(FunctionDecl *ND);
256 bool VisitFieldDecl(FieldDecl *D);
Ted Kremenek4540c9c2010-02-18 18:47:08 +0000257 bool VisitVarDecl(VarDecl *);
Ted Kremenek79758f62010-02-18 22:36:18 +0000258 bool VisitObjCMethodDecl(ObjCMethodDecl *ND);
259 bool VisitObjCContainerDecl(ObjCContainerDecl *D);
260 bool VisitObjCCategoryDecl(ObjCCategoryDecl *ND);
261 bool VisitObjCProtocolDecl(ObjCProtocolDecl *PID);
262 bool VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
263 bool VisitObjCImplDecl(ObjCImplDecl *D);
264 bool VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
265 bool VisitObjCImplementationDecl(ObjCImplementationDecl *D);
266 // FIXME: ObjCPropertyDecl requires TypeSourceInfo, getter/setter locations,
267 // etc.
268 // FIXME: ObjCCompatibleAliasDecl requires aliased-class locations.
269 bool VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D);
270 bool VisitObjCClassDecl(ObjCClassDecl *D);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000271
272 // Type visitors
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000273 // FIXME: QualifiedTypeLoc doesn't provide any location information
274 bool VisitBuiltinTypeLoc(BuiltinTypeLoc TL);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000275 bool VisitTypedefTypeLoc(TypedefTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000276 bool VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL);
277 bool VisitTagTypeLoc(TagTypeLoc TL);
278 // FIXME: TemplateTypeParmTypeLoc doesn't provide any location information
279 bool VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL);
280 bool VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL);
281 bool VisitPointerTypeLoc(PointerTypeLoc TL);
282 bool VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL);
283 bool VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL);
284 bool VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL);
285 bool VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL);
286 bool VisitFunctionTypeLoc(FunctionTypeLoc TL);
287 bool VisitArrayTypeLoc(ArrayTypeLoc TL);
Douglas Gregor2332c112010-01-21 20:48:56 +0000288 // FIXME: Implement for TemplateSpecializationTypeLoc
289 // FIXME: Implement visitors here when the unimplemented TypeLocs get
290 // implemented
291 bool VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL);
292 bool VisitTypeOfTypeLoc(TypeOfTypeLoc TL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000293
Douglas Gregora59e3902010-01-21 23:27:09 +0000294 // Statement visitors
295 bool VisitStmt(Stmt *S);
296 bool VisitDeclStmt(DeclStmt *S);
Douglas Gregorf5bab412010-01-22 01:00:11 +0000297 // FIXME: LabelStmt label?
298 bool VisitIfStmt(IfStmt *S);
299 bool VisitSwitchStmt(SwitchStmt *S);
Douglas Gregor263b47b2010-01-25 16:12:32 +0000300 bool VisitWhileStmt(WhileStmt *S);
301 bool VisitForStmt(ForStmt *S);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000302
Douglas Gregor336fd812010-01-23 00:40:08 +0000303 // Expression visitors
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000304 bool VisitBlockExpr(BlockExpr *B);
Douglas Gregor336fd812010-01-23 00:40:08 +0000305 bool VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000306 bool VisitExplicitCastExpr(ExplicitCastExpr *E);
Douglas Gregorc2350e52010-03-08 16:40:19 +0000307 bool VisitObjCMessageExpr(ObjCMessageExpr *E);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000308 bool VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E);
Steve Naroff89922f82009-08-31 00:59:03 +0000309};
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000310
Ted Kremenekab188932010-01-05 19:32:54 +0000311} // end anonymous namespace
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000312
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000313RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000314 return RangeCompare(TU->getSourceManager(), R, RegionOfInterest);
315}
316
Douglas Gregorb1373d02010-01-20 20:59:29 +0000317/// \brief Visit the given cursor and, if requested by the visitor,
318/// its children.
319///
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000320/// \param Cursor the cursor to visit.
321///
322/// \param CheckRegionOfInterest if true, then the caller already checked that
323/// this cursor is within the region of interest.
324///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000325/// \returns true if the visitation should be aborted, false if it
326/// should continue.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000327bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
Douglas Gregorb1373d02010-01-20 20:59:29 +0000328 if (clang_isInvalid(Cursor.kind))
329 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000330
Douglas Gregorb1373d02010-01-20 20:59:29 +0000331 if (clang_isDeclaration(Cursor.kind)) {
332 Decl *D = getCursorDecl(Cursor);
333 assert(D && "Invalid declaration cursor");
334 if (D->getPCHLevel() > MaxPCHLevel)
335 return false;
336
337 if (D->isImplicit())
338 return false;
339 }
340
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000341 // If we have a range of interest, and this cursor doesn't intersect with it,
342 // we're done.
343 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
Daniel Dunbarf408f322010-02-14 08:32:05 +0000344 SourceRange Range =
345 cxloc::translateCXSourceRange(clang_getCursorExtent(Cursor));
346 if (Range.isInvalid() || CompareRegionOfInterest(Range))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000347 return false;
348 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000349
Douglas Gregorb1373d02010-01-20 20:59:29 +0000350 switch (Visitor(Cursor, Parent, ClientData)) {
351 case CXChildVisit_Break:
352 return true;
353
354 case CXChildVisit_Continue:
355 return false;
356
357 case CXChildVisit_Recurse:
358 return VisitChildren(Cursor);
359 }
360
Douglas Gregorfd643772010-01-25 16:45:46 +0000361 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000362}
363
Douglas Gregor788f5a12010-03-20 00:41:21 +0000364std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
365CursorVisitor::getPreprocessedEntities() {
366 PreprocessingRecord &PPRec
367 = *TU->getPreprocessor().getPreprocessingRecord();
368
369 bool OnlyLocalDecls
370 = !TU->isMainFileAST() && TU->getOnlyLocalDecls();
371
372 // There is no region of interest; we have to walk everything.
373 if (RegionOfInterest.isInvalid())
374 return std::make_pair(PPRec.begin(OnlyLocalDecls),
375 PPRec.end(OnlyLocalDecls));
376
377 // Find the file in which the region of interest lands.
378 SourceManager &SM = TU->getSourceManager();
379 std::pair<FileID, unsigned> Begin
380 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getBegin());
381 std::pair<FileID, unsigned> End
382 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getEnd());
383
384 // The region of interest spans files; we have to walk everything.
385 if (Begin.first != End.first)
386 return std::make_pair(PPRec.begin(OnlyLocalDecls),
387 PPRec.end(OnlyLocalDecls));
388
389 ASTUnit::PreprocessedEntitiesByFileMap &ByFileMap
390 = TU->getPreprocessedEntitiesByFile();
391 if (ByFileMap.empty()) {
392 // Build the mapping from files to sets of preprocessed entities.
393 for (PreprocessingRecord::iterator E = PPRec.begin(OnlyLocalDecls),
394 EEnd = PPRec.end(OnlyLocalDecls);
395 E != EEnd; ++E) {
396 std::pair<FileID, unsigned> P
397 = SM.getDecomposedInstantiationLoc((*E)->getSourceRange().getBegin());
398 ByFileMap[P.first].push_back(*E);
399 }
400 }
401
402 return std::make_pair(ByFileMap[Begin.first].begin(),
403 ByFileMap[Begin.first].end());
404}
405
Douglas Gregorb1373d02010-01-20 20:59:29 +0000406/// \brief Visit the children of the given cursor.
407///
408/// \returns true if the visitation should be aborted, false if it
409/// should continue.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000410bool CursorVisitor::VisitChildren(CXCursor Cursor) {
Douglas Gregora59e3902010-01-21 23:27:09 +0000411 if (clang_isReference(Cursor.kind)) {
412 // By definition, references have no children.
413 return false;
414 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000415
416 // Set the Parent field to Cursor, then back to its old value once we're
Douglas Gregorb1373d02010-01-20 20:59:29 +0000417 // done.
418 class SetParentRAII {
419 CXCursor &Parent;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000420 Decl *&StmtParent;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000421 CXCursor OldParent;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000422
Douglas Gregorb1373d02010-01-20 20:59:29 +0000423 public:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000424 SetParentRAII(CXCursor &Parent, Decl *&StmtParent, CXCursor NewParent)
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000425 : Parent(Parent), StmtParent(StmtParent), OldParent(Parent)
Douglas Gregorb1373d02010-01-20 20:59:29 +0000426 {
427 Parent = NewParent;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000428 if (clang_isDeclaration(Parent.kind))
429 StmtParent = getCursorDecl(Parent);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000430 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000431
Douglas Gregorb1373d02010-01-20 20:59:29 +0000432 ~SetParentRAII() {
433 Parent = OldParent;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000434 if (clang_isDeclaration(Parent.kind))
435 StmtParent = getCursorDecl(Parent);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000436 }
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000437 } SetParent(Parent, StmtParent, Cursor);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000438
Douglas Gregorb1373d02010-01-20 20:59:29 +0000439 if (clang_isDeclaration(Cursor.kind)) {
440 Decl *D = getCursorDecl(Cursor);
441 assert(D && "Invalid declaration cursor");
Ted Kremenek539311e2010-02-18 18:47:01 +0000442 return VisitAttributes(D) || Visit(D);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000443 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000444
Douglas Gregora59e3902010-01-21 23:27:09 +0000445 if (clang_isStatement(Cursor.kind))
446 return Visit(getCursorStmt(Cursor));
447 if (clang_isExpression(Cursor.kind))
448 return Visit(getCursorExpr(Cursor));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000449
Douglas Gregorb1373d02010-01-20 20:59:29 +0000450 if (clang_isTranslationUnit(Cursor.kind)) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000451 ASTUnit *CXXUnit = getCursorASTUnit(Cursor);
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000452 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
453 RegionOfInterest.isInvalid()) {
Douglas Gregor7b691f332010-01-20 21:13:59 +0000454 const std::vector<Decl*> &TLDs = CXXUnit->getTopLevelDecls();
455 for (std::vector<Decl*>::const_iterator it = TLDs.begin(),
456 ie = TLDs.end(); it != ie; ++it) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000457 if (Visit(MakeCXCursor(*it, CXXUnit), true))
Douglas Gregor7b691f332010-01-20 21:13:59 +0000458 return true;
459 }
Douglas Gregor0396f462010-03-19 05:22:59 +0000460 } else if (VisitDeclContext(
461 CXXUnit->getASTContext().getTranslationUnitDecl()))
462 return true;
Bob Wilson3178cb62010-03-19 03:57:57 +0000463
Douglas Gregor0396f462010-03-19 05:22:59 +0000464 // Walk the preprocessing record.
Daniel Dunbar8de30ff2010-03-20 01:11:56 +0000465 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000466 // FIXME: Once we have the ability to deserialize a preprocessing record,
467 // do so.
Douglas Gregor788f5a12010-03-20 00:41:21 +0000468 PreprocessingRecord::iterator E, EEnd;
469 for (llvm::tie(E, EEnd) = getPreprocessedEntities(); E != EEnd; ++E) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000470 if (MacroInstantiation *MI = dyn_cast<MacroInstantiation>(*E)) {
471 if (Visit(MakeMacroInstantiationCursor(MI, CXXUnit)))
472 return true;
Douglas Gregor788f5a12010-03-20 00:41:21 +0000473
Douglas Gregor0396f462010-03-19 05:22:59 +0000474 continue;
475 }
476
477 if (MacroDefinition *MD = dyn_cast<MacroDefinition>(*E)) {
478 if (Visit(MakeMacroDefinitionCursor(MD, CXXUnit)))
479 return true;
480
481 continue;
482 }
483 }
484 }
Douglas Gregor7b691f332010-01-20 21:13:59 +0000485 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000486 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000487
Douglas Gregorb1373d02010-01-20 20:59:29 +0000488 // Nothing to visit at the moment.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000489 return false;
490}
491
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000492bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
493 for (BlockDecl::param_iterator I=B->param_begin(), E=B->param_end(); I!=E;++I)
494 if (Decl *D = *I)
495 if (Visit(D))
496 return true;
497
498 return Visit(MakeCXCursor(B->getBody(), StmtParent, TU));
499}
500
Douglas Gregorb1373d02010-01-20 20:59:29 +0000501bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000502 for (DeclContext::decl_iterator
Douglas Gregorb1373d02010-01-20 20:59:29 +0000503 I = DC->decls_begin(), E = DC->decls_end(); I != E; ++I) {
Ted Kremenek09dfa372010-02-18 05:46:33 +0000504
Daniel Dunbard52864b2010-02-14 10:02:57 +0000505 CXCursor Cursor = MakeCXCursor(*I, TU);
506
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000507 if (RegionOfInterest.isValid()) {
Daniel Dunbard52864b2010-02-14 10:02:57 +0000508 SourceRange Range =
509 cxloc::translateCXSourceRange(clang_getCursorExtent(Cursor));
510 if (Range.isInvalid())
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000511 continue;
Daniel Dunbard52864b2010-02-14 10:02:57 +0000512
513 switch (CompareRegionOfInterest(Range)) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000514 case RangeBefore:
515 // This declaration comes before the region of interest; skip it.
516 continue;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000517
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000518 case RangeAfter:
519 // This declaration comes after the region of interest; we're done.
520 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000521
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000522 case RangeOverlap:
523 // This declaration overlaps the region of interest; visit it.
524 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000525 }
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000526 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000527
Daniel Dunbard52864b2010-02-14 10:02:57 +0000528 if (Visit(Cursor, true))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000529 return true;
530 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000531
Douglas Gregorb1373d02010-01-20 20:59:29 +0000532 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000533}
534
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000535bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
536 llvm_unreachable("Translation units are visited directly by Visit()");
537 return false;
538}
539
540bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
541 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
542 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000543
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000544 return false;
545}
546
547bool CursorVisitor::VisitTagDecl(TagDecl *D) {
548 return VisitDeclContext(D);
549}
550
551bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
552 if (Expr *Init = D->getInitExpr())
553 return Visit(MakeCXCursor(Init, StmtParent, TU));
554 return false;
555}
556
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000557bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
558 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
559 if (Visit(TSInfo->getTypeLoc()))
560 return true;
561
562 return false;
563}
564
Douglas Gregorb1373d02010-01-20 20:59:29 +0000565bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000566 if (VisitDeclaratorDecl(ND))
567 return true;
568
Douglas Gregora59e3902010-01-21 23:27:09 +0000569 if (ND->isThisDeclarationADefinition() &&
570 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
571 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000572
Douglas Gregorb1373d02010-01-20 20:59:29 +0000573 return false;
574}
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000575
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000576bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
577 if (VisitDeclaratorDecl(D))
578 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000579
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000580 if (Expr *BitWidth = D->getBitWidth())
581 return Visit(MakeCXCursor(BitWidth, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000582
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000583 return false;
584}
585
586bool CursorVisitor::VisitVarDecl(VarDecl *D) {
587 if (VisitDeclaratorDecl(D))
588 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000589
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000590 if (Expr *Init = D->getInit())
591 return Visit(MakeCXCursor(Init, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000592
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000593 return false;
594}
595
596bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
Douglas Gregor4bc1cb62010-03-08 14:59:44 +0000597 if (TypeSourceInfo *TSInfo = ND->getResultTypeSourceInfo())
598 if (Visit(TSInfo->getTypeLoc()))
599 return true;
600
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000601 for (ObjCMethodDecl::param_iterator P = ND->param_begin(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000602 PEnd = ND->param_end();
603 P != PEnd; ++P) {
604 if (Visit(MakeCXCursor(*P, TU)))
605 return true;
606 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000607
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000608 if (ND->isThisDeclarationADefinition() &&
609 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
610 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000611
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000612 return false;
613}
614
Douglas Gregora59e3902010-01-21 23:27:09 +0000615bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
616 return VisitDeclContext(D);
617}
618
Douglas Gregorb1373d02010-01-20 20:59:29 +0000619bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000620 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
621 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000622 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000623
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000624 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
625 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
626 E = ND->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000627 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000628 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000629
Douglas Gregora59e3902010-01-21 23:27:09 +0000630 return VisitObjCContainerDecl(ND);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000631}
632
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000633bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
634 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
635 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
636 E = PID->protocol_end(); I != E; ++I, ++PL)
637 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
638 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000639
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000640 return VisitObjCContainerDecl(PID);
641}
642
Douglas Gregorb1373d02010-01-20 20:59:29 +0000643bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000644 // Issue callbacks for super class.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000645 if (D->getSuperClass() &&
646 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000647 D->getSuperClassLoc(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000648 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000649 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000650
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000651 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
652 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
653 E = D->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000654 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000655 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000656
Douglas Gregora59e3902010-01-21 23:27:09 +0000657 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000658}
659
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000660bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
661 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000662}
663
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000664bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
Ted Kremenekebfa3392010-03-19 20:39:03 +0000665 // 'ID' could be null when dealing with invalid code.
666 if (ObjCInterfaceDecl *ID = D->getClassInterface())
667 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
668 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000669
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000670 return VisitObjCImplDecl(D);
671}
672
673bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
674#if 0
675 // Issue callbacks for super class.
676 // FIXME: No source location information!
677 if (D->getSuperClass() &&
678 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000679 D->getSuperClassLoc(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000680 TU)))
681 return true;
682#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000683
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000684 return VisitObjCImplDecl(D);
685}
686
687bool CursorVisitor::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D) {
688 ObjCForwardProtocolDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
689 for (ObjCForwardProtocolDecl::protocol_iterator I = D->protocol_begin(),
690 E = D->protocol_end();
691 I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000692 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000693 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000694
695 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000696}
697
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000698bool CursorVisitor::VisitObjCClassDecl(ObjCClassDecl *D) {
699 for (ObjCClassDecl::iterator C = D->begin(), CEnd = D->end(); C != CEnd; ++C)
700 if (Visit(MakeCursorObjCClassRef(C->getInterface(), C->getLocation(), TU)))
701 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000702
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000703 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000704}
705
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000706bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
707 ASTContext &Context = TU->getASTContext();
708
709 // Some builtin types (such as Objective-C's "id", "sel", and
710 // "Class") have associated declarations. Create cursors for those.
711 QualType VisitType;
712 switch (TL.getType()->getAs<BuiltinType>()->getKind()) {
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000713 case BuiltinType::Void:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000714 case BuiltinType::Bool:
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000715 case BuiltinType::Char_U:
716 case BuiltinType::UChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000717 case BuiltinType::Char16:
718 case BuiltinType::Char32:
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000719 case BuiltinType::UShort:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000720 case BuiltinType::UInt:
721 case BuiltinType::ULong:
722 case BuiltinType::ULongLong:
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000723 case BuiltinType::UInt128:
724 case BuiltinType::Char_S:
725 case BuiltinType::SChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000726 case BuiltinType::WChar:
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000727 case BuiltinType::Short:
728 case BuiltinType::Int:
729 case BuiltinType::Long:
730 case BuiltinType::LongLong:
731 case BuiltinType::Int128:
732 case BuiltinType::Float:
733 case BuiltinType::Double:
734 case BuiltinType::LongDouble:
735 case BuiltinType::NullPtr:
736 case BuiltinType::Overload:
737 case BuiltinType::Dependent:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000738 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000739
740 case BuiltinType::UndeducedAuto: // FIXME: Deserves a cursor?
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000741 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000742
Ted Kremenekc4174cc2010-02-18 18:52:18 +0000743 case BuiltinType::ObjCId:
744 VisitType = Context.getObjCIdType();
745 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000746
747 case BuiltinType::ObjCClass:
748 VisitType = Context.getObjCClassType();
749 break;
750
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000751 case BuiltinType::ObjCSel:
752 VisitType = Context.getObjCSelType();
753 break;
754 }
755
756 if (!VisitType.isNull()) {
757 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000758 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000759 TU));
760 }
761
762 return false;
763}
764
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000765bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
766 return Visit(MakeCursorTypeRef(TL.getTypedefDecl(), TL.getNameLoc(), TU));
767}
768
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000769bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
770 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
771}
772
773bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
774 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
775}
776
777bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
778 if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
779 return true;
780
781 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
782 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
783 TU)))
784 return true;
785 }
786
787 return false;
788}
789
790bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
791 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseTypeLoc()))
792 return true;
793
794 if (TL.hasProtocolsAsWritten()) {
795 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000796 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I),
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000797 TL.getProtocolLoc(I),
798 TU)))
799 return true;
800 }
801 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000802
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000803 return false;
804}
805
806bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
807 return Visit(TL.getPointeeLoc());
808}
809
810bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
811 return Visit(TL.getPointeeLoc());
812}
813
814bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
815 return Visit(TL.getPointeeLoc());
816}
817
818bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000819 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000820}
821
822bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000823 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000824}
825
826bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
827 if (Visit(TL.getResultLoc()))
828 return true;
829
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000830 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
Ted Kremenek5dbacb42010-04-07 00:27:13 +0000831 if (Decl *D = TL.getArg(I))
832 if (Visit(MakeCXCursor(D, TU)))
833 return true;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000834
835 return false;
836}
837
838bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
839 if (Visit(TL.getElementLoc()))
840 return true;
841
842 if (Expr *Size = TL.getSizeExpr())
843 return Visit(MakeCXCursor(Size, StmtParent, TU));
844
845 return false;
846}
847
Douglas Gregor2332c112010-01-21 20:48:56 +0000848bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
849 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
850}
851
852bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
853 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
854 return Visit(TSInfo->getTypeLoc());
855
856 return false;
857}
858
Douglas Gregora59e3902010-01-21 23:27:09 +0000859bool CursorVisitor::VisitStmt(Stmt *S) {
860 for (Stmt::child_iterator Child = S->child_begin(), ChildEnd = S->child_end();
861 Child != ChildEnd; ++Child) {
Daniel Dunbar54d67ca2010-01-25 00:40:30 +0000862 if (*Child && Visit(MakeCXCursor(*Child, StmtParent, TU)))
Douglas Gregora59e3902010-01-21 23:27:09 +0000863 return true;
864 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000865
Douglas Gregora59e3902010-01-21 23:27:09 +0000866 return false;
867}
868
869bool CursorVisitor::VisitDeclStmt(DeclStmt *S) {
870 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
871 D != DEnd; ++D) {
Douglas Gregor263b47b2010-01-25 16:12:32 +0000872 if (*D && Visit(MakeCXCursor(*D, TU)))
Douglas Gregora59e3902010-01-21 23:27:09 +0000873 return true;
874 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000875
Douglas Gregora59e3902010-01-21 23:27:09 +0000876 return false;
877}
878
Douglas Gregorf5bab412010-01-22 01:00:11 +0000879bool CursorVisitor::VisitIfStmt(IfStmt *S) {
880 if (VarDecl *Var = S->getConditionVariable()) {
881 if (Visit(MakeCXCursor(Var, TU)))
882 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000883 }
884
Douglas Gregor263b47b2010-01-25 16:12:32 +0000885 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
886 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +0000887 if (S->getThen() && Visit(MakeCXCursor(S->getThen(), StmtParent, TU)))
888 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +0000889 if (S->getElse() && Visit(MakeCXCursor(S->getElse(), StmtParent, TU)))
890 return true;
891
892 return false;
893}
894
895bool CursorVisitor::VisitSwitchStmt(SwitchStmt *S) {
896 if (VarDecl *Var = S->getConditionVariable()) {
897 if (Visit(MakeCXCursor(Var, TU)))
898 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000899 }
900
Douglas Gregor263b47b2010-01-25 16:12:32 +0000901 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
902 return true;
903 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
904 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000905
Douglas Gregor263b47b2010-01-25 16:12:32 +0000906 return false;
907}
908
909bool CursorVisitor::VisitWhileStmt(WhileStmt *S) {
910 if (VarDecl *Var = S->getConditionVariable()) {
911 if (Visit(MakeCXCursor(Var, TU)))
912 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000913 }
914
Douglas Gregor263b47b2010-01-25 16:12:32 +0000915 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
916 return true;
917 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
Douglas Gregorf5bab412010-01-22 01:00:11 +0000918 return true;
919
Douglas Gregor263b47b2010-01-25 16:12:32 +0000920 return false;
921}
922
923bool CursorVisitor::VisitForStmt(ForStmt *S) {
924 if (S->getInit() && Visit(MakeCXCursor(S->getInit(), StmtParent, TU)))
925 return true;
926 if (VarDecl *Var = S->getConditionVariable()) {
927 if (Visit(MakeCXCursor(Var, TU)))
928 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000929 }
930
Douglas Gregor263b47b2010-01-25 16:12:32 +0000931 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
932 return true;
933 if (S->getInc() && Visit(MakeCXCursor(S->getInc(), StmtParent, TU)))
934 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +0000935 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
936 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000937
Douglas Gregorf5bab412010-01-22 01:00:11 +0000938 return false;
939}
940
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000941bool CursorVisitor::VisitBlockExpr(BlockExpr *B) {
942 return Visit(B->getBlockDecl());
943}
944
Douglas Gregor336fd812010-01-23 00:40:08 +0000945bool CursorVisitor::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E) {
946 if (E->isArgumentType()) {
947 if (TypeSourceInfo *TSInfo = E->getArgumentTypeInfo())
948 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000949
Douglas Gregor336fd812010-01-23 00:40:08 +0000950 return false;
951 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000952
Douglas Gregor336fd812010-01-23 00:40:08 +0000953 return VisitExpr(E);
954}
955
956bool CursorVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
957 if (TypeSourceInfo *TSInfo = E->getTypeInfoAsWritten())
958 if (Visit(TSInfo->getTypeLoc()))
959 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000960
Douglas Gregor336fd812010-01-23 00:40:08 +0000961 return VisitCastExpr(E);
962}
963
964bool CursorVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
965 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
966 if (Visit(TSInfo->getTypeLoc()))
967 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000968
Douglas Gregor336fd812010-01-23 00:40:08 +0000969 return VisitExpr(E);
970}
971
Douglas Gregorc2350e52010-03-08 16:40:19 +0000972bool CursorVisitor::VisitObjCMessageExpr(ObjCMessageExpr *E) {
973 ObjCMessageExpr::ClassInfo CI = E->getClassInfo();
974 if (CI.Decl && Visit(MakeCursorObjCClassRef(CI.Decl, CI.Loc, TU)))
975 return true;
976
977 return VisitExpr(E);
978}
979
Ted Kremenek09dfa372010-02-18 05:46:33 +0000980bool CursorVisitor::VisitAttributes(Decl *D) {
981 for (const Attr *A = D->getAttrs(); A; A = A->getNext())
982 if (Visit(MakeCXCursor(A, D, TU)))
983 return true;
984
985 return false;
986}
987
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000988extern "C" {
Douglas Gregor0a812cf2010-02-18 23:07:20 +0000989CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
990 int displayDiagnostics) {
Douglas Gregora030b7c2010-01-22 20:35:53 +0000991 CIndexer *CIdxr = new CIndexer();
Steve Naroffe56b4ba2009-10-20 14:46:24 +0000992 if (excludeDeclarationsFromPCH)
993 CIdxr->setOnlyLocalDecls();
Douglas Gregor0a812cf2010-02-18 23:07:20 +0000994 if (displayDiagnostics)
995 CIdxr->setDisplayDiagnostics();
Steve Naroffe56b4ba2009-10-20 14:46:24 +0000996 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +0000997}
998
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000999void clang_disposeIndex(CXIndex CIdx) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001000 if (CIdx)
1001 delete static_cast<CIndexer *>(CIdx);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00001002}
1003
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001004void clang_setUseExternalASTGeneration(CXIndex CIdx, int value) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001005 if (CIdx) {
1006 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
1007 CXXIdx->setUseExternalASTGeneration(value);
1008 }
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001009}
1010
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001011CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
Douglas Gregora88084b2010-02-18 18:08:43 +00001012 const char *ast_filename) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001013 if (!CIdx)
1014 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001015
Douglas Gregor7d1d49d2009-10-16 20:01:17 +00001016 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001017
Douglas Gregor28019772010-04-05 23:52:57 +00001018 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
1019 return ASTUnit::LoadFromPCHFile(ast_filename, Diags,
Douglas Gregora88084b2010-02-18 18:08:43 +00001020 CXXIdx->getOnlyLocalDecls(),
1021 0, 0, true);
Steve Naroff600866c2009-08-27 19:51:58 +00001022}
1023
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001024CXTranslationUnit
1025clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
1026 const char *source_filename,
1027 int num_command_line_args,
Douglas Gregor4db64a42010-01-23 00:14:00 +00001028 const char **command_line_args,
1029 unsigned num_unsaved_files,
Douglas Gregora88084b2010-02-18 18:08:43 +00001030 struct CXUnsavedFile *unsaved_files) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001031 if (!CIdx)
1032 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001033
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001034 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
1035
Douglas Gregor5352ac02010-01-28 00:27:43 +00001036 // Configure the diagnostics.
1037 DiagnosticOptions DiagOpts;
Douglas Gregor28019772010-04-05 23:52:57 +00001038 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
1039 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001040
Douglas Gregor4db64a42010-01-23 00:14:00 +00001041 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
1042 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattnera0a270c2010-04-05 22:42:27 +00001043 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001044 const llvm::MemoryBuffer *Buffer
Chris Lattnera0a270c2010-04-05 22:42:27 +00001045 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregor4db64a42010-01-23 00:14:00 +00001046 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
1047 Buffer));
1048 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001049
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001050 if (!CXXIdx->getUseExternalASTGeneration()) {
1051 llvm::SmallVector<const char *, 16> Args;
1052
1053 // The 'source_filename' argument is optional. If the caller does not
1054 // specify it then it is assumed that the source file is specified
1055 // in the actual argument list.
1056 if (source_filename)
1057 Args.push_back(source_filename);
1058 Args.insert(Args.end(), command_line_args,
1059 command_line_args + num_command_line_args);
Douglas Gregor94dc8f62010-03-19 16:15:56 +00001060 Args.push_back("-Xclang");
1061 Args.push_back("-detailed-preprocessing-record");
Douglas Gregor5352ac02010-01-28 00:27:43 +00001062 unsigned NumErrors = Diags->getNumErrors();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001063
Ted Kremenek29b72842010-01-07 22:49:05 +00001064#ifdef USE_CRASHTRACER
1065 ArgsCrashTracerInfo ACTI(Args);
Ted Kremenek8a8da7d2010-01-06 03:42:32 +00001066#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001067
Daniel Dunbar94220972009-12-05 02:17:18 +00001068 llvm::OwningPtr<ASTUnit> Unit(
1069 ASTUnit::LoadFromCommandLine(Args.data(), Args.data() + Args.size(),
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001070 Diags,
Daniel Dunbar869824e2009-12-13 03:46:13 +00001071 CXXIdx->getClangResourcesPath(),
Daniel Dunbar94220972009-12-05 02:17:18 +00001072 CXXIdx->getOnlyLocalDecls(),
Douglas Gregor4db64a42010-01-23 00:14:00 +00001073 RemappedFiles.data(),
Douglas Gregora88084b2010-02-18 18:08:43 +00001074 RemappedFiles.size(),
Douglas Gregor94dc8f62010-03-19 16:15:56 +00001075 /*CaptureDiagnostics=*/true));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001076
Daniel Dunbar94220972009-12-05 02:17:18 +00001077 // FIXME: Until we have broader testing, just drop the entire AST if we
1078 // encountered an error.
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001079 if (NumErrors != Diags->getNumErrors()) {
Ted Kremenek34f6a322010-03-05 22:43:29 +00001080 // Make sure to check that 'Unit' is non-NULL.
1081 if (CXXIdx->getDisplayDiagnostics() && Unit.get()) {
Douglas Gregor405634b2010-04-05 18:10:21 +00001082 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
1083 DEnd = Unit->stored_diag_end();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001084 D != DEnd; ++D) {
1085 CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOptions());
Douglas Gregor274f1902010-02-22 23:17:23 +00001086 CXString Msg = clang_formatDiagnostic(&Diag,
1087 clang_defaultDiagnosticDisplayOptions());
1088 fprintf(stderr, "%s\n", clang_getCString(Msg));
1089 clang_disposeString(Msg);
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001090 }
Douglas Gregor274f1902010-02-22 23:17:23 +00001091#ifdef LLVM_ON_WIN32
1092 // On Windows, force a flush, since there may be multiple copies of
1093 // stderr and stdout in the file system, all with different buffers
1094 // but writing to the same device.
1095 fflush(stderr);
Ted Kremenek83c51842010-03-26 01:34:51 +00001096#endif
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001097 }
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001098 }
Daniel Dunbar94220972009-12-05 02:17:18 +00001099
1100 return Unit.take();
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001101 }
1102
Ted Kremenek139ba862009-10-22 00:03:57 +00001103 // Build up the arguments for invoking 'clang'.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001104 std::vector<const char *> argv;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001105
Ted Kremenek139ba862009-10-22 00:03:57 +00001106 // First add the complete path to the 'clang' executable.
1107 llvm::sys::Path ClangPath = static_cast<CIndexer *>(CIdx)->getClangPath();
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00001108 argv.push_back(ClangPath.c_str());
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001109
Ted Kremenek139ba862009-10-22 00:03:57 +00001110 // Add the '-emit-ast' option as our execution mode for 'clang'.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001111 argv.push_back("-emit-ast");
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001112
Ted Kremenek139ba862009-10-22 00:03:57 +00001113 // The 'source_filename' argument is optional. If the caller does not
1114 // specify it then it is assumed that the source file is specified
1115 // in the actual argument list.
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001116 if (source_filename)
1117 argv.push_back(source_filename);
Ted Kremenek139ba862009-10-22 00:03:57 +00001118
Steve Naroff37b5ac22009-10-15 20:50:09 +00001119 // Generate a temporary name for the AST file.
Ted Kremenek139ba862009-10-22 00:03:57 +00001120 argv.push_back("-o");
Benjamin Kramerc2a98162010-03-13 21:22:49 +00001121 char astTmpFile[L_tmpnam];
1122 argv.push_back(tmpnam(astTmpFile));
Ted Kremenek139ba862009-10-22 00:03:57 +00001123
Douglas Gregor4db64a42010-01-23 00:14:00 +00001124 // Remap any unsaved files to temporary files.
1125 std::vector<llvm::sys::Path> TemporaryFiles;
1126 std::vector<std::string> RemapArgs;
1127 if (RemapFiles(num_unsaved_files, unsaved_files, RemapArgs, TemporaryFiles))
1128 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001129
Douglas Gregor4db64a42010-01-23 00:14:00 +00001130 // The pointers into the elements of RemapArgs are stable because we
1131 // won't be adding anything to RemapArgs after this point.
1132 for (unsigned i = 0, e = RemapArgs.size(); i != e; ++i)
1133 argv.push_back(RemapArgs[i].c_str());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001134
Ted Kremenek139ba862009-10-22 00:03:57 +00001135 // Process the compiler options, stripping off '-o', '-c', '-fsyntax-only'.
1136 for (int i = 0; i < num_command_line_args; ++i)
1137 if (const char *arg = command_line_args[i]) {
1138 if (strcmp(arg, "-o") == 0) {
1139 ++i; // Also skip the matching argument.
1140 continue;
1141 }
1142 if (strcmp(arg, "-emit-ast") == 0 ||
1143 strcmp(arg, "-c") == 0 ||
1144 strcmp(arg, "-fsyntax-only") == 0) {
1145 continue;
1146 }
1147
1148 // Keep the argument.
1149 argv.push_back(arg);
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001150 }
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001151
Douglas Gregord93256e2010-01-28 06:00:51 +00001152 // Generate a temporary name for the diagnostics file.
Benjamin Kramerc2a98162010-03-13 21:22:49 +00001153 char tmpFileResults[L_tmpnam];
1154 char *tmpResultsFileName = tmpnam(tmpFileResults);
1155 llvm::sys::Path DiagnosticsFile(tmpResultsFileName);
Douglas Gregord93256e2010-01-28 06:00:51 +00001156 TemporaryFiles.push_back(DiagnosticsFile);
1157 argv.push_back("-fdiagnostics-binary");
1158
Douglas Gregor94dc8f62010-03-19 16:15:56 +00001159 argv.push_back("-Xclang");
1160 argv.push_back("-detailed-preprocessing-record");
1161
Ted Kremenek139ba862009-10-22 00:03:57 +00001162 // Add the null terminator.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001163 argv.push_back(NULL);
1164
Ted Kremenekfeb15e32009-10-26 22:14:08 +00001165 // Invoke 'clang'.
1166 llvm::sys::Path DevNull; // leave empty, causes redirection to /dev/null
1167 // on Unix or NUL (Windows).
Ted Kremenek379afec2009-10-22 03:24:01 +00001168 std::string ErrMsg;
Douglas Gregord93256e2010-01-28 06:00:51 +00001169 const llvm::sys::Path *Redirects[] = { &DevNull, &DevNull, &DiagnosticsFile,
1170 NULL };
Ted Kremenek379afec2009-10-22 03:24:01 +00001171 llvm::sys::Program::ExecuteAndWait(ClangPath, &argv[0], /* env */ NULL,
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001172 /* redirects */ &Redirects[0],
Ted Kremenek379afec2009-10-22 03:24:01 +00001173 /* secondsToWait */ 0, /* memoryLimits */ 0, &ErrMsg);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001174
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001175 if (!ErrMsg.empty()) {
1176 std::string AllArgs;
Ted Kremenek379afec2009-10-22 03:24:01 +00001177 for (std::vector<const char*>::iterator I = argv.begin(), E = argv.end();
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001178 I != E; ++I) {
1179 AllArgs += ' ';
Ted Kremenek779e5f42009-10-26 22:08:39 +00001180 if (*I)
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001181 AllArgs += *I;
Ted Kremenek779e5f42009-10-26 22:08:39 +00001182 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001183
Daniel Dunbar32141c82010-02-23 20:23:45 +00001184 Diags->Report(diag::err_fe_invoking) << AllArgs << ErrMsg;
Ted Kremenek379afec2009-10-22 03:24:01 +00001185 }
Benjamin Kramer0829a832009-10-18 11:19:36 +00001186
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001187 ASTUnit *ATU = ASTUnit::LoadFromPCHFile(astTmpFile, Diags,
Douglas Gregor4db64a42010-01-23 00:14:00 +00001188 CXXIdx->getOnlyLocalDecls(),
Douglas Gregor4db64a42010-01-23 00:14:00 +00001189 RemappedFiles.data(),
Douglas Gregora88084b2010-02-18 18:08:43 +00001190 RemappedFiles.size(),
1191 /*CaptureDiagnostics=*/true);
Douglas Gregora88084b2010-02-18 18:08:43 +00001192 if (ATU) {
1193 LoadSerializedDiagnostics(DiagnosticsFile,
1194 num_unsaved_files, unsaved_files,
1195 ATU->getFileManager(),
1196 ATU->getSourceManager(),
Douglas Gregor405634b2010-04-05 18:10:21 +00001197 ATU->getStoredDiagnostics());
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001198 } else if (CXXIdx->getDisplayDiagnostics()) {
1199 // We failed to load the ASTUnit, but we can still deserialize the
1200 // diagnostics and emit them.
1201 FileManager FileMgr;
Douglas Gregorf715ca12010-03-16 00:06:06 +00001202 Diagnostic Diag;
1203 SourceManager SourceMgr(Diag);
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001204 // FIXME: Faked LangOpts!
1205 LangOptions LangOpts;
1206 llvm::SmallVector<StoredDiagnostic, 4> Diags;
1207 LoadSerializedDiagnostics(DiagnosticsFile,
1208 num_unsaved_files, unsaved_files,
1209 FileMgr, SourceMgr, Diags);
1210 for (llvm::SmallVector<StoredDiagnostic, 4>::iterator D = Diags.begin(),
1211 DEnd = Diags.end();
1212 D != DEnd; ++D) {
1213 CXStoredDiagnostic Diag(*D, LangOpts);
Douglas Gregor274f1902010-02-22 23:17:23 +00001214 CXString Msg = clang_formatDiagnostic(&Diag,
1215 clang_defaultDiagnosticDisplayOptions());
1216 fprintf(stderr, "%s\n", clang_getCString(Msg));
1217 clang_disposeString(Msg);
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001218 }
Douglas Gregor274f1902010-02-22 23:17:23 +00001219
1220#ifdef LLVM_ON_WIN32
1221 // On Windows, force a flush, since there may be multiple copies of
1222 // stderr and stdout in the file system, all with different buffers
1223 // but writing to the same device.
1224 fflush(stderr);
1225#endif
Douglas Gregora88084b2010-02-18 18:08:43 +00001226 }
Douglas Gregord93256e2010-01-28 06:00:51 +00001227
Douglas Gregor313e26c2010-02-18 23:35:40 +00001228 if (ATU) {
1229 // Make the translation unit responsible for destroying all temporary files.
1230 for (unsigned i = 0, e = TemporaryFiles.size(); i != e; ++i)
1231 ATU->addTemporaryFile(TemporaryFiles[i]);
1232 ATU->addTemporaryFile(llvm::sys::Path(ATU->getPCHFileName()));
1233 } else {
1234 // Destroy all of the temporary files now; they can't be referenced any
1235 // longer.
1236 llvm::sys::Path(astTmpFile).eraseFromDisk();
1237 for (unsigned i = 0, e = TemporaryFiles.size(); i != e; ++i)
1238 TemporaryFiles[i].eraseFromDisk();
1239 }
1240
Steve Naroffe19944c2009-10-15 22:23:48 +00001241 return ATU;
Steve Naroff5b7d8e22009-10-15 20:04:39 +00001242}
1243
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001244void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001245 if (CTUnit)
1246 delete static_cast<ASTUnit *>(CTUnit);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00001247}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001248
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001249CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001250 if (!CTUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001251 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001252
Steve Naroff77accc12009-09-03 18:19:54 +00001253 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001254 return createCXString(CXXUnit->getOriginalSourceFileName(), true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +00001255}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +00001256
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001257CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001258 CXCursor Result = { CXCursor_TranslationUnit, { 0, 0, TU } };
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001259 return Result;
1260}
1261
Ted Kremenekfb480492010-01-13 21:46:36 +00001262} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +00001263
Ted Kremenekfb480492010-01-13 21:46:36 +00001264//===----------------------------------------------------------------------===//
Douglas Gregor1db19de2010-01-19 21:36:55 +00001265// CXSourceLocation and CXSourceRange Operations.
1266//===----------------------------------------------------------------------===//
1267
Douglas Gregorb9790342010-01-22 21:44:22 +00001268extern "C" {
1269CXSourceLocation clang_getNullLocation() {
Douglas Gregor5352ac02010-01-28 00:27:43 +00001270 CXSourceLocation Result = { { 0, 0 }, 0 };
Douglas Gregorb9790342010-01-22 21:44:22 +00001271 return Result;
1272}
1273
1274unsigned clang_equalLocations(CXSourceLocation loc1, CXSourceLocation loc2) {
Daniel Dunbar90a6b9e2010-01-30 23:58:27 +00001275 return (loc1.ptr_data[0] == loc2.ptr_data[0] &&
1276 loc1.ptr_data[1] == loc2.ptr_data[1] &&
1277 loc1.int_data == loc2.int_data);
Douglas Gregorb9790342010-01-22 21:44:22 +00001278}
1279
1280CXSourceLocation clang_getLocation(CXTranslationUnit tu,
1281 CXFile file,
1282 unsigned line,
1283 unsigned column) {
1284 if (!tu)
1285 return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001286
Douglas Gregorb9790342010-01-22 21:44:22 +00001287 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
1288 SourceLocation SLoc
1289 = CXXUnit->getSourceManager().getLocation(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001290 static_cast<const FileEntry *>(file),
Douglas Gregorb9790342010-01-22 21:44:22 +00001291 line, column);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001292
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00001293 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
Douglas Gregorb9790342010-01-22 21:44:22 +00001294}
1295
Douglas Gregor5352ac02010-01-28 00:27:43 +00001296CXSourceRange clang_getNullRange() {
1297 CXSourceRange Result = { { 0, 0 }, 0, 0 };
1298 return Result;
1299}
Daniel Dunbard52864b2010-02-14 10:02:57 +00001300
Douglas Gregor5352ac02010-01-28 00:27:43 +00001301CXSourceRange clang_getRange(CXSourceLocation begin, CXSourceLocation end) {
1302 if (begin.ptr_data[0] != end.ptr_data[0] ||
1303 begin.ptr_data[1] != end.ptr_data[1])
1304 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001305
1306 CXSourceRange Result = { { begin.ptr_data[0], begin.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00001307 begin.int_data, end.int_data };
Douglas Gregorb9790342010-01-22 21:44:22 +00001308 return Result;
1309}
1310
Douglas Gregor46766dc2010-01-26 19:19:08 +00001311void clang_getInstantiationLocation(CXSourceLocation location,
1312 CXFile *file,
1313 unsigned *line,
1314 unsigned *column,
1315 unsigned *offset) {
Douglas Gregor1db19de2010-01-19 21:36:55 +00001316 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
1317
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00001318 if (!location.ptr_data[0] || Loc.isInvalid()) {
Douglas Gregor46766dc2010-01-26 19:19:08 +00001319 if (file)
1320 *file = 0;
1321 if (line)
1322 *line = 0;
1323 if (column)
1324 *column = 0;
1325 if (offset)
1326 *offset = 0;
1327 return;
1328 }
1329
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00001330 const SourceManager &SM =
1331 *static_cast<const SourceManager*>(location.ptr_data[0]);
Douglas Gregor1db19de2010-01-19 21:36:55 +00001332 SourceLocation InstLoc = SM.getInstantiationLoc(Loc);
Douglas Gregor1db19de2010-01-19 21:36:55 +00001333
1334 if (file)
1335 *file = (void *)SM.getFileEntryForID(SM.getFileID(InstLoc));
1336 if (line)
1337 *line = SM.getInstantiationLineNumber(InstLoc);
1338 if (column)
1339 *column = SM.getInstantiationColumnNumber(InstLoc);
Douglas Gregore69517c2010-01-26 03:07:15 +00001340 if (offset)
Douglas Gregor46766dc2010-01-26 19:19:08 +00001341 *offset = SM.getDecomposedLoc(InstLoc).second;
Douglas Gregore69517c2010-01-26 03:07:15 +00001342}
1343
Douglas Gregor1db19de2010-01-19 21:36:55 +00001344CXSourceLocation clang_getRangeStart(CXSourceRange range) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001345 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00001346 range.begin_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00001347 return Result;
1348}
1349
1350CXSourceLocation clang_getRangeEnd(CXSourceRange range) {
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00001351 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00001352 range.end_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00001353 return Result;
1354}
1355
Douglas Gregorb9790342010-01-22 21:44:22 +00001356} // end: extern "C"
1357
Douglas Gregor1db19de2010-01-19 21:36:55 +00001358//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00001359// CXFile Operations.
1360//===----------------------------------------------------------------------===//
1361
1362extern "C" {
Ted Kremenek74844072010-02-17 00:41:20 +00001363CXString clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00001364 if (!SFile)
Ted Kremenek74844072010-02-17 00:41:20 +00001365 return createCXString(NULL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001366
Steve Naroff88145032009-10-27 14:35:18 +00001367 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Ted Kremenek74844072010-02-17 00:41:20 +00001368 return createCXString(FEnt->getName());
Steve Naroff88145032009-10-27 14:35:18 +00001369}
1370
1371time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00001372 if (!SFile)
1373 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001374
Steve Naroff88145032009-10-27 14:35:18 +00001375 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
1376 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +00001377}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001378
Douglas Gregorb9790342010-01-22 21:44:22 +00001379CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
1380 if (!tu)
1381 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001382
Douglas Gregorb9790342010-01-22 21:44:22 +00001383 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001384
Douglas Gregorb9790342010-01-22 21:44:22 +00001385 FileManager &FMgr = CXXUnit->getFileManager();
1386 const FileEntry *File = FMgr.getFile(file_name, file_name+strlen(file_name));
1387 return const_cast<FileEntry *>(File);
1388}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001389
Ted Kremenekfb480492010-01-13 21:46:36 +00001390} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +00001391
Ted Kremenekfb480492010-01-13 21:46:36 +00001392//===----------------------------------------------------------------------===//
1393// CXCursor Operations.
1394//===----------------------------------------------------------------------===//
1395
Ted Kremenekfb480492010-01-13 21:46:36 +00001396static Decl *getDeclFromExpr(Stmt *E) {
1397 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
1398 return RefExpr->getDecl();
1399 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
1400 return ME->getMemberDecl();
1401 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
1402 return RE->getDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001403
Ted Kremenekfb480492010-01-13 21:46:36 +00001404 if (CallExpr *CE = dyn_cast<CallExpr>(E))
1405 return getDeclFromExpr(CE->getCallee());
1406 if (CastExpr *CE = dyn_cast<CastExpr>(E))
1407 return getDeclFromExpr(CE->getSubExpr());
1408 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
1409 return OME->getMethodDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001410
Ted Kremenekfb480492010-01-13 21:46:36 +00001411 return 0;
1412}
1413
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00001414static SourceLocation getLocationFromExpr(Expr *E) {
1415 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
1416 return /*FIXME:*/Msg->getLeftLoc();
1417 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
1418 return DRE->getLocation();
1419 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
1420 return Member->getMemberLoc();
1421 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
1422 return Ivar->getLocation();
1423 return E->getLocStart();
1424}
1425
Ted Kremenekfb480492010-01-13 21:46:36 +00001426extern "C" {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001427
1428unsigned clang_visitChildren(CXCursor parent,
Douglas Gregorb1373d02010-01-20 20:59:29 +00001429 CXCursorVisitor visitor,
1430 CXClientData client_data) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001431 ASTUnit *CXXUnit = getCursorASTUnit(parent);
Douglas Gregorb1373d02010-01-20 20:59:29 +00001432
1433 unsigned PCHLevel = Decl::MaxPCHLevel;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001434
Douglas Gregorb1373d02010-01-20 20:59:29 +00001435 // Set the PCHLevel to filter out unwanted decls if requested.
1436 if (CXXUnit->getOnlyLocalDecls()) {
1437 PCHLevel = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001438
Douglas Gregorb1373d02010-01-20 20:59:29 +00001439 // If the main input was an AST, bump the level.
1440 if (CXXUnit->isMainFileAST())
1441 ++PCHLevel;
1442 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001443
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001444 CursorVisitor CursorVis(CXXUnit, visitor, client_data, PCHLevel);
Douglas Gregorb1373d02010-01-20 20:59:29 +00001445 return CursorVis.VisitChildren(parent);
1446}
1447
Douglas Gregor78205d42010-01-20 21:45:58 +00001448static CXString getDeclSpelling(Decl *D) {
1449 NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
1450 if (!ND)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001451 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001452
Douglas Gregor78205d42010-01-20 21:45:58 +00001453 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001454 return createCXString(OMD->getSelector().getAsString());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001455
Douglas Gregor78205d42010-01-20 21:45:58 +00001456 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
1457 // No, this isn't the same as the code below. getIdentifier() is non-virtual
1458 // and returns different names. NamedDecl returns the class name and
1459 // ObjCCategoryImplDecl returns the category name.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001460 return createCXString(CIMP->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001461
Douglas Gregor78205d42010-01-20 21:45:58 +00001462 if (ND->getIdentifier())
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001463 return createCXString(ND->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001464
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001465 return createCXString("");
Douglas Gregor78205d42010-01-20 21:45:58 +00001466}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001467
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001468CXString clang_getCursorSpelling(CXCursor C) {
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001469 if (clang_isTranslationUnit(C.kind))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001470 return clang_getTranslationUnitSpelling(C.data[2]);
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001471
Steve Narofff334b4e2009-09-02 18:26:48 +00001472 if (clang_isReference(C.kind)) {
1473 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00001474 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +00001475 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001476 return createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00001477 }
1478 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +00001479 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001480 return createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00001481 }
1482 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +00001483 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +00001484 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001485 return createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00001486 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001487 case CXCursor_TypeRef: {
1488 TypeDecl *Type = getCursorTypeRef(C).first;
1489 assert(Type && "Missing type decl");
1490
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001491 return createCXString(getCursorContext(C).getTypeDeclType(Type).
1492 getAsString());
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001493 }
1494
Daniel Dunbaracca7252009-11-30 20:42:49 +00001495 default:
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001496 return createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +00001497 }
1498 }
Douglas Gregor97b98722010-01-19 23:20:36 +00001499
1500 if (clang_isExpression(C.kind)) {
1501 Decl *D = getDeclFromExpr(getCursorExpr(C));
1502 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +00001503 return getDeclSpelling(D);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001504 return createCXString("");
Douglas Gregor97b98722010-01-19 23:20:36 +00001505 }
1506
Douglas Gregor4ae8f292010-03-18 17:52:52 +00001507 if (C.kind == CXCursor_MacroInstantiation)
1508 return createCXString(getCursorMacroInstantiation(C)->getName()
1509 ->getNameStart());
1510
Douglas Gregor572feb22010-03-18 18:04:21 +00001511 if (C.kind == CXCursor_MacroDefinition)
1512 return createCXString(getCursorMacroDefinition(C)->getName()
1513 ->getNameStart());
1514
Douglas Gregor60cbfac2010-01-25 16:56:17 +00001515 if (clang_isDeclaration(C.kind))
1516 return getDeclSpelling(getCursorDecl(C));
Ted Kremeneke68fff62010-02-17 00:41:32 +00001517
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001518 return createCXString("");
Steve Narofff334b4e2009-09-02 18:26:48 +00001519}
1520
Ted Kremeneke68fff62010-02-17 00:41:32 +00001521CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00001522 switch (Kind) {
Ted Kremeneke68fff62010-02-17 00:41:32 +00001523 case CXCursor_FunctionDecl:
1524 return createCXString("FunctionDecl");
1525 case CXCursor_TypedefDecl:
1526 return createCXString("TypedefDecl");
1527 case CXCursor_EnumDecl:
1528 return createCXString("EnumDecl");
1529 case CXCursor_EnumConstantDecl:
1530 return createCXString("EnumConstantDecl");
1531 case CXCursor_StructDecl:
1532 return createCXString("StructDecl");
1533 case CXCursor_UnionDecl:
1534 return createCXString("UnionDecl");
1535 case CXCursor_ClassDecl:
1536 return createCXString("ClassDecl");
1537 case CXCursor_FieldDecl:
1538 return createCXString("FieldDecl");
1539 case CXCursor_VarDecl:
1540 return createCXString("VarDecl");
1541 case CXCursor_ParmDecl:
1542 return createCXString("ParmDecl");
1543 case CXCursor_ObjCInterfaceDecl:
1544 return createCXString("ObjCInterfaceDecl");
1545 case CXCursor_ObjCCategoryDecl:
1546 return createCXString("ObjCCategoryDecl");
1547 case CXCursor_ObjCProtocolDecl:
1548 return createCXString("ObjCProtocolDecl");
1549 case CXCursor_ObjCPropertyDecl:
1550 return createCXString("ObjCPropertyDecl");
1551 case CXCursor_ObjCIvarDecl:
1552 return createCXString("ObjCIvarDecl");
1553 case CXCursor_ObjCInstanceMethodDecl:
1554 return createCXString("ObjCInstanceMethodDecl");
1555 case CXCursor_ObjCClassMethodDecl:
1556 return createCXString("ObjCClassMethodDecl");
1557 case CXCursor_ObjCImplementationDecl:
1558 return createCXString("ObjCImplementationDecl");
1559 case CXCursor_ObjCCategoryImplDecl:
1560 return createCXString("ObjCCategoryImplDecl");
1561 case CXCursor_UnexposedDecl:
1562 return createCXString("UnexposedDecl");
1563 case CXCursor_ObjCSuperClassRef:
1564 return createCXString("ObjCSuperClassRef");
1565 case CXCursor_ObjCProtocolRef:
1566 return createCXString("ObjCProtocolRef");
1567 case CXCursor_ObjCClassRef:
1568 return createCXString("ObjCClassRef");
1569 case CXCursor_TypeRef:
1570 return createCXString("TypeRef");
1571 case CXCursor_UnexposedExpr:
1572 return createCXString("UnexposedExpr");
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00001573 case CXCursor_BlockExpr:
1574 return createCXString("BlockExpr");
Ted Kremeneke68fff62010-02-17 00:41:32 +00001575 case CXCursor_DeclRefExpr:
1576 return createCXString("DeclRefExpr");
1577 case CXCursor_MemberRefExpr:
1578 return createCXString("MemberRefExpr");
1579 case CXCursor_CallExpr:
1580 return createCXString("CallExpr");
1581 case CXCursor_ObjCMessageExpr:
1582 return createCXString("ObjCMessageExpr");
1583 case CXCursor_UnexposedStmt:
1584 return createCXString("UnexposedStmt");
1585 case CXCursor_InvalidFile:
1586 return createCXString("InvalidFile");
Ted Kremenek292db642010-03-19 20:39:05 +00001587 case CXCursor_InvalidCode:
1588 return createCXString("InvalidCode");
Ted Kremeneke68fff62010-02-17 00:41:32 +00001589 case CXCursor_NoDeclFound:
1590 return createCXString("NoDeclFound");
1591 case CXCursor_NotImplemented:
1592 return createCXString("NotImplemented");
1593 case CXCursor_TranslationUnit:
1594 return createCXString("TranslationUnit");
Ted Kremeneke77f4432010-02-18 03:09:07 +00001595 case CXCursor_UnexposedAttr:
1596 return createCXString("UnexposedAttr");
1597 case CXCursor_IBActionAttr:
1598 return createCXString("attribute(ibaction)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00001599 case CXCursor_IBOutletAttr:
1600 return createCXString("attribute(iboutlet)");
1601 case CXCursor_PreprocessingDirective:
1602 return createCXString("preprocessing directive");
Douglas Gregor572feb22010-03-18 18:04:21 +00001603 case CXCursor_MacroDefinition:
1604 return createCXString("macro definition");
Douglas Gregor48072312010-03-18 15:23:44 +00001605 case CXCursor_MacroInstantiation:
1606 return createCXString("macro instantiation");
Steve Naroff89922f82009-08-31 00:59:03 +00001607 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00001608
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00001609 llvm_unreachable("Unhandled CXCursorKind");
Ted Kremeneke68fff62010-02-17 00:41:32 +00001610 return createCXString(NULL);
Steve Naroff600866c2009-08-27 19:51:58 +00001611}
Steve Naroff89922f82009-08-31 00:59:03 +00001612
Ted Kremeneke68fff62010-02-17 00:41:32 +00001613enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
1614 CXCursor parent,
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001615 CXClientData client_data) {
1616 CXCursor *BestCursor = static_cast<CXCursor *>(client_data);
1617 *BestCursor = cursor;
1618 return CXChildVisit_Recurse;
1619}
Ted Kremeneke68fff62010-02-17 00:41:32 +00001620
Douglas Gregorb9790342010-01-22 21:44:22 +00001621CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
1622 if (!TU)
Ted Kremenekf4629892010-01-14 01:51:23 +00001623 return clang_getNullCursor();
Ted Kremeneke68fff62010-02-17 00:41:32 +00001624
Douglas Gregorb9790342010-01-22 21:44:22 +00001625 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
1626
Douglas Gregorbdf60622010-03-05 21:16:25 +00001627 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
1628
Ted Kremeneka297de22010-01-25 22:34:44 +00001629 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001630 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
1631 if (SLoc.isValid()) {
Daniel Dunbard52864b2010-02-14 10:02:57 +00001632 SourceRange RegionOfInterest(SLoc, SLoc.getFileLocWithOffset(1));
Ted Kremeneke68fff62010-02-17 00:41:32 +00001633
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001634 // FIXME: Would be great to have a "hint" cursor, then walk from that
1635 // hint cursor upward until we find a cursor whose source range encloses
1636 // the region of interest, rather than starting from the translation unit.
1637 CXCursor Parent = clang_getTranslationUnitCursor(CXXUnit);
Ted Kremeneke68fff62010-02-17 00:41:32 +00001638 CursorVisitor CursorVis(CXXUnit, GetCursorVisitor, &Result,
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001639 Decl::MaxPCHLevel, RegionOfInterest);
1640 CursorVis.VisitChildren(Parent);
Steve Naroff77128dd2009-09-15 20:25:34 +00001641 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00001642 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00001643}
1644
Ted Kremenek73885552009-11-17 19:28:59 +00001645CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00001646 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00001647}
1648
1649unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00001650 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00001651}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001652
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001653unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00001654 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
1655}
1656
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001657unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +00001658 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
1659}
Steve Naroff2d4d6292009-08-31 14:26:51 +00001660
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001661unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00001662 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
1663}
1664
Douglas Gregor97b98722010-01-19 23:20:36 +00001665unsigned clang_isExpression(enum CXCursorKind K) {
1666 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
1667}
1668
1669unsigned clang_isStatement(enum CXCursorKind K) {
1670 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
1671}
1672
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001673unsigned clang_isTranslationUnit(enum CXCursorKind K) {
1674 return K == CXCursor_TranslationUnit;
1675}
1676
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00001677unsigned clang_isPreprocessing(enum CXCursorKind K) {
1678 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
1679}
1680
Ted Kremenekad6eff62010-03-08 21:17:29 +00001681unsigned clang_isUnexposed(enum CXCursorKind K) {
1682 switch (K) {
1683 case CXCursor_UnexposedDecl:
1684 case CXCursor_UnexposedExpr:
1685 case CXCursor_UnexposedStmt:
1686 case CXCursor_UnexposedAttr:
1687 return true;
1688 default:
1689 return false;
1690 }
1691}
1692
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001693CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00001694 return C.kind;
1695}
1696
Douglas Gregor98258af2010-01-18 22:46:11 +00001697CXSourceLocation clang_getCursorLocation(CXCursor C) {
1698 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00001699 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001700 case CXCursor_ObjCSuperClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00001701 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1702 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001703 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001704 }
1705
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001706 case CXCursor_ObjCProtocolRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00001707 std::pair<ObjCProtocolDecl *, SourceLocation> P
1708 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001709 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001710 }
1711
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001712 case CXCursor_ObjCClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00001713 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1714 = getCursorObjCClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001715 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001716 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001717
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001718 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001719 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001720 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001721 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001722
Douglas Gregorf46034a2010-01-18 23:41:10 +00001723 default:
1724 // FIXME: Need a way to enumerate all non-reference cases.
1725 llvm_unreachable("Missed a reference kind");
1726 }
Douglas Gregor98258af2010-01-18 22:46:11 +00001727 }
Douglas Gregor97b98722010-01-19 23:20:36 +00001728
1729 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001730 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00001731 getLocationFromExpr(getCursorExpr(C)));
1732
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00001733 if (C.kind == CXCursor_PreprocessingDirective) {
1734 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
1735 return cxloc::translateSourceLocation(getCursorContext(C), L);
1736 }
Douglas Gregor48072312010-03-18 15:23:44 +00001737
1738 if (C.kind == CXCursor_MacroInstantiation) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00001739 SourceLocation L
1740 = cxcursor::getCursorMacroInstantiation(C)->getSourceRange().getBegin();
Douglas Gregor48072312010-03-18 15:23:44 +00001741 return cxloc::translateSourceLocation(getCursorContext(C), L);
1742 }
Douglas Gregor572feb22010-03-18 18:04:21 +00001743
1744 if (C.kind == CXCursor_MacroDefinition) {
1745 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
1746 return cxloc::translateSourceLocation(getCursorContext(C), L);
1747 }
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00001748
Douglas Gregor5352ac02010-01-28 00:27:43 +00001749 if (!getCursorDecl(C))
1750 return clang_getNullLocation();
Douglas Gregor98258af2010-01-18 22:46:11 +00001751
Douglas Gregorf46034a2010-01-18 23:41:10 +00001752 Decl *D = getCursorDecl(C);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001753 SourceLocation Loc = D->getLocation();
1754 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
1755 Loc = Class->getClassLoc();
Douglas Gregor2ca54fe2010-03-22 15:53:50 +00001756 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00001757}
Douglas Gregora7bde202010-01-19 00:34:46 +00001758
1759CXSourceRange clang_getCursorExtent(CXCursor C) {
1760 if (clang_isReference(C.kind)) {
1761 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001762 case CXCursor_ObjCSuperClassRef: {
Douglas Gregora7bde202010-01-19 00:34:46 +00001763 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1764 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001765 return cxloc::translateSourceRange(P.first->getASTContext(), P.second);
Douglas Gregora7bde202010-01-19 00:34:46 +00001766 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001767
1768 case CXCursor_ObjCProtocolRef: {
Douglas Gregora7bde202010-01-19 00:34:46 +00001769 std::pair<ObjCProtocolDecl *, SourceLocation> P
1770 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001771 return cxloc::translateSourceRange(P.first->getASTContext(), P.second);
Douglas Gregora7bde202010-01-19 00:34:46 +00001772 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001773
1774 case CXCursor_ObjCClassRef: {
Douglas Gregora7bde202010-01-19 00:34:46 +00001775 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1776 = getCursorObjCClassRef(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001777
Ted Kremeneka297de22010-01-25 22:34:44 +00001778 return cxloc::translateSourceRange(P.first->getASTContext(), P.second);
Douglas Gregora7bde202010-01-19 00:34:46 +00001779 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001780
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001781 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001782 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001783 return cxloc::translateSourceRange(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001784 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001785
Douglas Gregora7bde202010-01-19 00:34:46 +00001786 default:
1787 // FIXME: Need a way to enumerate all non-reference cases.
1788 llvm_unreachable("Missed a reference kind");
1789 }
1790 }
Douglas Gregor97b98722010-01-19 23:20:36 +00001791
1792 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001793 return cxloc::translateSourceRange(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00001794 getCursorExpr(C)->getSourceRange());
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001795
1796 if (clang_isStatement(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001797 return cxloc::translateSourceRange(getCursorContext(C),
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001798 getCursorStmt(C)->getSourceRange());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001799
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00001800 if (C.kind == CXCursor_PreprocessingDirective) {
1801 SourceRange R = cxcursor::getCursorPreprocessingDirective(C);
1802 return cxloc::translateSourceRange(getCursorContext(C), R);
1803 }
Douglas Gregor48072312010-03-18 15:23:44 +00001804
1805 if (C.kind == CXCursor_MacroInstantiation) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00001806 SourceRange R = cxcursor::getCursorMacroInstantiation(C)->getSourceRange();
Douglas Gregor48072312010-03-18 15:23:44 +00001807 return cxloc::translateSourceRange(getCursorContext(C), R);
1808 }
Douglas Gregor572feb22010-03-18 18:04:21 +00001809
1810 if (C.kind == CXCursor_MacroDefinition) {
1811 SourceRange R = cxcursor::getCursorMacroDefinition(C)->getSourceRange();
1812 return cxloc::translateSourceRange(getCursorContext(C), R);
1813 }
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00001814
Douglas Gregor5352ac02010-01-28 00:27:43 +00001815 if (!getCursorDecl(C))
1816 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001817
Douglas Gregora7bde202010-01-19 00:34:46 +00001818 Decl *D = getCursorDecl(C);
Douglas Gregor2ca54fe2010-03-22 15:53:50 +00001819 return cxloc::translateSourceRange(getCursorContext(C), D->getSourceRange());
Douglas Gregora7bde202010-01-19 00:34:46 +00001820}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001821
1822CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001823 if (clang_isInvalid(C.kind))
1824 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001825
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001826 ASTUnit *CXXUnit = getCursorASTUnit(C);
Douglas Gregorb6998662010-01-19 19:34:47 +00001827 if (clang_isDeclaration(C.kind))
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001828 return C;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001829
Douglas Gregor97b98722010-01-19 23:20:36 +00001830 if (clang_isExpression(C.kind)) {
1831 Decl *D = getDeclFromExpr(getCursorExpr(C));
1832 if (D)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001833 return MakeCXCursor(D, CXXUnit);
Douglas Gregor97b98722010-01-19 23:20:36 +00001834 return clang_getNullCursor();
1835 }
1836
Douglas Gregorbf7efa22010-03-18 18:23:03 +00001837 if (C.kind == CXCursor_MacroInstantiation) {
1838 if (MacroDefinition *Def = getCursorMacroInstantiation(C)->getDefinition())
1839 return MakeMacroDefinitionCursor(Def, CXXUnit);
1840 }
1841
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001842 if (!clang_isReference(C.kind))
1843 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001844
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001845 switch (C.kind) {
1846 case CXCursor_ObjCSuperClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001847 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001848
1849 case CXCursor_ObjCProtocolRef: {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001850 return MakeCXCursor(getCursorObjCProtocolRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001851
1852 case CXCursor_ObjCClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001853 return MakeCXCursor(getCursorObjCClassRef(C).first, CXXUnit);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001854
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001855 case CXCursor_TypeRef:
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001856 return MakeCXCursor(getCursorTypeRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001857
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001858 default:
1859 // We would prefer to enumerate all non-reference cursor kinds here.
1860 llvm_unreachable("Unhandled reference cursor kind");
1861 break;
1862 }
1863 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001864
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001865 return clang_getNullCursor();
1866}
1867
Douglas Gregorb6998662010-01-19 19:34:47 +00001868CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001869 if (clang_isInvalid(C.kind))
1870 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001871
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001872 ASTUnit *CXXUnit = getCursorASTUnit(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001873
Douglas Gregorb6998662010-01-19 19:34:47 +00001874 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00001875 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00001876 C = clang_getCursorReferenced(C);
1877 WasReference = true;
1878 }
1879
Douglas Gregorbf7efa22010-03-18 18:23:03 +00001880 if (C.kind == CXCursor_MacroInstantiation)
1881 return clang_getCursorReferenced(C);
1882
Douglas Gregorb6998662010-01-19 19:34:47 +00001883 if (!clang_isDeclaration(C.kind))
1884 return clang_getNullCursor();
1885
1886 Decl *D = getCursorDecl(C);
1887 if (!D)
1888 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001889
Douglas Gregorb6998662010-01-19 19:34:47 +00001890 switch (D->getKind()) {
1891 // Declaration kinds that don't really separate the notions of
1892 // declaration and definition.
1893 case Decl::Namespace:
1894 case Decl::Typedef:
1895 case Decl::TemplateTypeParm:
1896 case Decl::EnumConstant:
1897 case Decl::Field:
1898 case Decl::ObjCIvar:
1899 case Decl::ObjCAtDefsField:
1900 case Decl::ImplicitParam:
1901 case Decl::ParmVar:
1902 case Decl::NonTypeTemplateParm:
1903 case Decl::TemplateTemplateParm:
1904 case Decl::ObjCCategoryImpl:
1905 case Decl::ObjCImplementation:
1906 case Decl::LinkageSpec:
1907 case Decl::ObjCPropertyImpl:
1908 case Decl::FileScopeAsm:
1909 case Decl::StaticAssert:
1910 case Decl::Block:
1911 return C;
1912
1913 // Declaration kinds that don't make any sense here, but are
1914 // nonetheless harmless.
1915 case Decl::TranslationUnit:
1916 case Decl::Template:
1917 case Decl::ObjCContainer:
1918 break;
1919
1920 // Declaration kinds for which the definition is not resolvable.
1921 case Decl::UnresolvedUsingTypename:
1922 case Decl::UnresolvedUsingValue:
1923 break;
1924
1925 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001926 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
1927 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001928
1929 case Decl::NamespaceAlias:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001930 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001931
1932 case Decl::Enum:
1933 case Decl::Record:
1934 case Decl::CXXRecord:
1935 case Decl::ClassTemplateSpecialization:
1936 case Decl::ClassTemplatePartialSpecialization:
Douglas Gregor952b0172010-02-11 01:04:33 +00001937 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001938 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001939 return clang_getNullCursor();
1940
1941 case Decl::Function:
1942 case Decl::CXXMethod:
1943 case Decl::CXXConstructor:
1944 case Decl::CXXDestructor:
1945 case Decl::CXXConversion: {
1946 const FunctionDecl *Def = 0;
1947 if (cast<FunctionDecl>(D)->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001948 return MakeCXCursor(const_cast<FunctionDecl *>(Def), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001949 return clang_getNullCursor();
1950 }
1951
1952 case Decl::Var: {
Sebastian Redl31310a22010-02-01 20:16:42 +00001953 // Ask the variable if it has a definition.
1954 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
1955 return MakeCXCursor(Def, CXXUnit);
1956 return clang_getNullCursor();
Douglas Gregorb6998662010-01-19 19:34:47 +00001957 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001958
Douglas Gregorb6998662010-01-19 19:34:47 +00001959 case Decl::FunctionTemplate: {
1960 const FunctionDecl *Def = 0;
1961 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001962 return MakeCXCursor(Def->getDescribedFunctionTemplate(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001963 return clang_getNullCursor();
1964 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001965
Douglas Gregorb6998662010-01-19 19:34:47 +00001966 case Decl::ClassTemplate: {
1967 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
Douglas Gregor952b0172010-02-11 01:04:33 +00001968 ->getDefinition())
Douglas Gregorb6998662010-01-19 19:34:47 +00001969 return MakeCXCursor(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001970 cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001971 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001972 return clang_getNullCursor();
1973 }
1974
1975 case Decl::Using: {
1976 UsingDecl *Using = cast<UsingDecl>(D);
1977 CXCursor Def = clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001978 for (UsingDecl::shadow_iterator S = Using->shadow_begin(),
1979 SEnd = Using->shadow_end();
Douglas Gregorb6998662010-01-19 19:34:47 +00001980 S != SEnd; ++S) {
1981 if (Def != clang_getNullCursor()) {
1982 // FIXME: We have no way to return multiple results.
1983 return clang_getNullCursor();
1984 }
1985
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001986 Def = clang_getCursorDefinition(MakeCXCursor((*S)->getTargetDecl(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001987 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00001988 }
1989
1990 return Def;
1991 }
1992
1993 case Decl::UsingShadow:
1994 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001995 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001996 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00001997
1998 case Decl::ObjCMethod: {
1999 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
2000 if (Method->isThisDeclarationADefinition())
2001 return C;
2002
2003 // Dig out the method definition in the associated
2004 // @implementation, if we have it.
2005 // FIXME: The ASTs should make finding the definition easier.
2006 if (ObjCInterfaceDecl *Class
2007 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
2008 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
2009 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
2010 Method->isInstanceMethod()))
2011 if (Def->isThisDeclarationADefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002012 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002013
2014 return clang_getNullCursor();
2015 }
2016
2017 case Decl::ObjCCategory:
2018 if (ObjCCategoryImplDecl *Impl
2019 = cast<ObjCCategoryDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002020 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002021 return clang_getNullCursor();
2022
2023 case Decl::ObjCProtocol:
2024 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
2025 return C;
2026 return clang_getNullCursor();
2027
2028 case Decl::ObjCInterface:
2029 // There are two notions of a "definition" for an Objective-C
2030 // class: the interface and its implementation. When we resolved a
2031 // reference to an Objective-C class, produce the @interface as
2032 // the definition; when we were provided with the interface,
2033 // produce the @implementation as the definition.
2034 if (WasReference) {
2035 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
2036 return C;
2037 } else if (ObjCImplementationDecl *Impl
2038 = cast<ObjCInterfaceDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002039 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002040 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002041
Douglas Gregorb6998662010-01-19 19:34:47 +00002042 case Decl::ObjCProperty:
2043 // FIXME: We don't really know where to find the
2044 // ObjCPropertyImplDecls that implement this property.
2045 return clang_getNullCursor();
2046
2047 case Decl::ObjCCompatibleAlias:
2048 if (ObjCInterfaceDecl *Class
2049 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
2050 if (!Class->isForwardDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002051 return MakeCXCursor(Class, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002052
Douglas Gregorb6998662010-01-19 19:34:47 +00002053 return clang_getNullCursor();
2054
2055 case Decl::ObjCForwardProtocol: {
2056 ObjCForwardProtocolDecl *Forward = cast<ObjCForwardProtocolDecl>(D);
2057 if (Forward->protocol_size() == 1)
2058 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002059 MakeCXCursor(*Forward->protocol_begin(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002060 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002061
2062 // FIXME: Cannot return multiple definitions.
2063 return clang_getNullCursor();
2064 }
2065
2066 case Decl::ObjCClass: {
2067 ObjCClassDecl *Class = cast<ObjCClassDecl>(D);
2068 if (Class->size() == 1) {
2069 ObjCInterfaceDecl *IFace = Class->begin()->getInterface();
2070 if (!IFace->isForwardDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002071 return MakeCXCursor(IFace, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002072 return clang_getNullCursor();
2073 }
2074
2075 // FIXME: Cannot return multiple definitions.
2076 return clang_getNullCursor();
2077 }
2078
2079 case Decl::Friend:
2080 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002081 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002082 return clang_getNullCursor();
2083
2084 case Decl::FriendTemplate:
2085 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002086 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002087 return clang_getNullCursor();
2088 }
2089
2090 return clang_getNullCursor();
2091}
2092
2093unsigned clang_isCursorDefinition(CXCursor C) {
2094 if (!clang_isDeclaration(C.kind))
2095 return 0;
2096
2097 return clang_getCursorDefinition(C) == C;
2098}
2099
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002100void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00002101 const char **startBuf,
2102 const char **endBuf,
2103 unsigned *startLine,
2104 unsigned *startColumn,
2105 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002106 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00002107 assert(getCursorDecl(C) && "CXCursor has null decl");
2108 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00002109 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
2110 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002111
Steve Naroff4ade6d62009-09-23 17:52:52 +00002112 SourceManager &SM = FD->getASTContext().getSourceManager();
2113 *startBuf = SM.getCharacterData(Body->getLBracLoc());
2114 *endBuf = SM.getCharacterData(Body->getRBracLoc());
2115 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
2116 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
2117 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
2118 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
2119}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002120
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002121void clang_enableStackTraces(void) {
2122 llvm::sys::PrintStackTraceOnErrorSignal();
2123}
2124
Ted Kremenekfb480492010-01-13 21:46:36 +00002125} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00002126
Ted Kremenekfb480492010-01-13 21:46:36 +00002127//===----------------------------------------------------------------------===//
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002128// Token-based Operations.
2129//===----------------------------------------------------------------------===//
2130
2131/* CXToken layout:
2132 * int_data[0]: a CXTokenKind
2133 * int_data[1]: starting token location
2134 * int_data[2]: token length
2135 * int_data[3]: reserved
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002136 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002137 * otherwise unused.
2138 */
2139extern "C" {
2140
2141CXTokenKind clang_getTokenKind(CXToken CXTok) {
2142 return static_cast<CXTokenKind>(CXTok.int_data[0]);
2143}
2144
2145CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
2146 switch (clang_getTokenKind(CXTok)) {
2147 case CXToken_Identifier:
2148 case CXToken_Keyword:
2149 // We know we have an IdentifierInfo*, so use that.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002150 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
2151 ->getNameStart());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002152
2153 case CXToken_Literal: {
2154 // We have stashed the starting pointer in the ptr_data field. Use it.
2155 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002156 return createCXString(llvm::StringRef(Text, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002157 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002158
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002159 case CXToken_Punctuation:
2160 case CXToken_Comment:
2161 break;
2162 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002163
2164 // We have to find the starting buffer pointer the hard way, by
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002165 // deconstructing the source location.
2166 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2167 if (!CXXUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002168 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002169
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002170 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
2171 std::pair<FileID, unsigned> LocInfo
2172 = CXXUnit->getSourceManager().getDecomposedLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +00002173 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002174 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00002175 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
2176 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00002177 return createCXString("");
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002178
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002179 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002180}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002181
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002182CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
2183 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2184 if (!CXXUnit)
2185 return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002186
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002187 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
2188 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
2189}
2190
2191CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
2192 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregor5352ac02010-01-28 00:27:43 +00002193 if (!CXXUnit)
2194 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002195
2196 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002197 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
2198}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002199
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002200void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
2201 CXToken **Tokens, unsigned *NumTokens) {
2202 if (Tokens)
2203 *Tokens = 0;
2204 if (NumTokens)
2205 *NumTokens = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002206
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002207 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2208 if (!CXXUnit || !Tokens || !NumTokens)
2209 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002210
Douglas Gregorbdf60622010-03-05 21:16:25 +00002211 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
2212
Daniel Dunbar85b988f2010-02-14 08:31:57 +00002213 SourceRange R = cxloc::translateCXSourceRange(Range);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002214 if (R.isInvalid())
2215 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002216
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002217 SourceManager &SourceMgr = CXXUnit->getSourceManager();
2218 std::pair<FileID, unsigned> BeginLocInfo
2219 = SourceMgr.getDecomposedLoc(R.getBegin());
2220 std::pair<FileID, unsigned> EndLocInfo
2221 = SourceMgr.getDecomposedLoc(R.getEnd());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002222
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002223 // Cannot tokenize across files.
2224 if (BeginLocInfo.first != EndLocInfo.first)
2225 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002226
2227 // Create a lexer
Douglas Gregorf715ca12010-03-16 00:06:06 +00002228 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002229 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00002230 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
Douglas Gregor47a3fcd2010-03-16 20:26:15 +00002231 if (Invalid)
2232 return;
Douglas Gregoraea67db2010-03-15 22:54:52 +00002233
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002234 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
2235 CXXUnit->getASTContext().getLangOptions(),
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002236 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002237 Lex.SetCommentRetentionState(true);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002238
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002239 // Lex tokens until we hit the end of the range.
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002240 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002241 llvm::SmallVector<CXToken, 32> CXTokens;
2242 Token Tok;
2243 do {
2244 // Lex the next token
2245 Lex.LexFromRawLexer(Tok);
2246 if (Tok.is(tok::eof))
2247 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002248
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002249 // Initialize the CXToken.
2250 CXToken CXTok;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002251
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002252 // - Common fields
2253 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
2254 CXTok.int_data[2] = Tok.getLength();
2255 CXTok.int_data[3] = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002256
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002257 // - Kind-specific fields
2258 if (Tok.isLiteral()) {
2259 CXTok.int_data[0] = CXToken_Literal;
2260 CXTok.ptr_data = (void *)Tok.getLiteralData();
2261 } else if (Tok.is(tok::identifier)) {
Douglas Gregoraea67db2010-03-15 22:54:52 +00002262 // Lookup the identifier to determine whether we have a keyword.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002263 std::pair<FileID, unsigned> LocInfo
2264 = SourceMgr.getDecomposedLoc(Tok.getLocation());
Douglas Gregorf715ca12010-03-16 00:06:06 +00002265 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002266 llvm::StringRef Buf
Douglas Gregorf715ca12010-03-16 00:06:06 +00002267 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
2268 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00002269 return;
2270
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002271 const char *StartPos = Buf.data() + LocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002272 IdentifierInfo *II
2273 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok, StartPos);
2274 CXTok.int_data[0] = II->getTokenID() == tok::identifier?
2275 CXToken_Identifier
2276 : CXToken_Keyword;
2277 CXTok.ptr_data = II;
2278 } else if (Tok.is(tok::comment)) {
2279 CXTok.int_data[0] = CXToken_Comment;
2280 CXTok.ptr_data = 0;
2281 } else {
2282 CXTok.int_data[0] = CXToken_Punctuation;
2283 CXTok.ptr_data = 0;
2284 }
2285 CXTokens.push_back(CXTok);
2286 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002287
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002288 if (CXTokens.empty())
2289 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002290
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002291 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
2292 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
2293 *NumTokens = CXTokens.size();
2294}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002295
2296typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
2297
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002298enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
2299 CXCursor parent,
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002300 CXClientData client_data) {
2301 AnnotateTokensData *Data = static_cast<AnnotateTokensData *>(client_data);
2302
2303 // We only annotate the locations of declarations, simple
2304 // references, and expressions which directly reference something.
2305 CXCursorKind Kind = clang_getCursorKind(cursor);
2306 if (clang_isDeclaration(Kind) || clang_isReference(Kind)) {
2307 // Okay: We can annotate the location of this declaration with the
2308 // declaration or reference
2309 } else if (clang_isExpression(cursor.kind)) {
2310 if (Kind != CXCursor_DeclRefExpr &&
2311 Kind != CXCursor_MemberRefExpr &&
2312 Kind != CXCursor_ObjCMessageExpr)
2313 return CXChildVisit_Recurse;
2314
2315 CXCursor Referenced = clang_getCursorReferenced(cursor);
2316 if (Referenced == cursor || Referenced == clang_getNullCursor())
2317 return CXChildVisit_Recurse;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002318
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002319 // Okay: we can annotate the location of this expression
Douglas Gregor0396f462010-03-19 05:22:59 +00002320 } else if (clang_isPreprocessing(cursor.kind)) {
2321 // We can always annotate a preprocessing directive/macro instantiation.
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002322 } else {
2323 // Nothing to annotate
2324 return CXChildVisit_Recurse;
2325 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002326
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002327 CXSourceLocation Loc = clang_getCursorLocation(cursor);
2328 (*Data)[Loc.int_data] = cursor;
2329 return CXChildVisit_Recurse;
2330}
2331
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002332void clang_annotateTokens(CXTranslationUnit TU,
2333 CXToken *Tokens, unsigned NumTokens,
2334 CXCursor *Cursors) {
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002335 if (NumTokens == 0)
2336 return;
2337
2338 // Any token we don't specifically annotate will have a NULL cursor.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002339 for (unsigned I = 0; I != NumTokens; ++I)
2340 Cursors[I] = clang_getNullCursor();
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002341
2342 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2343 if (!CXXUnit || !Tokens)
2344 return;
2345
Douglas Gregorbdf60622010-03-05 21:16:25 +00002346 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
2347
Douglas Gregor0396f462010-03-19 05:22:59 +00002348 // Determine the region of interest, which contains all of the tokens.
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002349 SourceRange RegionOfInterest;
2350 RegionOfInterest.setBegin(
2351 cxloc::translateSourceLocation(clang_getTokenLocation(TU, Tokens[0])));
2352 SourceLocation End
Douglas Gregor09d9fa12010-04-05 16:10:30 +00002353 = cxloc::translateSourceLocation(clang_getTokenLocation(TU,
Douglas Gregor0396f462010-03-19 05:22:59 +00002354 Tokens[NumTokens - 1]));
Daniel Dunbard52864b2010-02-14 10:02:57 +00002355 RegionOfInterest.setEnd(CXXUnit->getPreprocessor().getLocForEndOfToken(End));
Douglas Gregor2507fa82010-03-19 00:18:31 +00002356
Douglas Gregor0396f462010-03-19 05:22:59 +00002357 // A mapping from the source locations found when re-lexing or traversing the
2358 // region of interest to the corresponding cursors.
2359 AnnotateTokensData Annotated;
2360
2361 // Relex the tokens within the source range to look for preprocessing
2362 // directives.
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002363 SourceManager &SourceMgr = CXXUnit->getSourceManager();
2364 std::pair<FileID, unsigned> BeginLocInfo
2365 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
2366 std::pair<FileID, unsigned> EndLocInfo
2367 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
2368
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002369 llvm::StringRef Buffer;
Douglas Gregor0396f462010-03-19 05:22:59 +00002370 bool Invalid = false;
2371 if (BeginLocInfo.first == EndLocInfo.first &&
2372 ((Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid)),true) &&
2373 !Invalid) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002374 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
2375 CXXUnit->getASTContext().getLangOptions(),
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002376 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
2377 Buffer.end());
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002378 Lex.SetCommentRetentionState(true);
2379
2380 // Lex tokens in raw mode until we hit the end of the range, to avoid
2381 // entering #includes or expanding macros.
Douglas Gregor48072312010-03-18 15:23:44 +00002382 while (true) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002383 Token Tok;
2384 Lex.LexFromRawLexer(Tok);
2385
2386 reprocess:
2387 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
2388 // We have found a preprocessing directive. Gobble it up so that we
2389 // don't see it while preprocessing these tokens later, but keep track of
2390 // all of the token locations inside this preprocessing directive so that
2391 // we can annotate them appropriately.
2392 //
2393 // FIXME: Some simple tests here could identify macro definitions and
2394 // #undefs, to provide specific cursor kinds for those.
2395 std::vector<SourceLocation> Locations;
2396 do {
2397 Locations.push_back(Tok.getLocation());
2398 Lex.LexFromRawLexer(Tok);
2399 } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
2400
2401 using namespace cxcursor;
2402 CXCursor Cursor
2403 = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
2404 Locations.back()),
2405 CXXUnit);
2406 for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
2407 Annotated[Locations[I].getRawEncoding()] = Cursor;
2408 }
2409
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002410 if (Tok.isAtStartOfLine())
2411 goto reprocess;
2412
2413 continue;
2414 }
2415
Douglas Gregor48072312010-03-18 15:23:44 +00002416 if (Tok.is(tok::eof))
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002417 break;
2418 }
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002419 }
Douglas Gregor0396f462010-03-19 05:22:59 +00002420
2421 // Annotate all of the source locations in the region of interest that map to
2422 // a specific cursor.
2423 CXCursor Parent = clang_getTranslationUnitCursor(CXXUnit);
2424 CursorVisitor AnnotateVis(CXXUnit, AnnotateTokensVisitor, &Annotated,
2425 Decl::MaxPCHLevel, RegionOfInterest);
2426 AnnotateVis.VisitChildren(Parent);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002427
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002428 for (unsigned I = 0; I != NumTokens; ++I) {
2429 // Determine whether we saw a cursor at this token's location.
2430 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
2431 if (Pos == Annotated.end())
2432 continue;
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002433
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002434 Cursors[I] = Pos->second;
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002435 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002436}
2437
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002438void clang_disposeTokens(CXTranslationUnit TU,
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002439 CXToken *Tokens, unsigned NumTokens) {
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002440 free(Tokens);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002441}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002442
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002443} // end: extern "C"
2444
2445//===----------------------------------------------------------------------===//
Ted Kremenek16b42592010-03-03 06:36:57 +00002446// Operations for querying linkage of a cursor.
2447//===----------------------------------------------------------------------===//
2448
2449extern "C" {
2450CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
Douglas Gregor0396f462010-03-19 05:22:59 +00002451 if (!clang_isDeclaration(cursor.kind))
2452 return CXLinkage_Invalid;
2453
Ted Kremenek16b42592010-03-03 06:36:57 +00002454 Decl *D = cxcursor::getCursorDecl(cursor);
2455 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
2456 switch (ND->getLinkage()) {
2457 case NoLinkage: return CXLinkage_NoLinkage;
2458 case InternalLinkage: return CXLinkage_Internal;
2459 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
2460 case ExternalLinkage: return CXLinkage_External;
2461 };
2462
2463 return CXLinkage_Invalid;
2464}
2465} // end: extern "C"
2466
2467//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00002468// CXString Operations.
2469//===----------------------------------------------------------------------===//
2470
2471extern "C" {
2472const char *clang_getCString(CXString string) {
2473 return string.Spelling;
2474}
2475
2476void clang_disposeString(CXString string) {
2477 if (string.MustFreeString && string.Spelling)
2478 free((void*)string.Spelling);
2479}
Ted Kremenek04bb7162010-01-22 22:44:15 +00002480
Ted Kremenekfb480492010-01-13 21:46:36 +00002481} // end: extern "C"
Ted Kremenek04bb7162010-01-22 22:44:15 +00002482
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002483namespace clang { namespace cxstring {
2484CXString createCXString(const char *String, bool DupString){
2485 CXString Str;
2486 if (DupString) {
2487 Str.Spelling = strdup(String);
2488 Str.MustFreeString = 1;
2489 } else {
2490 Str.Spelling = String;
2491 Str.MustFreeString = 0;
2492 }
2493 return Str;
2494}
2495
2496CXString createCXString(llvm::StringRef String, bool DupString) {
2497 CXString Result;
2498 if (DupString || (!String.empty() && String.data()[String.size()] != 0)) {
2499 char *Spelling = (char *)malloc(String.size() + 1);
2500 memmove(Spelling, String.data(), String.size());
2501 Spelling[String.size()] = 0;
2502 Result.Spelling = Spelling;
2503 Result.MustFreeString = 1;
2504 } else {
2505 Result.Spelling = String.data();
2506 Result.MustFreeString = 0;
2507 }
2508 return Result;
2509}
2510}}
2511
Ted Kremenek04bb7162010-01-22 22:44:15 +00002512//===----------------------------------------------------------------------===//
2513// Misc. utility functions.
2514//===----------------------------------------------------------------------===//
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002515
Ted Kremenek04bb7162010-01-22 22:44:15 +00002516extern "C" {
2517
Ted Kremeneka2a9d6e2010-02-12 22:54:40 +00002518CXString clang_getClangVersion() {
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002519 return createCXString(getClangFullVersion());
Ted Kremenek04bb7162010-01-22 22:44:15 +00002520}
2521
2522} // end: extern "C"