blob: 7d63d26b9206db3acee990ad45e71c70ee209715 [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"
Douglas Gregor936ea3b2010-01-28 00:56:43 +000025#include "clang/Frontend/FrontendDiagnostic.h"
Ted Kremenekd8210652010-01-06 23:43:31 +000026#include "clang/Lex/Lexer.h"
Douglas Gregor33e9abd2010-01-22 19:49:59 +000027#include "clang/Lex/Preprocessor.h"
Douglas Gregor02465752009-10-16 21:24:31 +000028#include "llvm/Support/MemoryBuffer.h"
Benjamin Kramer0829a832009-10-18 11:19:36 +000029#include "llvm/System/Program.h"
Douglas Gregor0a812cf2010-02-18 23:07:20 +000030#include "llvm/System/Signals.h"
Ted Kremenekfc062212009-10-19 21:44:57 +000031
Benjamin Kramerc2a98162010-03-13 21:22:49 +000032// Needed to define L_TMPNAM on some systems.
33#include <cstdio>
34
Steve Naroff50398192009-08-28 15:28:48 +000035using namespace clang;
Ted Kremenek16c440a2010-01-15 20:35:54 +000036using namespace clang::cxcursor;
Ted Kremenekee4db4f2010-02-17 00:41:08 +000037using namespace clang::cxstring;
Steve Naroff50398192009-08-28 15:28:48 +000038using namespace idx;
39
Ted Kremenek8a8da7d2010-01-06 03:42:32 +000040//===----------------------------------------------------------------------===//
41// Crash Reporting.
42//===----------------------------------------------------------------------===//
43
44#ifdef __APPLE__
Ted Kremenek29b72842010-01-07 22:49:05 +000045#define USE_CRASHTRACER
Ted Kremenek8a8da7d2010-01-06 03:42:32 +000046#include "clang/Analysis/Support/SaveAndRestore.h"
47// Integrate with crash reporter.
48extern "C" const char *__crashreporter_info__;
Ted Kremenek6b569992010-02-17 21:12:23 +000049#define NUM_CRASH_STRINGS 32
Ted Kremenek29b72842010-01-07 22:49:05 +000050static unsigned crashtracer_counter = 0;
Ted Kremenek254ba7c2010-01-07 23:13:53 +000051static unsigned crashtracer_counter_id[NUM_CRASH_STRINGS] = { 0 };
Ted Kremenek29b72842010-01-07 22:49:05 +000052static const char *crashtracer_strings[NUM_CRASH_STRINGS] = { 0 };
53static const char *agg_crashtracer_strings[NUM_CRASH_STRINGS] = { 0 };
54
55static unsigned SetCrashTracerInfo(const char *str,
56 llvm::SmallString<1024> &AggStr) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +000057
Ted Kremenek254ba7c2010-01-07 23:13:53 +000058 unsigned slot = 0;
Ted Kremenek29b72842010-01-07 22:49:05 +000059 while (crashtracer_strings[slot]) {
60 if (++slot == NUM_CRASH_STRINGS)
61 slot = 0;
62 }
63 crashtracer_strings[slot] = str;
Ted Kremenek254ba7c2010-01-07 23:13:53 +000064 crashtracer_counter_id[slot] = ++crashtracer_counter;
Ted Kremenek29b72842010-01-07 22:49:05 +000065
66 // We need to create an aggregate string because multiple threads
67 // may be in this method at one time. The crash reporter string
68 // will attempt to overapproximate the set of in-flight invocations
69 // of this function. Race conditions can still cause this goal
70 // to not be achieved.
71 {
Ted Kremenekf0e23e82010-02-17 00:41:40 +000072 llvm::raw_svector_ostream Out(AggStr);
Ted Kremenek29b72842010-01-07 22:49:05 +000073 for (unsigned i = 0; i < NUM_CRASH_STRINGS; ++i)
74 if (crashtracer_strings[i]) Out << crashtracer_strings[i] << '\n';
75 }
76 __crashreporter_info__ = agg_crashtracer_strings[slot] = AggStr.c_str();
77 return slot;
78}
79
80static void ResetCrashTracerInfo(unsigned slot) {
Ted Kremenek254ba7c2010-01-07 23:13:53 +000081 unsigned max_slot = 0;
82 unsigned max_value = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +000083
Ted Kremenek254ba7c2010-01-07 23:13:53 +000084 crashtracer_strings[slot] = agg_crashtracer_strings[slot] = 0;
85
86 for (unsigned i = 0 ; i < NUM_CRASH_STRINGS; ++i)
87 if (agg_crashtracer_strings[i] &&
88 crashtracer_counter_id[i] > max_value) {
89 max_slot = i;
90 max_value = crashtracer_counter_id[i];
Ted Kremenek29b72842010-01-07 22:49:05 +000091 }
Ted Kremenek254ba7c2010-01-07 23:13:53 +000092
93 __crashreporter_info__ = agg_crashtracer_strings[max_slot];
Ted Kremenek29b72842010-01-07 22:49:05 +000094}
95
96namespace {
97class ArgsCrashTracerInfo {
98 llvm::SmallString<1024> CrashString;
99 llvm::SmallString<1024> AggregateString;
100 unsigned crashtracerSlot;
101public:
102 ArgsCrashTracerInfo(llvm::SmallVectorImpl<const char*> &Args)
103 : crashtracerSlot(0)
104 {
105 {
106 llvm::raw_svector_ostream Out(CrashString);
Ted Kremenek0baa9522010-03-05 22:43:25 +0000107 Out << "ClangCIndex [" << getClangFullVersion() << "]"
108 << "[createTranslationUnitFromSourceFile]: clang";
Ted Kremenek29b72842010-01-07 22:49:05 +0000109 for (llvm::SmallVectorImpl<const char*>::iterator I=Args.begin(),
110 E=Args.end(); I!=E; ++I)
111 Out << ' ' << *I;
112 }
113 crashtracerSlot = SetCrashTracerInfo(CrashString.c_str(),
114 AggregateString);
115 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000116
Ted Kremenek29b72842010-01-07 22:49:05 +0000117 ~ArgsCrashTracerInfo() {
118 ResetCrashTracerInfo(crashtracerSlot);
119 }
120};
121}
122#endif
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000123
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000124/// \brief The result of comparing two source ranges.
125enum RangeComparisonResult {
126 /// \brief Either the ranges overlap or one of the ranges is invalid.
127 RangeOverlap,
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000128
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000129 /// \brief The first range ends before the second range starts.
130 RangeBefore,
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000131
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000132 /// \brief The first range starts after the second range ends.
133 RangeAfter
134};
135
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000136/// \brief Compare two source ranges to determine their relative position in
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000137/// the translation unit.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000138static RangeComparisonResult RangeCompare(SourceManager &SM,
139 SourceRange R1,
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000140 SourceRange R2) {
141 assert(R1.isValid() && "First range is invalid?");
142 assert(R2.isValid() && "Second range is invalid?");
Daniel Dunbard52864b2010-02-14 10:02:57 +0000143 if (R1.getEnd() == R2.getBegin() ||
144 SM.isBeforeInTranslationUnit(R1.getEnd(), R2.getBegin()))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000145 return RangeBefore;
Daniel Dunbard52864b2010-02-14 10:02:57 +0000146 if (R2.getEnd() == R1.getBegin() ||
147 SM.isBeforeInTranslationUnit(R2.getEnd(), R1.getBegin()))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000148 return RangeAfter;
149 return RangeOverlap;
150}
151
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000152/// \brief Translate a Clang source range into a CIndex source range.
153///
154/// Clang internally represents ranges where the end location points to the
155/// start of the token at the end. However, for external clients it is more
156/// useful to have a CXSourceRange be a proper half-open interval. This routine
157/// does the appropriate translation.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000158CXSourceRange cxloc::translateSourceRange(const SourceManager &SM,
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000159 const LangOptions &LangOpts,
160 SourceRange R) {
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000161 // We want the last character in this location, so we will adjust the
Douglas Gregor6a5a23f2010-03-19 21:51:54 +0000162 // location accordingly.
163 // FIXME: How do do this with a macro instantiation location?
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000164 SourceLocation EndLoc = R.getEnd();
Douglas Gregor6a5a23f2010-03-19 21:51:54 +0000165 if (!EndLoc.isInvalid() && EndLoc.isFileID()) {
166 unsigned Length = Lexer::MeasureTokenLength(EndLoc, SM, LangOpts);
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000167 EndLoc = EndLoc.getFileLocWithOffset(Length);
168 }
169
170 CXSourceRange Result = { { (void *)&SM, (void *)&LangOpts },
171 R.getBegin().getRawEncoding(),
172 EndLoc.getRawEncoding() };
173 return Result;
174}
Douglas Gregor1db19de2010-01-19 21:36:55 +0000175
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000176//===----------------------------------------------------------------------===//
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000177// Cursor visitor.
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000178//===----------------------------------------------------------------------===//
179
Steve Naroff89922f82009-08-31 00:59:03 +0000180namespace {
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000181
Douglas Gregorb1373d02010-01-20 20:59:29 +0000182// Cursor visitor.
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000183class CursorVisitor : public DeclVisitor<CursorVisitor, bool>,
Douglas Gregora59e3902010-01-21 23:27:09 +0000184 public TypeLocVisitor<CursorVisitor, bool>,
185 public StmtVisitor<CursorVisitor, bool>
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000186{
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000187 /// \brief The translation unit we are traversing.
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000188 ASTUnit *TU;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000189
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000190 /// \brief The parent cursor whose children we are traversing.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000191 CXCursor Parent;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000192
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000193 /// \brief The declaration that serves at the parent of any statement or
194 /// expression nodes.
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000195 Decl *StmtParent;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000196
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000197 /// \brief The visitor function.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000198 CXCursorVisitor Visitor;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000199
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000200 /// \brief The opaque client data, to be passed along to the visitor.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000201 CXClientData ClientData;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000202
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000203 // MaxPCHLevel - the maximum PCH level of declarations that we will pass on
204 // to the visitor. Declarations with a PCH level greater than this value will
205 // be suppressed.
206 unsigned MaxPCHLevel;
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000207
208 /// \brief When valid, a source range to which the cursor should restrict
209 /// its search.
210 SourceRange RegionOfInterest;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000211
Douglas Gregorb1373d02010-01-20 20:59:29 +0000212 using DeclVisitor<CursorVisitor, bool>::Visit;
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000213 using TypeLocVisitor<CursorVisitor, bool>::Visit;
Douglas Gregora59e3902010-01-21 23:27:09 +0000214 using StmtVisitor<CursorVisitor, bool>::Visit;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000215
216 /// \brief Determine whether this particular source range comes before, comes
217 /// after, or overlaps the region of interest.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000218 ///
Daniel Dunbard52864b2010-02-14 10:02:57 +0000219 /// \param R a half-open source range retrieved from the abstract syntax tree.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000220 RangeComparisonResult CompareRegionOfInterest(SourceRange R);
221
Steve Naroff89922f82009-08-31 00:59:03 +0000222public:
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000223 CursorVisitor(ASTUnit *TU, CXCursorVisitor Visitor, CXClientData ClientData,
224 unsigned MaxPCHLevel,
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000225 SourceRange RegionOfInterest = SourceRange())
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000226 : TU(TU), Visitor(Visitor), ClientData(ClientData),
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000227 MaxPCHLevel(MaxPCHLevel), RegionOfInterest(RegionOfInterest)
Douglas Gregorb1373d02010-01-20 20:59:29 +0000228 {
229 Parent.kind = CXCursor_NoDeclFound;
230 Parent.data[0] = 0;
231 Parent.data[1] = 0;
232 Parent.data[2] = 0;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000233 StmtParent = 0;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000234 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000235
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000236 bool Visit(CXCursor Cursor, bool CheckedRegionOfInterest = false);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000237 bool VisitChildren(CXCursor Parent);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000238
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000239 // Declaration visitors
Ted Kremenek09dfa372010-02-18 05:46:33 +0000240 bool VisitAttributes(Decl *D);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000241 bool VisitDeclContext(DeclContext *DC);
Ted Kremenek4540c9c2010-02-18 18:47:08 +0000242 bool VisitTranslationUnitDecl(TranslationUnitDecl *D);
243 bool VisitTypedefDecl(TypedefDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000244 bool VisitTagDecl(TagDecl *D);
245 bool VisitEnumConstantDecl(EnumConstantDecl *D);
246 bool VisitDeclaratorDecl(DeclaratorDecl *DD);
247 bool VisitFunctionDecl(FunctionDecl *ND);
248 bool VisitFieldDecl(FieldDecl *D);
Ted Kremenek4540c9c2010-02-18 18:47:08 +0000249 bool VisitVarDecl(VarDecl *);
Ted Kremenek79758f62010-02-18 22:36:18 +0000250 bool VisitObjCMethodDecl(ObjCMethodDecl *ND);
251 bool VisitObjCContainerDecl(ObjCContainerDecl *D);
252 bool VisitObjCCategoryDecl(ObjCCategoryDecl *ND);
253 bool VisitObjCProtocolDecl(ObjCProtocolDecl *PID);
254 bool VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
255 bool VisitObjCImplDecl(ObjCImplDecl *D);
256 bool VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
257 bool VisitObjCImplementationDecl(ObjCImplementationDecl *D);
258 // FIXME: ObjCPropertyDecl requires TypeSourceInfo, getter/setter locations,
259 // etc.
260 // FIXME: ObjCCompatibleAliasDecl requires aliased-class locations.
261 bool VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D);
262 bool VisitObjCClassDecl(ObjCClassDecl *D);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000263
264 // Type visitors
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000265 // FIXME: QualifiedTypeLoc doesn't provide any location information
266 bool VisitBuiltinTypeLoc(BuiltinTypeLoc TL);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000267 bool VisitTypedefTypeLoc(TypedefTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000268 bool VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL);
269 bool VisitTagTypeLoc(TagTypeLoc TL);
270 // FIXME: TemplateTypeParmTypeLoc doesn't provide any location information
271 bool VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL);
272 bool VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL);
273 bool VisitPointerTypeLoc(PointerTypeLoc TL);
274 bool VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL);
275 bool VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL);
276 bool VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL);
277 bool VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL);
278 bool VisitFunctionTypeLoc(FunctionTypeLoc TL);
279 bool VisitArrayTypeLoc(ArrayTypeLoc TL);
Douglas Gregor2332c112010-01-21 20:48:56 +0000280 // FIXME: Implement for TemplateSpecializationTypeLoc
281 // FIXME: Implement visitors here when the unimplemented TypeLocs get
282 // implemented
283 bool VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL);
284 bool VisitTypeOfTypeLoc(TypeOfTypeLoc TL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000285
Douglas Gregora59e3902010-01-21 23:27:09 +0000286 // Statement visitors
287 bool VisitStmt(Stmt *S);
288 bool VisitDeclStmt(DeclStmt *S);
Douglas Gregorf5bab412010-01-22 01:00:11 +0000289 // FIXME: LabelStmt label?
290 bool VisitIfStmt(IfStmt *S);
291 bool VisitSwitchStmt(SwitchStmt *S);
Douglas Gregor263b47b2010-01-25 16:12:32 +0000292 bool VisitWhileStmt(WhileStmt *S);
293 bool VisitForStmt(ForStmt *S);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000294
Douglas Gregor336fd812010-01-23 00:40:08 +0000295 // Expression visitors
296 bool VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E);
297 bool VisitExplicitCastExpr(ExplicitCastExpr *E);
298 bool VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
Douglas Gregorc2350e52010-03-08 16:40:19 +0000299 bool VisitObjCMessageExpr(ObjCMessageExpr *E);
Steve Naroff89922f82009-08-31 00:59:03 +0000300};
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000301
Ted Kremenekab188932010-01-05 19:32:54 +0000302} // end anonymous namespace
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000303
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000304RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000305 return RangeCompare(TU->getSourceManager(), R, RegionOfInterest);
306}
307
Douglas Gregorb1373d02010-01-20 20:59:29 +0000308/// \brief Visit the given cursor and, if requested by the visitor,
309/// its children.
310///
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000311/// \param Cursor the cursor to visit.
312///
313/// \param CheckRegionOfInterest if true, then the caller already checked that
314/// this cursor is within the region of interest.
315///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000316/// \returns true if the visitation should be aborted, false if it
317/// should continue.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000318bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
Douglas Gregorb1373d02010-01-20 20:59:29 +0000319 if (clang_isInvalid(Cursor.kind))
320 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000321
Douglas Gregorb1373d02010-01-20 20:59:29 +0000322 if (clang_isDeclaration(Cursor.kind)) {
323 Decl *D = getCursorDecl(Cursor);
324 assert(D && "Invalid declaration cursor");
325 if (D->getPCHLevel() > MaxPCHLevel)
326 return false;
327
328 if (D->isImplicit())
329 return false;
330 }
331
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000332 // If we have a range of interest, and this cursor doesn't intersect with it,
333 // we're done.
334 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
Daniel Dunbarf408f322010-02-14 08:32:05 +0000335 SourceRange Range =
336 cxloc::translateCXSourceRange(clang_getCursorExtent(Cursor));
337 if (Range.isInvalid() || CompareRegionOfInterest(Range))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000338 return false;
339 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000340
Douglas Gregorb1373d02010-01-20 20:59:29 +0000341 switch (Visitor(Cursor, Parent, ClientData)) {
342 case CXChildVisit_Break:
343 return true;
344
345 case CXChildVisit_Continue:
346 return false;
347
348 case CXChildVisit_Recurse:
349 return VisitChildren(Cursor);
350 }
351
Douglas Gregorfd643772010-01-25 16:45:46 +0000352 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000353}
354
355/// \brief Visit the children of the given cursor.
356///
357/// \returns true if the visitation should be aborted, false if it
358/// should continue.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000359bool CursorVisitor::VisitChildren(CXCursor Cursor) {
Douglas Gregora59e3902010-01-21 23:27:09 +0000360 if (clang_isReference(Cursor.kind)) {
361 // By definition, references have no children.
362 return false;
363 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000364
365 // Set the Parent field to Cursor, then back to its old value once we're
Douglas Gregorb1373d02010-01-20 20:59:29 +0000366 // done.
367 class SetParentRAII {
368 CXCursor &Parent;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000369 Decl *&StmtParent;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000370 CXCursor OldParent;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000371
Douglas Gregorb1373d02010-01-20 20:59:29 +0000372 public:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000373 SetParentRAII(CXCursor &Parent, Decl *&StmtParent, CXCursor NewParent)
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000374 : Parent(Parent), StmtParent(StmtParent), OldParent(Parent)
Douglas Gregorb1373d02010-01-20 20:59:29 +0000375 {
376 Parent = NewParent;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000377 if (clang_isDeclaration(Parent.kind))
378 StmtParent = getCursorDecl(Parent);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000379 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000380
Douglas Gregorb1373d02010-01-20 20:59:29 +0000381 ~SetParentRAII() {
382 Parent = OldParent;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000383 if (clang_isDeclaration(Parent.kind))
384 StmtParent = getCursorDecl(Parent);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000385 }
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000386 } SetParent(Parent, StmtParent, Cursor);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000387
Douglas Gregorb1373d02010-01-20 20:59:29 +0000388 if (clang_isDeclaration(Cursor.kind)) {
389 Decl *D = getCursorDecl(Cursor);
390 assert(D && "Invalid declaration cursor");
Ted Kremenek539311e2010-02-18 18:47:01 +0000391 return VisitAttributes(D) || Visit(D);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000392 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000393
Douglas Gregora59e3902010-01-21 23:27:09 +0000394 if (clang_isStatement(Cursor.kind))
395 return Visit(getCursorStmt(Cursor));
396 if (clang_isExpression(Cursor.kind))
397 return Visit(getCursorExpr(Cursor));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000398
Douglas Gregorb1373d02010-01-20 20:59:29 +0000399 if (clang_isTranslationUnit(Cursor.kind)) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000400 ASTUnit *CXXUnit = getCursorASTUnit(Cursor);
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000401 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
402 RegionOfInterest.isInvalid()) {
Douglas Gregor7b691f332010-01-20 21:13:59 +0000403 const std::vector<Decl*> &TLDs = CXXUnit->getTopLevelDecls();
404 for (std::vector<Decl*>::const_iterator it = TLDs.begin(),
405 ie = TLDs.end(); it != ie; ++it) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000406 if (Visit(MakeCXCursor(*it, CXXUnit), true))
Douglas Gregor7b691f332010-01-20 21:13:59 +0000407 return true;
408 }
Douglas Gregor0396f462010-03-19 05:22:59 +0000409 } else if (VisitDeclContext(
410 CXXUnit->getASTContext().getTranslationUnitDecl()))
411 return true;
Bob Wilson3178cb62010-03-19 03:57:57 +0000412
Douglas Gregor0396f462010-03-19 05:22:59 +0000413 // Walk the preprocessing record.
Douglas Gregor94dc8f62010-03-19 16:15:56 +0000414 if (PreprocessingRecord *PPRec
415 = CXXUnit->getPreprocessor().getPreprocessingRecord()) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000416 // FIXME: Once we have the ability to deserialize a preprocessing record,
417 // do so.
Douglas Gregor6a5a23f2010-03-19 21:51:54 +0000418 bool OnlyLocalDecls
419 = !CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls();
420 for (PreprocessingRecord::iterator
421 E = PPRec->begin(OnlyLocalDecls),
422 EEnd = PPRec->end(OnlyLocalDecls);
Douglas Gregor0396f462010-03-19 05:22:59 +0000423 E != EEnd; ++E) {
424 if (MacroInstantiation *MI = dyn_cast<MacroInstantiation>(*E)) {
425 if (Visit(MakeMacroInstantiationCursor(MI, CXXUnit)))
426 return true;
427 continue;
428 }
429
430 if (MacroDefinition *MD = dyn_cast<MacroDefinition>(*E)) {
431 if (Visit(MakeMacroDefinitionCursor(MD, CXXUnit)))
432 return true;
433
434 continue;
435 }
436 }
437 }
Douglas Gregor7b691f332010-01-20 21:13:59 +0000438 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000439 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000440
Douglas Gregorb1373d02010-01-20 20:59:29 +0000441 // Nothing to visit at the moment.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000442 return false;
443}
444
Douglas Gregorb1373d02010-01-20 20:59:29 +0000445bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000446 for (DeclContext::decl_iterator
Douglas Gregorb1373d02010-01-20 20:59:29 +0000447 I = DC->decls_begin(), E = DC->decls_end(); I != E; ++I) {
Ted Kremenek09dfa372010-02-18 05:46:33 +0000448
Daniel Dunbard52864b2010-02-14 10:02:57 +0000449 CXCursor Cursor = MakeCXCursor(*I, TU);
450
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000451 if (RegionOfInterest.isValid()) {
Daniel Dunbard52864b2010-02-14 10:02:57 +0000452 SourceRange Range =
453 cxloc::translateCXSourceRange(clang_getCursorExtent(Cursor));
454 if (Range.isInvalid())
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000455 continue;
Daniel Dunbard52864b2010-02-14 10:02:57 +0000456
457 switch (CompareRegionOfInterest(Range)) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000458 case RangeBefore:
459 // This declaration comes before the region of interest; skip it.
460 continue;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000461
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000462 case RangeAfter:
463 // This declaration comes after the region of interest; we're done.
464 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000465
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000466 case RangeOverlap:
467 // This declaration overlaps the region of interest; visit it.
468 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000469 }
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000470 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000471
Daniel Dunbard52864b2010-02-14 10:02:57 +0000472 if (Visit(Cursor, true))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000473 return true;
474 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000475
Douglas Gregorb1373d02010-01-20 20:59:29 +0000476 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000477}
478
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000479bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
480 llvm_unreachable("Translation units are visited directly by Visit()");
481 return false;
482}
483
484bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
485 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
486 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000487
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000488 return false;
489}
490
491bool CursorVisitor::VisitTagDecl(TagDecl *D) {
492 return VisitDeclContext(D);
493}
494
495bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
496 if (Expr *Init = D->getInitExpr())
497 return Visit(MakeCXCursor(Init, StmtParent, TU));
498 return false;
499}
500
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000501bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
502 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
503 if (Visit(TSInfo->getTypeLoc()))
504 return true;
505
506 return false;
507}
508
Douglas Gregorb1373d02010-01-20 20:59:29 +0000509bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000510 if (VisitDeclaratorDecl(ND))
511 return true;
512
Douglas Gregora59e3902010-01-21 23:27:09 +0000513 if (ND->isThisDeclarationADefinition() &&
514 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
515 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000516
Douglas Gregorb1373d02010-01-20 20:59:29 +0000517 return false;
518}
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000519
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000520bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
521 if (VisitDeclaratorDecl(D))
522 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000523
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000524 if (Expr *BitWidth = D->getBitWidth())
525 return Visit(MakeCXCursor(BitWidth, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000526
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000527 return false;
528}
529
530bool CursorVisitor::VisitVarDecl(VarDecl *D) {
531 if (VisitDeclaratorDecl(D))
532 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000533
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000534 if (Expr *Init = D->getInit())
535 return Visit(MakeCXCursor(Init, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000536
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000537 return false;
538}
539
540bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
Douglas Gregor4bc1cb62010-03-08 14:59:44 +0000541 if (TypeSourceInfo *TSInfo = ND->getResultTypeSourceInfo())
542 if (Visit(TSInfo->getTypeLoc()))
543 return true;
544
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000545 for (ObjCMethodDecl::param_iterator P = ND->param_begin(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000546 PEnd = ND->param_end();
547 P != PEnd; ++P) {
548 if (Visit(MakeCXCursor(*P, TU)))
549 return true;
550 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000551
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000552 if (ND->isThisDeclarationADefinition() &&
553 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
554 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000555
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000556 return false;
557}
558
Douglas Gregora59e3902010-01-21 23:27:09 +0000559bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
560 return VisitDeclContext(D);
561}
562
Douglas Gregorb1373d02010-01-20 20:59:29 +0000563bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000564 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
565 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000566 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000567
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000568 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
569 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
570 E = ND->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000571 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000572 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000573
Douglas Gregora59e3902010-01-21 23:27:09 +0000574 return VisitObjCContainerDecl(ND);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000575}
576
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000577bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
578 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
579 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
580 E = PID->protocol_end(); I != E; ++I, ++PL)
581 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
582 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000583
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000584 return VisitObjCContainerDecl(PID);
585}
586
Douglas Gregorb1373d02010-01-20 20:59:29 +0000587bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000588 // Issue callbacks for super class.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000589 if (D->getSuperClass() &&
590 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000591 D->getSuperClassLoc(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000592 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000593 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000594
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000595 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
596 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
597 E = D->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000598 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000599 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000600
Douglas Gregora59e3902010-01-21 23:27:09 +0000601 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000602}
603
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000604bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
605 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000606}
607
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000608bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
Ted Kremenekebfa3392010-03-19 20:39:03 +0000609 // 'ID' could be null when dealing with invalid code.
610 if (ObjCInterfaceDecl *ID = D->getClassInterface())
611 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
612 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000613
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000614 return VisitObjCImplDecl(D);
615}
616
617bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
618#if 0
619 // Issue callbacks for super class.
620 // FIXME: No source location information!
621 if (D->getSuperClass() &&
622 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000623 D->getSuperClassLoc(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000624 TU)))
625 return true;
626#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000627
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000628 return VisitObjCImplDecl(D);
629}
630
631bool CursorVisitor::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D) {
632 ObjCForwardProtocolDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
633 for (ObjCForwardProtocolDecl::protocol_iterator I = D->protocol_begin(),
634 E = D->protocol_end();
635 I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000636 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000637 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000638
639 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000640}
641
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000642bool CursorVisitor::VisitObjCClassDecl(ObjCClassDecl *D) {
643 for (ObjCClassDecl::iterator C = D->begin(), CEnd = D->end(); C != CEnd; ++C)
644 if (Visit(MakeCursorObjCClassRef(C->getInterface(), C->getLocation(), TU)))
645 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000646
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000647 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000648}
649
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000650bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
651 ASTContext &Context = TU->getASTContext();
652
653 // Some builtin types (such as Objective-C's "id", "sel", and
654 // "Class") have associated declarations. Create cursors for those.
655 QualType VisitType;
656 switch (TL.getType()->getAs<BuiltinType>()->getKind()) {
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000657 case BuiltinType::Void:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000658 case BuiltinType::Bool:
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000659 case BuiltinType::Char_U:
660 case BuiltinType::UChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000661 case BuiltinType::Char16:
662 case BuiltinType::Char32:
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000663 case BuiltinType::UShort:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000664 case BuiltinType::UInt:
665 case BuiltinType::ULong:
666 case BuiltinType::ULongLong:
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000667 case BuiltinType::UInt128:
668 case BuiltinType::Char_S:
669 case BuiltinType::SChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000670 case BuiltinType::WChar:
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000671 case BuiltinType::Short:
672 case BuiltinType::Int:
673 case BuiltinType::Long:
674 case BuiltinType::LongLong:
675 case BuiltinType::Int128:
676 case BuiltinType::Float:
677 case BuiltinType::Double:
678 case BuiltinType::LongDouble:
679 case BuiltinType::NullPtr:
680 case BuiltinType::Overload:
681 case BuiltinType::Dependent:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000682 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000683
684 case BuiltinType::UndeducedAuto: // FIXME: Deserves a cursor?
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000685 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000686
Ted Kremenekc4174cc2010-02-18 18:52:18 +0000687 case BuiltinType::ObjCId:
688 VisitType = Context.getObjCIdType();
689 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000690
691 case BuiltinType::ObjCClass:
692 VisitType = Context.getObjCClassType();
693 break;
694
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000695 case BuiltinType::ObjCSel:
696 VisitType = Context.getObjCSelType();
697 break;
698 }
699
700 if (!VisitType.isNull()) {
701 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000702 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000703 TU));
704 }
705
706 return false;
707}
708
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000709bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
710 return Visit(MakeCursorTypeRef(TL.getTypedefDecl(), TL.getNameLoc(), TU));
711}
712
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000713bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
714 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
715}
716
717bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
718 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
719}
720
721bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
722 if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
723 return true;
724
725 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
726 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
727 TU)))
728 return true;
729 }
730
731 return false;
732}
733
734bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
735 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseTypeLoc()))
736 return true;
737
738 if (TL.hasProtocolsAsWritten()) {
739 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000740 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I),
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000741 TL.getProtocolLoc(I),
742 TU)))
743 return true;
744 }
745 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000746
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000747 return false;
748}
749
750bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
751 return Visit(TL.getPointeeLoc());
752}
753
754bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
755 return Visit(TL.getPointeeLoc());
756}
757
758bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
759 return Visit(TL.getPointeeLoc());
760}
761
762bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000763 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000764}
765
766bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000767 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000768}
769
770bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
771 if (Visit(TL.getResultLoc()))
772 return true;
773
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000774 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
775 if (Visit(MakeCXCursor(TL.getArg(I), TU)))
776 return true;
777
778 return false;
779}
780
781bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
782 if (Visit(TL.getElementLoc()))
783 return true;
784
785 if (Expr *Size = TL.getSizeExpr())
786 return Visit(MakeCXCursor(Size, StmtParent, TU));
787
788 return false;
789}
790
Douglas Gregor2332c112010-01-21 20:48:56 +0000791bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
792 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
793}
794
795bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
796 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
797 return Visit(TSInfo->getTypeLoc());
798
799 return false;
800}
801
Douglas Gregora59e3902010-01-21 23:27:09 +0000802bool CursorVisitor::VisitStmt(Stmt *S) {
803 for (Stmt::child_iterator Child = S->child_begin(), ChildEnd = S->child_end();
804 Child != ChildEnd; ++Child) {
Daniel Dunbar54d67ca2010-01-25 00:40:30 +0000805 if (*Child && Visit(MakeCXCursor(*Child, StmtParent, TU)))
Douglas Gregora59e3902010-01-21 23:27:09 +0000806 return true;
807 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000808
Douglas Gregora59e3902010-01-21 23:27:09 +0000809 return false;
810}
811
812bool CursorVisitor::VisitDeclStmt(DeclStmt *S) {
813 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
814 D != DEnd; ++D) {
Douglas Gregor263b47b2010-01-25 16:12:32 +0000815 if (*D && Visit(MakeCXCursor(*D, TU)))
Douglas Gregora59e3902010-01-21 23:27:09 +0000816 return true;
817 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000818
Douglas Gregora59e3902010-01-21 23:27:09 +0000819 return false;
820}
821
Douglas Gregorf5bab412010-01-22 01:00:11 +0000822bool CursorVisitor::VisitIfStmt(IfStmt *S) {
823 if (VarDecl *Var = S->getConditionVariable()) {
824 if (Visit(MakeCXCursor(Var, TU)))
825 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000826 }
827
Douglas Gregor263b47b2010-01-25 16:12:32 +0000828 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
829 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +0000830 if (S->getThen() && Visit(MakeCXCursor(S->getThen(), StmtParent, TU)))
831 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +0000832 if (S->getElse() && Visit(MakeCXCursor(S->getElse(), StmtParent, TU)))
833 return true;
834
835 return false;
836}
837
838bool CursorVisitor::VisitSwitchStmt(SwitchStmt *S) {
839 if (VarDecl *Var = S->getConditionVariable()) {
840 if (Visit(MakeCXCursor(Var, TU)))
841 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000842 }
843
Douglas Gregor263b47b2010-01-25 16:12:32 +0000844 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
845 return true;
846 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
847 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000848
Douglas Gregor263b47b2010-01-25 16:12:32 +0000849 return false;
850}
851
852bool CursorVisitor::VisitWhileStmt(WhileStmt *S) {
853 if (VarDecl *Var = S->getConditionVariable()) {
854 if (Visit(MakeCXCursor(Var, TU)))
855 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000856 }
857
Douglas Gregor263b47b2010-01-25 16:12:32 +0000858 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
859 return true;
860 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
Douglas Gregorf5bab412010-01-22 01:00:11 +0000861 return true;
862
Douglas Gregor263b47b2010-01-25 16:12:32 +0000863 return false;
864}
865
866bool CursorVisitor::VisitForStmt(ForStmt *S) {
867 if (S->getInit() && Visit(MakeCXCursor(S->getInit(), StmtParent, TU)))
868 return true;
869 if (VarDecl *Var = S->getConditionVariable()) {
870 if (Visit(MakeCXCursor(Var, TU)))
871 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000872 }
873
Douglas Gregor263b47b2010-01-25 16:12:32 +0000874 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
875 return true;
876 if (S->getInc() && Visit(MakeCXCursor(S->getInc(), StmtParent, TU)))
877 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +0000878 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
879 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000880
Douglas Gregorf5bab412010-01-22 01:00:11 +0000881 return false;
882}
883
Douglas Gregor336fd812010-01-23 00:40:08 +0000884bool CursorVisitor::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E) {
885 if (E->isArgumentType()) {
886 if (TypeSourceInfo *TSInfo = E->getArgumentTypeInfo())
887 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000888
Douglas Gregor336fd812010-01-23 00:40:08 +0000889 return false;
890 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000891
Douglas Gregor336fd812010-01-23 00:40:08 +0000892 return VisitExpr(E);
893}
894
895bool CursorVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
896 if (TypeSourceInfo *TSInfo = E->getTypeInfoAsWritten())
897 if (Visit(TSInfo->getTypeLoc()))
898 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000899
Douglas Gregor336fd812010-01-23 00:40:08 +0000900 return VisitCastExpr(E);
901}
902
903bool CursorVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
904 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
905 if (Visit(TSInfo->getTypeLoc()))
906 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000907
Douglas Gregor336fd812010-01-23 00:40:08 +0000908 return VisitExpr(E);
909}
910
Douglas Gregorc2350e52010-03-08 16:40:19 +0000911bool CursorVisitor::VisitObjCMessageExpr(ObjCMessageExpr *E) {
912 ObjCMessageExpr::ClassInfo CI = E->getClassInfo();
913 if (CI.Decl && Visit(MakeCursorObjCClassRef(CI.Decl, CI.Loc, TU)))
914 return true;
915
916 return VisitExpr(E);
917}
918
Ted Kremenek09dfa372010-02-18 05:46:33 +0000919bool CursorVisitor::VisitAttributes(Decl *D) {
920 for (const Attr *A = D->getAttrs(); A; A = A->getNext())
921 if (Visit(MakeCXCursor(A, D, TU)))
922 return true;
923
924 return false;
925}
926
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000927extern "C" {
Douglas Gregor0a812cf2010-02-18 23:07:20 +0000928CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
929 int displayDiagnostics) {
Douglas Gregora030b7c2010-01-22 20:35:53 +0000930 CIndexer *CIdxr = new CIndexer();
Steve Naroffe56b4ba2009-10-20 14:46:24 +0000931 if (excludeDeclarationsFromPCH)
932 CIdxr->setOnlyLocalDecls();
Douglas Gregor0a812cf2010-02-18 23:07:20 +0000933 if (displayDiagnostics)
934 CIdxr->setDisplayDiagnostics();
Steve Naroffe56b4ba2009-10-20 14:46:24 +0000935 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +0000936}
937
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000938void clang_disposeIndex(CXIndex CIdx) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +0000939 if (CIdx)
940 delete static_cast<CIndexer *>(CIdx);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +0000941}
942
Daniel Dunbar8506dde2009-12-03 01:54:28 +0000943void clang_setUseExternalASTGeneration(CXIndex CIdx, int value) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +0000944 if (CIdx) {
945 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
946 CXXIdx->setUseExternalASTGeneration(value);
947 }
Daniel Dunbar8506dde2009-12-03 01:54:28 +0000948}
949
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000950CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
Douglas Gregora88084b2010-02-18 18:08:43 +0000951 const char *ast_filename) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +0000952 if (!CIdx)
953 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000954
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000955 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000956
Douglas Gregor5352ac02010-01-28 00:27:43 +0000957 // Configure the diagnostics.
958 DiagnosticOptions DiagOpts;
959 llvm::OwningPtr<Diagnostic> Diags;
960 Diags.reset(CompilerInstance::createDiagnostics(DiagOpts, 0, 0));
Douglas Gregor5352ac02010-01-28 00:27:43 +0000961 return ASTUnit::LoadFromPCHFile(ast_filename, *Diags,
Douglas Gregora88084b2010-02-18 18:08:43 +0000962 CXXIdx->getOnlyLocalDecls(),
963 0, 0, true);
Steve Naroff600866c2009-08-27 19:51:58 +0000964}
965
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000966CXTranslationUnit
967clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
968 const char *source_filename,
969 int num_command_line_args,
Douglas Gregor4db64a42010-01-23 00:14:00 +0000970 const char **command_line_args,
971 unsigned num_unsaved_files,
Douglas Gregora88084b2010-02-18 18:08:43 +0000972 struct CXUnsavedFile *unsaved_files) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +0000973 if (!CIdx)
974 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000975
Steve Naroffe56b4ba2009-10-20 14:46:24 +0000976 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
977
Douglas Gregor5352ac02010-01-28 00:27:43 +0000978 // Configure the diagnostics.
979 DiagnosticOptions DiagOpts;
980 llvm::OwningPtr<Diagnostic> Diags;
981 Diags.reset(CompilerInstance::createDiagnostics(DiagOpts, 0, 0));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000982
Douglas Gregor4db64a42010-01-23 00:14:00 +0000983 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
984 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000985 const llvm::MemoryBuffer *Buffer
Douglas Gregorc8dfe5e2010-02-27 01:32:48 +0000986 = llvm::MemoryBuffer::getMemBufferCopy(unsaved_files[I].Contents,
Douglas Gregor313e26c2010-02-18 23:35:40 +0000987 unsaved_files[I].Contents + unsaved_files[I].Length,
988 unsaved_files[I].Filename);
Douglas Gregor4db64a42010-01-23 00:14:00 +0000989 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
990 Buffer));
991 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000992
Daniel Dunbar8506dde2009-12-03 01:54:28 +0000993 if (!CXXIdx->getUseExternalASTGeneration()) {
994 llvm::SmallVector<const char *, 16> Args;
995
996 // The 'source_filename' argument is optional. If the caller does not
997 // specify it then it is assumed that the source file is specified
998 // in the actual argument list.
999 if (source_filename)
1000 Args.push_back(source_filename);
1001 Args.insert(Args.end(), command_line_args,
1002 command_line_args + num_command_line_args);
Douglas Gregor94dc8f62010-03-19 16:15:56 +00001003 Args.push_back("-Xclang");
1004 Args.push_back("-detailed-preprocessing-record");
Douglas Gregor5352ac02010-01-28 00:27:43 +00001005 unsigned NumErrors = Diags->getNumErrors();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001006
Ted Kremenek29b72842010-01-07 22:49:05 +00001007#ifdef USE_CRASHTRACER
1008 ArgsCrashTracerInfo ACTI(Args);
Ted Kremenek8a8da7d2010-01-06 03:42:32 +00001009#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001010
Daniel Dunbar94220972009-12-05 02:17:18 +00001011 llvm::OwningPtr<ASTUnit> Unit(
1012 ASTUnit::LoadFromCommandLine(Args.data(), Args.data() + Args.size(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001013 *Diags,
Daniel Dunbar869824e2009-12-13 03:46:13 +00001014 CXXIdx->getClangResourcesPath(),
Daniel Dunbar94220972009-12-05 02:17:18 +00001015 CXXIdx->getOnlyLocalDecls(),
Douglas Gregor4db64a42010-01-23 00:14:00 +00001016 RemappedFiles.data(),
Douglas Gregora88084b2010-02-18 18:08:43 +00001017 RemappedFiles.size(),
Douglas Gregor94dc8f62010-03-19 16:15:56 +00001018 /*CaptureDiagnostics=*/true));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001019
Daniel Dunbar94220972009-12-05 02:17:18 +00001020 // FIXME: Until we have broader testing, just drop the entire AST if we
1021 // encountered an error.
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001022 if (NumErrors != Diags->getNumErrors()) {
Ted Kremenek34f6a322010-03-05 22:43:29 +00001023 // Make sure to check that 'Unit' is non-NULL.
1024 if (CXXIdx->getDisplayDiagnostics() && Unit.get()) {
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001025 for (ASTUnit::diag_iterator D = Unit->diag_begin(),
1026 DEnd = Unit->diag_end();
1027 D != DEnd; ++D) {
1028 CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOptions());
Douglas Gregor274f1902010-02-22 23:17:23 +00001029 CXString Msg = clang_formatDiagnostic(&Diag,
1030 clang_defaultDiagnosticDisplayOptions());
1031 fprintf(stderr, "%s\n", clang_getCString(Msg));
1032 clang_disposeString(Msg);
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001033 }
Douglas Gregor274f1902010-02-22 23:17:23 +00001034#ifdef LLVM_ON_WIN32
1035 // On Windows, force a flush, since there may be multiple copies of
1036 // stderr and stdout in the file system, all with different buffers
1037 // but writing to the same device.
1038 fflush(stderr);
1039#endif
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001040 }
Daniel Dunbar94220972009-12-05 02:17:18 +00001041 return 0;
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001042 }
Daniel Dunbar94220972009-12-05 02:17:18 +00001043
1044 return Unit.take();
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001045 }
1046
Ted Kremenek139ba862009-10-22 00:03:57 +00001047 // Build up the arguments for invoking 'clang'.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001048 std::vector<const char *> argv;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001049
Ted Kremenek139ba862009-10-22 00:03:57 +00001050 // First add the complete path to the 'clang' executable.
1051 llvm::sys::Path ClangPath = static_cast<CIndexer *>(CIdx)->getClangPath();
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00001052 argv.push_back(ClangPath.c_str());
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001053
Ted Kremenek139ba862009-10-22 00:03:57 +00001054 // Add the '-emit-ast' option as our execution mode for 'clang'.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001055 argv.push_back("-emit-ast");
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001056
Ted Kremenek139ba862009-10-22 00:03:57 +00001057 // The 'source_filename' argument is optional. If the caller does not
1058 // specify it then it is assumed that the source file is specified
1059 // in the actual argument list.
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001060 if (source_filename)
1061 argv.push_back(source_filename);
Ted Kremenek139ba862009-10-22 00:03:57 +00001062
Steve Naroff37b5ac22009-10-15 20:50:09 +00001063 // Generate a temporary name for the AST file.
Ted Kremenek139ba862009-10-22 00:03:57 +00001064 argv.push_back("-o");
Benjamin Kramerc2a98162010-03-13 21:22:49 +00001065 char astTmpFile[L_tmpnam];
1066 argv.push_back(tmpnam(astTmpFile));
Ted Kremenek139ba862009-10-22 00:03:57 +00001067
Douglas Gregor4db64a42010-01-23 00:14:00 +00001068 // Remap any unsaved files to temporary files.
1069 std::vector<llvm::sys::Path> TemporaryFiles;
1070 std::vector<std::string> RemapArgs;
1071 if (RemapFiles(num_unsaved_files, unsaved_files, RemapArgs, TemporaryFiles))
1072 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001073
Douglas Gregor4db64a42010-01-23 00:14:00 +00001074 // The pointers into the elements of RemapArgs are stable because we
1075 // won't be adding anything to RemapArgs after this point.
1076 for (unsigned i = 0, e = RemapArgs.size(); i != e; ++i)
1077 argv.push_back(RemapArgs[i].c_str());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001078
Ted Kremenek139ba862009-10-22 00:03:57 +00001079 // Process the compiler options, stripping off '-o', '-c', '-fsyntax-only'.
1080 for (int i = 0; i < num_command_line_args; ++i)
1081 if (const char *arg = command_line_args[i]) {
1082 if (strcmp(arg, "-o") == 0) {
1083 ++i; // Also skip the matching argument.
1084 continue;
1085 }
1086 if (strcmp(arg, "-emit-ast") == 0 ||
1087 strcmp(arg, "-c") == 0 ||
1088 strcmp(arg, "-fsyntax-only") == 0) {
1089 continue;
1090 }
1091
1092 // Keep the argument.
1093 argv.push_back(arg);
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001094 }
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001095
Douglas Gregord93256e2010-01-28 06:00:51 +00001096 // Generate a temporary name for the diagnostics file.
Benjamin Kramerc2a98162010-03-13 21:22:49 +00001097 char tmpFileResults[L_tmpnam];
1098 char *tmpResultsFileName = tmpnam(tmpFileResults);
1099 llvm::sys::Path DiagnosticsFile(tmpResultsFileName);
Douglas Gregord93256e2010-01-28 06:00:51 +00001100 TemporaryFiles.push_back(DiagnosticsFile);
1101 argv.push_back("-fdiagnostics-binary");
1102
Douglas Gregor94dc8f62010-03-19 16:15:56 +00001103 argv.push_back("-Xclang");
1104 argv.push_back("-detailed-preprocessing-record");
1105
Ted Kremenek139ba862009-10-22 00:03:57 +00001106 // Add the null terminator.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001107 argv.push_back(NULL);
1108
Ted Kremenekfeb15e32009-10-26 22:14:08 +00001109 // Invoke 'clang'.
1110 llvm::sys::Path DevNull; // leave empty, causes redirection to /dev/null
1111 // on Unix or NUL (Windows).
Ted Kremenek379afec2009-10-22 03:24:01 +00001112 std::string ErrMsg;
Douglas Gregord93256e2010-01-28 06:00:51 +00001113 const llvm::sys::Path *Redirects[] = { &DevNull, &DevNull, &DiagnosticsFile,
1114 NULL };
Ted Kremenek379afec2009-10-22 03:24:01 +00001115 llvm::sys::Program::ExecuteAndWait(ClangPath, &argv[0], /* env */ NULL,
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001116 /* redirects */ &Redirects[0],
Ted Kremenek379afec2009-10-22 03:24:01 +00001117 /* secondsToWait */ 0, /* memoryLimits */ 0, &ErrMsg);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001118
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001119 if (!ErrMsg.empty()) {
1120 std::string AllArgs;
Ted Kremenek379afec2009-10-22 03:24:01 +00001121 for (std::vector<const char*>::iterator I = argv.begin(), E = argv.end();
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001122 I != E; ++I) {
1123 AllArgs += ' ';
Ted Kremenek779e5f42009-10-26 22:08:39 +00001124 if (*I)
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001125 AllArgs += *I;
Ted Kremenek779e5f42009-10-26 22:08:39 +00001126 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001127
Daniel Dunbar32141c82010-02-23 20:23:45 +00001128 Diags->Report(diag::err_fe_invoking) << AllArgs << ErrMsg;
Ted Kremenek379afec2009-10-22 03:24:01 +00001129 }
Benjamin Kramer0829a832009-10-18 11:19:36 +00001130
Benjamin Kramerc2a98162010-03-13 21:22:49 +00001131 ASTUnit *ATU = ASTUnit::LoadFromPCHFile(astTmpFile, *Diags,
Douglas Gregor4db64a42010-01-23 00:14:00 +00001132 CXXIdx->getOnlyLocalDecls(),
Douglas Gregor4db64a42010-01-23 00:14:00 +00001133 RemappedFiles.data(),
Douglas Gregora88084b2010-02-18 18:08:43 +00001134 RemappedFiles.size(),
1135 /*CaptureDiagnostics=*/true);
Douglas Gregora88084b2010-02-18 18:08:43 +00001136 if (ATU) {
1137 LoadSerializedDiagnostics(DiagnosticsFile,
1138 num_unsaved_files, unsaved_files,
1139 ATU->getFileManager(),
1140 ATU->getSourceManager(),
1141 ATU->getDiagnostics());
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001142 } else if (CXXIdx->getDisplayDiagnostics()) {
1143 // We failed to load the ASTUnit, but we can still deserialize the
1144 // diagnostics and emit them.
1145 FileManager FileMgr;
Douglas Gregorf715ca12010-03-16 00:06:06 +00001146 Diagnostic Diag;
1147 SourceManager SourceMgr(Diag);
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001148 // FIXME: Faked LangOpts!
1149 LangOptions LangOpts;
1150 llvm::SmallVector<StoredDiagnostic, 4> Diags;
1151 LoadSerializedDiagnostics(DiagnosticsFile,
1152 num_unsaved_files, unsaved_files,
1153 FileMgr, SourceMgr, Diags);
1154 for (llvm::SmallVector<StoredDiagnostic, 4>::iterator D = Diags.begin(),
1155 DEnd = Diags.end();
1156 D != DEnd; ++D) {
1157 CXStoredDiagnostic Diag(*D, LangOpts);
Douglas Gregor274f1902010-02-22 23:17:23 +00001158 CXString Msg = clang_formatDiagnostic(&Diag,
1159 clang_defaultDiagnosticDisplayOptions());
1160 fprintf(stderr, "%s\n", clang_getCString(Msg));
1161 clang_disposeString(Msg);
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001162 }
Douglas Gregor274f1902010-02-22 23:17:23 +00001163
1164#ifdef LLVM_ON_WIN32
1165 // On Windows, force a flush, since there may be multiple copies of
1166 // stderr and stdout in the file system, all with different buffers
1167 // but writing to the same device.
1168 fflush(stderr);
1169#endif
Douglas Gregora88084b2010-02-18 18:08:43 +00001170 }
Douglas Gregord93256e2010-01-28 06:00:51 +00001171
Douglas Gregor313e26c2010-02-18 23:35:40 +00001172 if (ATU) {
1173 // Make the translation unit responsible for destroying all temporary files.
1174 for (unsigned i = 0, e = TemporaryFiles.size(); i != e; ++i)
1175 ATU->addTemporaryFile(TemporaryFiles[i]);
1176 ATU->addTemporaryFile(llvm::sys::Path(ATU->getPCHFileName()));
1177 } else {
1178 // Destroy all of the temporary files now; they can't be referenced any
1179 // longer.
1180 llvm::sys::Path(astTmpFile).eraseFromDisk();
1181 for (unsigned i = 0, e = TemporaryFiles.size(); i != e; ++i)
1182 TemporaryFiles[i].eraseFromDisk();
1183 }
1184
Steve Naroffe19944c2009-10-15 22:23:48 +00001185 return ATU;
Steve Naroff5b7d8e22009-10-15 20:04:39 +00001186}
1187
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001188void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001189 if (CTUnit)
1190 delete static_cast<ASTUnit *>(CTUnit);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00001191}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001192
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001193CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001194 if (!CTUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001195 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001196
Steve Naroff77accc12009-09-03 18:19:54 +00001197 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001198 return createCXString(CXXUnit->getOriginalSourceFileName(), true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +00001199}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +00001200
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001201CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001202 CXCursor Result = { CXCursor_TranslationUnit, { 0, 0, TU } };
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001203 return Result;
1204}
1205
Ted Kremenekfb480492010-01-13 21:46:36 +00001206} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +00001207
Ted Kremenekfb480492010-01-13 21:46:36 +00001208//===----------------------------------------------------------------------===//
Douglas Gregor1db19de2010-01-19 21:36:55 +00001209// CXSourceLocation and CXSourceRange Operations.
1210//===----------------------------------------------------------------------===//
1211
Douglas Gregorb9790342010-01-22 21:44:22 +00001212extern "C" {
1213CXSourceLocation clang_getNullLocation() {
Douglas Gregor5352ac02010-01-28 00:27:43 +00001214 CXSourceLocation Result = { { 0, 0 }, 0 };
Douglas Gregorb9790342010-01-22 21:44:22 +00001215 return Result;
1216}
1217
1218unsigned clang_equalLocations(CXSourceLocation loc1, CXSourceLocation loc2) {
Daniel Dunbar90a6b9e2010-01-30 23:58:27 +00001219 return (loc1.ptr_data[0] == loc2.ptr_data[0] &&
1220 loc1.ptr_data[1] == loc2.ptr_data[1] &&
1221 loc1.int_data == loc2.int_data);
Douglas Gregorb9790342010-01-22 21:44:22 +00001222}
1223
1224CXSourceLocation clang_getLocation(CXTranslationUnit tu,
1225 CXFile file,
1226 unsigned line,
1227 unsigned column) {
1228 if (!tu)
1229 return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001230
Douglas Gregorb9790342010-01-22 21:44:22 +00001231 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
1232 SourceLocation SLoc
1233 = CXXUnit->getSourceManager().getLocation(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001234 static_cast<const FileEntry *>(file),
Douglas Gregorb9790342010-01-22 21:44:22 +00001235 line, column);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001236
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00001237 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
Douglas Gregorb9790342010-01-22 21:44:22 +00001238}
1239
Douglas Gregor5352ac02010-01-28 00:27:43 +00001240CXSourceRange clang_getNullRange() {
1241 CXSourceRange Result = { { 0, 0 }, 0, 0 };
1242 return Result;
1243}
Daniel Dunbard52864b2010-02-14 10:02:57 +00001244
Douglas Gregor5352ac02010-01-28 00:27:43 +00001245CXSourceRange clang_getRange(CXSourceLocation begin, CXSourceLocation end) {
1246 if (begin.ptr_data[0] != end.ptr_data[0] ||
1247 begin.ptr_data[1] != end.ptr_data[1])
1248 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001249
1250 CXSourceRange Result = { { begin.ptr_data[0], begin.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00001251 begin.int_data, end.int_data };
Douglas Gregorb9790342010-01-22 21:44:22 +00001252 return Result;
1253}
1254
Douglas Gregor46766dc2010-01-26 19:19:08 +00001255void clang_getInstantiationLocation(CXSourceLocation location,
1256 CXFile *file,
1257 unsigned *line,
1258 unsigned *column,
1259 unsigned *offset) {
Douglas Gregor1db19de2010-01-19 21:36:55 +00001260 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
1261
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00001262 if (!location.ptr_data[0] || Loc.isInvalid()) {
Douglas Gregor46766dc2010-01-26 19:19:08 +00001263 if (file)
1264 *file = 0;
1265 if (line)
1266 *line = 0;
1267 if (column)
1268 *column = 0;
1269 if (offset)
1270 *offset = 0;
1271 return;
1272 }
1273
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00001274 const SourceManager &SM =
1275 *static_cast<const SourceManager*>(location.ptr_data[0]);
Douglas Gregor1db19de2010-01-19 21:36:55 +00001276 SourceLocation InstLoc = SM.getInstantiationLoc(Loc);
Douglas Gregor1db19de2010-01-19 21:36:55 +00001277
1278 if (file)
1279 *file = (void *)SM.getFileEntryForID(SM.getFileID(InstLoc));
1280 if (line)
1281 *line = SM.getInstantiationLineNumber(InstLoc);
1282 if (column)
1283 *column = SM.getInstantiationColumnNumber(InstLoc);
Douglas Gregore69517c2010-01-26 03:07:15 +00001284 if (offset)
Douglas Gregor46766dc2010-01-26 19:19:08 +00001285 *offset = SM.getDecomposedLoc(InstLoc).second;
Douglas Gregore69517c2010-01-26 03:07:15 +00001286}
1287
Douglas Gregor1db19de2010-01-19 21:36:55 +00001288CXSourceLocation clang_getRangeStart(CXSourceRange range) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001289 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00001290 range.begin_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00001291 return Result;
1292}
1293
1294CXSourceLocation clang_getRangeEnd(CXSourceRange range) {
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00001295 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00001296 range.end_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00001297 return Result;
1298}
1299
Douglas Gregorb9790342010-01-22 21:44:22 +00001300} // end: extern "C"
1301
Douglas Gregor1db19de2010-01-19 21:36:55 +00001302//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00001303// CXFile Operations.
1304//===----------------------------------------------------------------------===//
1305
1306extern "C" {
Ted Kremenek74844072010-02-17 00:41:20 +00001307CXString clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00001308 if (!SFile)
Ted Kremenek74844072010-02-17 00:41:20 +00001309 return createCXString(NULL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001310
Steve Naroff88145032009-10-27 14:35:18 +00001311 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Ted Kremenek74844072010-02-17 00:41:20 +00001312 return createCXString(FEnt->getName());
Steve Naroff88145032009-10-27 14:35:18 +00001313}
1314
1315time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00001316 if (!SFile)
1317 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001318
Steve Naroff88145032009-10-27 14:35:18 +00001319 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
1320 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +00001321}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001322
Douglas Gregorb9790342010-01-22 21:44:22 +00001323CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
1324 if (!tu)
1325 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001326
Douglas Gregorb9790342010-01-22 21:44:22 +00001327 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001328
Douglas Gregorb9790342010-01-22 21:44:22 +00001329 FileManager &FMgr = CXXUnit->getFileManager();
1330 const FileEntry *File = FMgr.getFile(file_name, file_name+strlen(file_name));
1331 return const_cast<FileEntry *>(File);
1332}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001333
Ted Kremenekfb480492010-01-13 21:46:36 +00001334} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +00001335
Ted Kremenekfb480492010-01-13 21:46:36 +00001336//===----------------------------------------------------------------------===//
1337// CXCursor Operations.
1338//===----------------------------------------------------------------------===//
1339
Ted Kremenekfb480492010-01-13 21:46:36 +00001340static Decl *getDeclFromExpr(Stmt *E) {
1341 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
1342 return RefExpr->getDecl();
1343 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
1344 return ME->getMemberDecl();
1345 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
1346 return RE->getDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001347
Ted Kremenekfb480492010-01-13 21:46:36 +00001348 if (CallExpr *CE = dyn_cast<CallExpr>(E))
1349 return getDeclFromExpr(CE->getCallee());
1350 if (CastExpr *CE = dyn_cast<CastExpr>(E))
1351 return getDeclFromExpr(CE->getSubExpr());
1352 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
1353 return OME->getMethodDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001354
Ted Kremenekfb480492010-01-13 21:46:36 +00001355 return 0;
1356}
1357
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00001358static SourceLocation getLocationFromExpr(Expr *E) {
1359 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
1360 return /*FIXME:*/Msg->getLeftLoc();
1361 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
1362 return DRE->getLocation();
1363 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
1364 return Member->getMemberLoc();
1365 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
1366 return Ivar->getLocation();
1367 return E->getLocStart();
1368}
1369
Ted Kremenekfb480492010-01-13 21:46:36 +00001370extern "C" {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001371
1372unsigned clang_visitChildren(CXCursor parent,
Douglas Gregorb1373d02010-01-20 20:59:29 +00001373 CXCursorVisitor visitor,
1374 CXClientData client_data) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001375 ASTUnit *CXXUnit = getCursorASTUnit(parent);
Douglas Gregorb1373d02010-01-20 20:59:29 +00001376
1377 unsigned PCHLevel = Decl::MaxPCHLevel;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001378
Douglas Gregorb1373d02010-01-20 20:59:29 +00001379 // Set the PCHLevel to filter out unwanted decls if requested.
1380 if (CXXUnit->getOnlyLocalDecls()) {
1381 PCHLevel = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001382
Douglas Gregorb1373d02010-01-20 20:59:29 +00001383 // If the main input was an AST, bump the level.
1384 if (CXXUnit->isMainFileAST())
1385 ++PCHLevel;
1386 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001387
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001388 CursorVisitor CursorVis(CXXUnit, visitor, client_data, PCHLevel);
Douglas Gregorb1373d02010-01-20 20:59:29 +00001389 return CursorVis.VisitChildren(parent);
1390}
1391
Douglas Gregor78205d42010-01-20 21:45:58 +00001392static CXString getDeclSpelling(Decl *D) {
1393 NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
1394 if (!ND)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001395 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001396
Douglas Gregor78205d42010-01-20 21:45:58 +00001397 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001398 return createCXString(OMD->getSelector().getAsString());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001399
Douglas Gregor78205d42010-01-20 21:45:58 +00001400 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
1401 // No, this isn't the same as the code below. getIdentifier() is non-virtual
1402 // and returns different names. NamedDecl returns the class name and
1403 // ObjCCategoryImplDecl returns the category name.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001404 return createCXString(CIMP->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001405
Douglas Gregor78205d42010-01-20 21:45:58 +00001406 if (ND->getIdentifier())
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001407 return createCXString(ND->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001408
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001409 return createCXString("");
Douglas Gregor78205d42010-01-20 21:45:58 +00001410}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001411
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001412CXString clang_getCursorSpelling(CXCursor C) {
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001413 if (clang_isTranslationUnit(C.kind))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001414 return clang_getTranslationUnitSpelling(C.data[2]);
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001415
Steve Narofff334b4e2009-09-02 18:26:48 +00001416 if (clang_isReference(C.kind)) {
1417 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00001418 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +00001419 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001420 return createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00001421 }
1422 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +00001423 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001424 return createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00001425 }
1426 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +00001427 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +00001428 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001429 return createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00001430 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001431 case CXCursor_TypeRef: {
1432 TypeDecl *Type = getCursorTypeRef(C).first;
1433 assert(Type && "Missing type decl");
1434
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001435 return createCXString(getCursorContext(C).getTypeDeclType(Type).
1436 getAsString());
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001437 }
1438
Daniel Dunbaracca7252009-11-30 20:42:49 +00001439 default:
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001440 return createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +00001441 }
1442 }
Douglas Gregor97b98722010-01-19 23:20:36 +00001443
1444 if (clang_isExpression(C.kind)) {
1445 Decl *D = getDeclFromExpr(getCursorExpr(C));
1446 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +00001447 return getDeclSpelling(D);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001448 return createCXString("");
Douglas Gregor97b98722010-01-19 23:20:36 +00001449 }
1450
Douglas Gregor4ae8f292010-03-18 17:52:52 +00001451 if (C.kind == CXCursor_MacroInstantiation)
1452 return createCXString(getCursorMacroInstantiation(C)->getName()
1453 ->getNameStart());
1454
Douglas Gregor572feb22010-03-18 18:04:21 +00001455 if (C.kind == CXCursor_MacroDefinition)
1456 return createCXString(getCursorMacroDefinition(C)->getName()
1457 ->getNameStart());
1458
Douglas Gregor60cbfac2010-01-25 16:56:17 +00001459 if (clang_isDeclaration(C.kind))
1460 return getDeclSpelling(getCursorDecl(C));
Ted Kremeneke68fff62010-02-17 00:41:32 +00001461
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001462 return createCXString("");
Steve Narofff334b4e2009-09-02 18:26:48 +00001463}
1464
Ted Kremeneke68fff62010-02-17 00:41:32 +00001465CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00001466 switch (Kind) {
Ted Kremeneke68fff62010-02-17 00:41:32 +00001467 case CXCursor_FunctionDecl:
1468 return createCXString("FunctionDecl");
1469 case CXCursor_TypedefDecl:
1470 return createCXString("TypedefDecl");
1471 case CXCursor_EnumDecl:
1472 return createCXString("EnumDecl");
1473 case CXCursor_EnumConstantDecl:
1474 return createCXString("EnumConstantDecl");
1475 case CXCursor_StructDecl:
1476 return createCXString("StructDecl");
1477 case CXCursor_UnionDecl:
1478 return createCXString("UnionDecl");
1479 case CXCursor_ClassDecl:
1480 return createCXString("ClassDecl");
1481 case CXCursor_FieldDecl:
1482 return createCXString("FieldDecl");
1483 case CXCursor_VarDecl:
1484 return createCXString("VarDecl");
1485 case CXCursor_ParmDecl:
1486 return createCXString("ParmDecl");
1487 case CXCursor_ObjCInterfaceDecl:
1488 return createCXString("ObjCInterfaceDecl");
1489 case CXCursor_ObjCCategoryDecl:
1490 return createCXString("ObjCCategoryDecl");
1491 case CXCursor_ObjCProtocolDecl:
1492 return createCXString("ObjCProtocolDecl");
1493 case CXCursor_ObjCPropertyDecl:
1494 return createCXString("ObjCPropertyDecl");
1495 case CXCursor_ObjCIvarDecl:
1496 return createCXString("ObjCIvarDecl");
1497 case CXCursor_ObjCInstanceMethodDecl:
1498 return createCXString("ObjCInstanceMethodDecl");
1499 case CXCursor_ObjCClassMethodDecl:
1500 return createCXString("ObjCClassMethodDecl");
1501 case CXCursor_ObjCImplementationDecl:
1502 return createCXString("ObjCImplementationDecl");
1503 case CXCursor_ObjCCategoryImplDecl:
1504 return createCXString("ObjCCategoryImplDecl");
1505 case CXCursor_UnexposedDecl:
1506 return createCXString("UnexposedDecl");
1507 case CXCursor_ObjCSuperClassRef:
1508 return createCXString("ObjCSuperClassRef");
1509 case CXCursor_ObjCProtocolRef:
1510 return createCXString("ObjCProtocolRef");
1511 case CXCursor_ObjCClassRef:
1512 return createCXString("ObjCClassRef");
1513 case CXCursor_TypeRef:
1514 return createCXString("TypeRef");
1515 case CXCursor_UnexposedExpr:
1516 return createCXString("UnexposedExpr");
1517 case CXCursor_DeclRefExpr:
1518 return createCXString("DeclRefExpr");
1519 case CXCursor_MemberRefExpr:
1520 return createCXString("MemberRefExpr");
1521 case CXCursor_CallExpr:
1522 return createCXString("CallExpr");
1523 case CXCursor_ObjCMessageExpr:
1524 return createCXString("ObjCMessageExpr");
1525 case CXCursor_UnexposedStmt:
1526 return createCXString("UnexposedStmt");
1527 case CXCursor_InvalidFile:
1528 return createCXString("InvalidFile");
Ted Kremenek292db642010-03-19 20:39:05 +00001529 case CXCursor_InvalidCode:
1530 return createCXString("InvalidCode");
Ted Kremeneke68fff62010-02-17 00:41:32 +00001531 case CXCursor_NoDeclFound:
1532 return createCXString("NoDeclFound");
1533 case CXCursor_NotImplemented:
1534 return createCXString("NotImplemented");
1535 case CXCursor_TranslationUnit:
1536 return createCXString("TranslationUnit");
Ted Kremeneke77f4432010-02-18 03:09:07 +00001537 case CXCursor_UnexposedAttr:
1538 return createCXString("UnexposedAttr");
1539 case CXCursor_IBActionAttr:
1540 return createCXString("attribute(ibaction)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00001541 case CXCursor_IBOutletAttr:
1542 return createCXString("attribute(iboutlet)");
1543 case CXCursor_PreprocessingDirective:
1544 return createCXString("preprocessing directive");
Douglas Gregor572feb22010-03-18 18:04:21 +00001545 case CXCursor_MacroDefinition:
1546 return createCXString("macro definition");
Douglas Gregor48072312010-03-18 15:23:44 +00001547 case CXCursor_MacroInstantiation:
1548 return createCXString("macro instantiation");
Steve Naroff89922f82009-08-31 00:59:03 +00001549 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00001550
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00001551 llvm_unreachable("Unhandled CXCursorKind");
Ted Kremeneke68fff62010-02-17 00:41:32 +00001552 return createCXString(NULL);
Steve Naroff600866c2009-08-27 19:51:58 +00001553}
Steve Naroff89922f82009-08-31 00:59:03 +00001554
Ted Kremeneke68fff62010-02-17 00:41:32 +00001555enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
1556 CXCursor parent,
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001557 CXClientData client_data) {
1558 CXCursor *BestCursor = static_cast<CXCursor *>(client_data);
1559 *BestCursor = cursor;
1560 return CXChildVisit_Recurse;
1561}
Ted Kremeneke68fff62010-02-17 00:41:32 +00001562
Douglas Gregorb9790342010-01-22 21:44:22 +00001563CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
1564 if (!TU)
Ted Kremenekf4629892010-01-14 01:51:23 +00001565 return clang_getNullCursor();
Ted Kremeneke68fff62010-02-17 00:41:32 +00001566
Douglas Gregorb9790342010-01-22 21:44:22 +00001567 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
1568
Douglas Gregorbdf60622010-03-05 21:16:25 +00001569 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
1570
Ted Kremeneka297de22010-01-25 22:34:44 +00001571 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001572 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
1573 if (SLoc.isValid()) {
Daniel Dunbard52864b2010-02-14 10:02:57 +00001574 SourceRange RegionOfInterest(SLoc, SLoc.getFileLocWithOffset(1));
Ted Kremeneke68fff62010-02-17 00:41:32 +00001575
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001576 // FIXME: Would be great to have a "hint" cursor, then walk from that
1577 // hint cursor upward until we find a cursor whose source range encloses
1578 // the region of interest, rather than starting from the translation unit.
1579 CXCursor Parent = clang_getTranslationUnitCursor(CXXUnit);
Ted Kremeneke68fff62010-02-17 00:41:32 +00001580 CursorVisitor CursorVis(CXXUnit, GetCursorVisitor, &Result,
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001581 Decl::MaxPCHLevel, RegionOfInterest);
1582 CursorVis.VisitChildren(Parent);
Steve Naroff77128dd2009-09-15 20:25:34 +00001583 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00001584 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00001585}
1586
Ted Kremenek73885552009-11-17 19:28:59 +00001587CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00001588 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00001589}
1590
1591unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00001592 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00001593}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001594
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001595unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00001596 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
1597}
1598
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001599unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +00001600 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
1601}
Steve Naroff2d4d6292009-08-31 14:26:51 +00001602
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001603unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00001604 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
1605}
1606
Douglas Gregor97b98722010-01-19 23:20:36 +00001607unsigned clang_isExpression(enum CXCursorKind K) {
1608 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
1609}
1610
1611unsigned clang_isStatement(enum CXCursorKind K) {
1612 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
1613}
1614
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001615unsigned clang_isTranslationUnit(enum CXCursorKind K) {
1616 return K == CXCursor_TranslationUnit;
1617}
1618
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00001619unsigned clang_isPreprocessing(enum CXCursorKind K) {
1620 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
1621}
1622
Ted Kremenekad6eff62010-03-08 21:17:29 +00001623unsigned clang_isUnexposed(enum CXCursorKind K) {
1624 switch (K) {
1625 case CXCursor_UnexposedDecl:
1626 case CXCursor_UnexposedExpr:
1627 case CXCursor_UnexposedStmt:
1628 case CXCursor_UnexposedAttr:
1629 return true;
1630 default:
1631 return false;
1632 }
1633}
1634
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001635CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00001636 return C.kind;
1637}
1638
Douglas Gregor98258af2010-01-18 22:46:11 +00001639CXSourceLocation clang_getCursorLocation(CXCursor C) {
1640 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00001641 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001642 case CXCursor_ObjCSuperClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00001643 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1644 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001645 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001646 }
1647
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001648 case CXCursor_ObjCProtocolRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00001649 std::pair<ObjCProtocolDecl *, SourceLocation> P
1650 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001651 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001652 }
1653
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001654 case CXCursor_ObjCClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00001655 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1656 = getCursorObjCClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001657 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001658 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001659
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001660 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001661 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001662 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001663 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001664
Douglas Gregorf46034a2010-01-18 23:41:10 +00001665 default:
1666 // FIXME: Need a way to enumerate all non-reference cases.
1667 llvm_unreachable("Missed a reference kind");
1668 }
Douglas Gregor98258af2010-01-18 22:46:11 +00001669 }
Douglas Gregor97b98722010-01-19 23:20:36 +00001670
1671 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001672 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00001673 getLocationFromExpr(getCursorExpr(C)));
1674
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00001675 if (C.kind == CXCursor_PreprocessingDirective) {
1676 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
1677 return cxloc::translateSourceLocation(getCursorContext(C), L);
1678 }
Douglas Gregor48072312010-03-18 15:23:44 +00001679
1680 if (C.kind == CXCursor_MacroInstantiation) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00001681 SourceLocation L
1682 = cxcursor::getCursorMacroInstantiation(C)->getSourceRange().getBegin();
Douglas Gregor48072312010-03-18 15:23:44 +00001683 return cxloc::translateSourceLocation(getCursorContext(C), L);
1684 }
Douglas Gregor572feb22010-03-18 18:04:21 +00001685
1686 if (C.kind == CXCursor_MacroDefinition) {
1687 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
1688 return cxloc::translateSourceLocation(getCursorContext(C), L);
1689 }
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00001690
Douglas Gregor5352ac02010-01-28 00:27:43 +00001691 if (!getCursorDecl(C))
1692 return clang_getNullLocation();
Douglas Gregor98258af2010-01-18 22:46:11 +00001693
Douglas Gregorf46034a2010-01-18 23:41:10 +00001694 Decl *D = getCursorDecl(C);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001695 SourceLocation Loc = D->getLocation();
1696 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
1697 Loc = Class->getClassLoc();
Ted Kremeneka297de22010-01-25 22:34:44 +00001698 return cxloc::translateSourceLocation(D->getASTContext(), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00001699}
Douglas Gregora7bde202010-01-19 00:34:46 +00001700
1701CXSourceRange clang_getCursorExtent(CXCursor C) {
1702 if (clang_isReference(C.kind)) {
1703 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001704 case CXCursor_ObjCSuperClassRef: {
Douglas Gregora7bde202010-01-19 00:34:46 +00001705 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1706 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001707 return cxloc::translateSourceRange(P.first->getASTContext(), P.second);
Douglas Gregora7bde202010-01-19 00:34:46 +00001708 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001709
1710 case CXCursor_ObjCProtocolRef: {
Douglas Gregora7bde202010-01-19 00:34:46 +00001711 std::pair<ObjCProtocolDecl *, SourceLocation> P
1712 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001713 return cxloc::translateSourceRange(P.first->getASTContext(), P.second);
Douglas Gregora7bde202010-01-19 00:34:46 +00001714 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001715
1716 case CXCursor_ObjCClassRef: {
Douglas Gregora7bde202010-01-19 00:34:46 +00001717 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1718 = getCursorObjCClassRef(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001719
Ted Kremeneka297de22010-01-25 22:34:44 +00001720 return cxloc::translateSourceRange(P.first->getASTContext(), P.second);
Douglas Gregora7bde202010-01-19 00:34:46 +00001721 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001722
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001723 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001724 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001725 return cxloc::translateSourceRange(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001726 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001727
Douglas Gregora7bde202010-01-19 00:34:46 +00001728 default:
1729 // FIXME: Need a way to enumerate all non-reference cases.
1730 llvm_unreachable("Missed a reference kind");
1731 }
1732 }
Douglas Gregor97b98722010-01-19 23:20:36 +00001733
1734 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001735 return cxloc::translateSourceRange(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00001736 getCursorExpr(C)->getSourceRange());
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001737
1738 if (clang_isStatement(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001739 return cxloc::translateSourceRange(getCursorContext(C),
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001740 getCursorStmt(C)->getSourceRange());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001741
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00001742 if (C.kind == CXCursor_PreprocessingDirective) {
1743 SourceRange R = cxcursor::getCursorPreprocessingDirective(C);
1744 return cxloc::translateSourceRange(getCursorContext(C), R);
1745 }
Douglas Gregor48072312010-03-18 15:23:44 +00001746
1747 if (C.kind == CXCursor_MacroInstantiation) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00001748 SourceRange R = cxcursor::getCursorMacroInstantiation(C)->getSourceRange();
Douglas Gregor48072312010-03-18 15:23:44 +00001749 return cxloc::translateSourceRange(getCursorContext(C), R);
1750 }
Douglas Gregor572feb22010-03-18 18:04:21 +00001751
1752 if (C.kind == CXCursor_MacroDefinition) {
1753 SourceRange R = cxcursor::getCursorMacroDefinition(C)->getSourceRange();
1754 return cxloc::translateSourceRange(getCursorContext(C), R);
1755 }
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00001756
Douglas Gregor5352ac02010-01-28 00:27:43 +00001757 if (!getCursorDecl(C))
1758 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001759
Douglas Gregora7bde202010-01-19 00:34:46 +00001760 Decl *D = getCursorDecl(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001761 return cxloc::translateSourceRange(D->getASTContext(), D->getSourceRange());
Douglas Gregora7bde202010-01-19 00:34:46 +00001762}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001763
1764CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001765 if (clang_isInvalid(C.kind))
1766 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001767
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001768 ASTUnit *CXXUnit = getCursorASTUnit(C);
Douglas Gregorb6998662010-01-19 19:34:47 +00001769 if (clang_isDeclaration(C.kind))
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001770 return C;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001771
Douglas Gregor97b98722010-01-19 23:20:36 +00001772 if (clang_isExpression(C.kind)) {
1773 Decl *D = getDeclFromExpr(getCursorExpr(C));
1774 if (D)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001775 return MakeCXCursor(D, CXXUnit);
Douglas Gregor97b98722010-01-19 23:20:36 +00001776 return clang_getNullCursor();
1777 }
1778
Douglas Gregorbf7efa22010-03-18 18:23:03 +00001779 if (C.kind == CXCursor_MacroInstantiation) {
1780 if (MacroDefinition *Def = getCursorMacroInstantiation(C)->getDefinition())
1781 return MakeMacroDefinitionCursor(Def, CXXUnit);
1782 }
1783
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001784 if (!clang_isReference(C.kind))
1785 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001786
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001787 switch (C.kind) {
1788 case CXCursor_ObjCSuperClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001789 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001790
1791 case CXCursor_ObjCProtocolRef: {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001792 return MakeCXCursor(getCursorObjCProtocolRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001793
1794 case CXCursor_ObjCClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001795 return MakeCXCursor(getCursorObjCClassRef(C).first, CXXUnit);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001796
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001797 case CXCursor_TypeRef:
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001798 return MakeCXCursor(getCursorTypeRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001799
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001800 default:
1801 // We would prefer to enumerate all non-reference cursor kinds here.
1802 llvm_unreachable("Unhandled reference cursor kind");
1803 break;
1804 }
1805 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001806
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001807 return clang_getNullCursor();
1808}
1809
Douglas Gregorb6998662010-01-19 19:34:47 +00001810CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001811 if (clang_isInvalid(C.kind))
1812 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001813
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001814 ASTUnit *CXXUnit = getCursorASTUnit(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001815
Douglas Gregorb6998662010-01-19 19:34:47 +00001816 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00001817 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00001818 C = clang_getCursorReferenced(C);
1819 WasReference = true;
1820 }
1821
Douglas Gregorbf7efa22010-03-18 18:23:03 +00001822 if (C.kind == CXCursor_MacroInstantiation)
1823 return clang_getCursorReferenced(C);
1824
Douglas Gregorb6998662010-01-19 19:34:47 +00001825 if (!clang_isDeclaration(C.kind))
1826 return clang_getNullCursor();
1827
1828 Decl *D = getCursorDecl(C);
1829 if (!D)
1830 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001831
Douglas Gregorb6998662010-01-19 19:34:47 +00001832 switch (D->getKind()) {
1833 // Declaration kinds that don't really separate the notions of
1834 // declaration and definition.
1835 case Decl::Namespace:
1836 case Decl::Typedef:
1837 case Decl::TemplateTypeParm:
1838 case Decl::EnumConstant:
1839 case Decl::Field:
1840 case Decl::ObjCIvar:
1841 case Decl::ObjCAtDefsField:
1842 case Decl::ImplicitParam:
1843 case Decl::ParmVar:
1844 case Decl::NonTypeTemplateParm:
1845 case Decl::TemplateTemplateParm:
1846 case Decl::ObjCCategoryImpl:
1847 case Decl::ObjCImplementation:
1848 case Decl::LinkageSpec:
1849 case Decl::ObjCPropertyImpl:
1850 case Decl::FileScopeAsm:
1851 case Decl::StaticAssert:
1852 case Decl::Block:
1853 return C;
1854
1855 // Declaration kinds that don't make any sense here, but are
1856 // nonetheless harmless.
1857 case Decl::TranslationUnit:
1858 case Decl::Template:
1859 case Decl::ObjCContainer:
1860 break;
1861
1862 // Declaration kinds for which the definition is not resolvable.
1863 case Decl::UnresolvedUsingTypename:
1864 case Decl::UnresolvedUsingValue:
1865 break;
1866
1867 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001868 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
1869 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001870
1871 case Decl::NamespaceAlias:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001872 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001873
1874 case Decl::Enum:
1875 case Decl::Record:
1876 case Decl::CXXRecord:
1877 case Decl::ClassTemplateSpecialization:
1878 case Decl::ClassTemplatePartialSpecialization:
Douglas Gregor952b0172010-02-11 01:04:33 +00001879 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001880 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001881 return clang_getNullCursor();
1882
1883 case Decl::Function:
1884 case Decl::CXXMethod:
1885 case Decl::CXXConstructor:
1886 case Decl::CXXDestructor:
1887 case Decl::CXXConversion: {
1888 const FunctionDecl *Def = 0;
1889 if (cast<FunctionDecl>(D)->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001890 return MakeCXCursor(const_cast<FunctionDecl *>(Def), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001891 return clang_getNullCursor();
1892 }
1893
1894 case Decl::Var: {
Sebastian Redl31310a22010-02-01 20:16:42 +00001895 // Ask the variable if it has a definition.
1896 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
1897 return MakeCXCursor(Def, CXXUnit);
1898 return clang_getNullCursor();
Douglas Gregorb6998662010-01-19 19:34:47 +00001899 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001900
Douglas Gregorb6998662010-01-19 19:34:47 +00001901 case Decl::FunctionTemplate: {
1902 const FunctionDecl *Def = 0;
1903 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001904 return MakeCXCursor(Def->getDescribedFunctionTemplate(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001905 return clang_getNullCursor();
1906 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001907
Douglas Gregorb6998662010-01-19 19:34:47 +00001908 case Decl::ClassTemplate: {
1909 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
Douglas Gregor952b0172010-02-11 01:04:33 +00001910 ->getDefinition())
Douglas Gregorb6998662010-01-19 19:34:47 +00001911 return MakeCXCursor(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001912 cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001913 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001914 return clang_getNullCursor();
1915 }
1916
1917 case Decl::Using: {
1918 UsingDecl *Using = cast<UsingDecl>(D);
1919 CXCursor Def = clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001920 for (UsingDecl::shadow_iterator S = Using->shadow_begin(),
1921 SEnd = Using->shadow_end();
Douglas Gregorb6998662010-01-19 19:34:47 +00001922 S != SEnd; ++S) {
1923 if (Def != clang_getNullCursor()) {
1924 // FIXME: We have no way to return multiple results.
1925 return clang_getNullCursor();
1926 }
1927
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001928 Def = clang_getCursorDefinition(MakeCXCursor((*S)->getTargetDecl(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001929 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00001930 }
1931
1932 return Def;
1933 }
1934
1935 case Decl::UsingShadow:
1936 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001937 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001938 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00001939
1940 case Decl::ObjCMethod: {
1941 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
1942 if (Method->isThisDeclarationADefinition())
1943 return C;
1944
1945 // Dig out the method definition in the associated
1946 // @implementation, if we have it.
1947 // FIXME: The ASTs should make finding the definition easier.
1948 if (ObjCInterfaceDecl *Class
1949 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
1950 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
1951 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
1952 Method->isInstanceMethod()))
1953 if (Def->isThisDeclarationADefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001954 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001955
1956 return clang_getNullCursor();
1957 }
1958
1959 case Decl::ObjCCategory:
1960 if (ObjCCategoryImplDecl *Impl
1961 = cast<ObjCCategoryDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001962 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001963 return clang_getNullCursor();
1964
1965 case Decl::ObjCProtocol:
1966 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
1967 return C;
1968 return clang_getNullCursor();
1969
1970 case Decl::ObjCInterface:
1971 // There are two notions of a "definition" for an Objective-C
1972 // class: the interface and its implementation. When we resolved a
1973 // reference to an Objective-C class, produce the @interface as
1974 // the definition; when we were provided with the interface,
1975 // produce the @implementation as the definition.
1976 if (WasReference) {
1977 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
1978 return C;
1979 } else if (ObjCImplementationDecl *Impl
1980 = cast<ObjCInterfaceDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001981 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001982 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001983
Douglas Gregorb6998662010-01-19 19:34:47 +00001984 case Decl::ObjCProperty:
1985 // FIXME: We don't really know where to find the
1986 // ObjCPropertyImplDecls that implement this property.
1987 return clang_getNullCursor();
1988
1989 case Decl::ObjCCompatibleAlias:
1990 if (ObjCInterfaceDecl *Class
1991 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
1992 if (!Class->isForwardDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001993 return MakeCXCursor(Class, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001994
Douglas Gregorb6998662010-01-19 19:34:47 +00001995 return clang_getNullCursor();
1996
1997 case Decl::ObjCForwardProtocol: {
1998 ObjCForwardProtocolDecl *Forward = cast<ObjCForwardProtocolDecl>(D);
1999 if (Forward->protocol_size() == 1)
2000 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002001 MakeCXCursor(*Forward->protocol_begin(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002002 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002003
2004 // FIXME: Cannot return multiple definitions.
2005 return clang_getNullCursor();
2006 }
2007
2008 case Decl::ObjCClass: {
2009 ObjCClassDecl *Class = cast<ObjCClassDecl>(D);
2010 if (Class->size() == 1) {
2011 ObjCInterfaceDecl *IFace = Class->begin()->getInterface();
2012 if (!IFace->isForwardDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002013 return MakeCXCursor(IFace, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002014 return clang_getNullCursor();
2015 }
2016
2017 // FIXME: Cannot return multiple definitions.
2018 return clang_getNullCursor();
2019 }
2020
2021 case Decl::Friend:
2022 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002023 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002024 return clang_getNullCursor();
2025
2026 case Decl::FriendTemplate:
2027 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002028 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002029 return clang_getNullCursor();
2030 }
2031
2032 return clang_getNullCursor();
2033}
2034
2035unsigned clang_isCursorDefinition(CXCursor C) {
2036 if (!clang_isDeclaration(C.kind))
2037 return 0;
2038
2039 return clang_getCursorDefinition(C) == C;
2040}
2041
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002042void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00002043 const char **startBuf,
2044 const char **endBuf,
2045 unsigned *startLine,
2046 unsigned *startColumn,
2047 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002048 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00002049 assert(getCursorDecl(C) && "CXCursor has null decl");
2050 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00002051 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
2052 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002053
Steve Naroff4ade6d62009-09-23 17:52:52 +00002054 SourceManager &SM = FD->getASTContext().getSourceManager();
2055 *startBuf = SM.getCharacterData(Body->getLBracLoc());
2056 *endBuf = SM.getCharacterData(Body->getRBracLoc());
2057 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
2058 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
2059 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
2060 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
2061}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002062
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002063void clang_enableStackTraces(void) {
2064 llvm::sys::PrintStackTraceOnErrorSignal();
2065}
2066
Ted Kremenekfb480492010-01-13 21:46:36 +00002067} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00002068
Ted Kremenekfb480492010-01-13 21:46:36 +00002069//===----------------------------------------------------------------------===//
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002070// Token-based Operations.
2071//===----------------------------------------------------------------------===//
2072
2073/* CXToken layout:
2074 * int_data[0]: a CXTokenKind
2075 * int_data[1]: starting token location
2076 * int_data[2]: token length
2077 * int_data[3]: reserved
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002078 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002079 * otherwise unused.
2080 */
2081extern "C" {
2082
2083CXTokenKind clang_getTokenKind(CXToken CXTok) {
2084 return static_cast<CXTokenKind>(CXTok.int_data[0]);
2085}
2086
2087CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
2088 switch (clang_getTokenKind(CXTok)) {
2089 case CXToken_Identifier:
2090 case CXToken_Keyword:
2091 // We know we have an IdentifierInfo*, so use that.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002092 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
2093 ->getNameStart());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002094
2095 case CXToken_Literal: {
2096 // We have stashed the starting pointer in the ptr_data field. Use it.
2097 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002098 return createCXString(llvm::StringRef(Text, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002099 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002100
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002101 case CXToken_Punctuation:
2102 case CXToken_Comment:
2103 break;
2104 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002105
2106 // We have to find the starting buffer pointer the hard way, by
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002107 // deconstructing the source location.
2108 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2109 if (!CXXUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002110 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002111
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002112 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
2113 std::pair<FileID, unsigned> LocInfo
2114 = CXXUnit->getSourceManager().getDecomposedLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +00002115 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002116 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00002117 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
2118 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00002119 return createCXString("");
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002120
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002121 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002122}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002123
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002124CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
2125 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2126 if (!CXXUnit)
2127 return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002128
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002129 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
2130 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
2131}
2132
2133CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
2134 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregor5352ac02010-01-28 00:27:43 +00002135 if (!CXXUnit)
2136 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002137
2138 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002139 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
2140}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002141
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002142void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
2143 CXToken **Tokens, unsigned *NumTokens) {
2144 if (Tokens)
2145 *Tokens = 0;
2146 if (NumTokens)
2147 *NumTokens = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002148
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002149 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2150 if (!CXXUnit || !Tokens || !NumTokens)
2151 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002152
Douglas Gregorbdf60622010-03-05 21:16:25 +00002153 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
2154
Daniel Dunbar85b988f2010-02-14 08:31:57 +00002155 SourceRange R = cxloc::translateCXSourceRange(Range);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002156 if (R.isInvalid())
2157 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002158
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002159 SourceManager &SourceMgr = CXXUnit->getSourceManager();
2160 std::pair<FileID, unsigned> BeginLocInfo
2161 = SourceMgr.getDecomposedLoc(R.getBegin());
2162 std::pair<FileID, unsigned> EndLocInfo
2163 = SourceMgr.getDecomposedLoc(R.getEnd());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002164
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002165 // Cannot tokenize across files.
2166 if (BeginLocInfo.first != EndLocInfo.first)
2167 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002168
2169 // Create a lexer
Douglas Gregorf715ca12010-03-16 00:06:06 +00002170 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002171 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00002172 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
Douglas Gregor47a3fcd2010-03-16 20:26:15 +00002173 if (Invalid)
2174 return;
Douglas Gregoraea67db2010-03-15 22:54:52 +00002175
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002176 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
2177 CXXUnit->getASTContext().getLangOptions(),
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002178 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002179 Lex.SetCommentRetentionState(true);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002180
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002181 // Lex tokens until we hit the end of the range.
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002182 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002183 llvm::SmallVector<CXToken, 32> CXTokens;
2184 Token Tok;
2185 do {
2186 // Lex the next token
2187 Lex.LexFromRawLexer(Tok);
2188 if (Tok.is(tok::eof))
2189 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002190
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002191 // Initialize the CXToken.
2192 CXToken CXTok;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002193
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002194 // - Common fields
2195 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
2196 CXTok.int_data[2] = Tok.getLength();
2197 CXTok.int_data[3] = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002198
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002199 // - Kind-specific fields
2200 if (Tok.isLiteral()) {
2201 CXTok.int_data[0] = CXToken_Literal;
2202 CXTok.ptr_data = (void *)Tok.getLiteralData();
2203 } else if (Tok.is(tok::identifier)) {
Douglas Gregoraea67db2010-03-15 22:54:52 +00002204 // Lookup the identifier to determine whether we have a keyword.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002205 std::pair<FileID, unsigned> LocInfo
2206 = SourceMgr.getDecomposedLoc(Tok.getLocation());
Douglas Gregorf715ca12010-03-16 00:06:06 +00002207 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002208 llvm::StringRef Buf
Douglas Gregorf715ca12010-03-16 00:06:06 +00002209 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
2210 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00002211 return;
2212
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002213 const char *StartPos = Buf.data() + LocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002214 IdentifierInfo *II
2215 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok, StartPos);
2216 CXTok.int_data[0] = II->getTokenID() == tok::identifier?
2217 CXToken_Identifier
2218 : CXToken_Keyword;
2219 CXTok.ptr_data = II;
2220 } else if (Tok.is(tok::comment)) {
2221 CXTok.int_data[0] = CXToken_Comment;
2222 CXTok.ptr_data = 0;
2223 } else {
2224 CXTok.int_data[0] = CXToken_Punctuation;
2225 CXTok.ptr_data = 0;
2226 }
2227 CXTokens.push_back(CXTok);
2228 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002229
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002230 if (CXTokens.empty())
2231 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002232
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002233 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
2234 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
2235 *NumTokens = CXTokens.size();
2236}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002237
2238typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
2239
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002240enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
2241 CXCursor parent,
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002242 CXClientData client_data) {
2243 AnnotateTokensData *Data = static_cast<AnnotateTokensData *>(client_data);
2244
2245 // We only annotate the locations of declarations, simple
2246 // references, and expressions which directly reference something.
2247 CXCursorKind Kind = clang_getCursorKind(cursor);
2248 if (clang_isDeclaration(Kind) || clang_isReference(Kind)) {
2249 // Okay: We can annotate the location of this declaration with the
2250 // declaration or reference
2251 } else if (clang_isExpression(cursor.kind)) {
2252 if (Kind != CXCursor_DeclRefExpr &&
2253 Kind != CXCursor_MemberRefExpr &&
2254 Kind != CXCursor_ObjCMessageExpr)
2255 return CXChildVisit_Recurse;
2256
2257 CXCursor Referenced = clang_getCursorReferenced(cursor);
2258 if (Referenced == cursor || Referenced == clang_getNullCursor())
2259 return CXChildVisit_Recurse;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002260
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002261 // Okay: we can annotate the location of this expression
Douglas Gregor0396f462010-03-19 05:22:59 +00002262 } else if (clang_isPreprocessing(cursor.kind)) {
2263 // We can always annotate a preprocessing directive/macro instantiation.
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002264 } else {
2265 // Nothing to annotate
2266 return CXChildVisit_Recurse;
2267 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002268
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002269 CXSourceLocation Loc = clang_getCursorLocation(cursor);
2270 (*Data)[Loc.int_data] = cursor;
2271 return CXChildVisit_Recurse;
2272}
2273
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002274void clang_annotateTokens(CXTranslationUnit TU,
2275 CXToken *Tokens, unsigned NumTokens,
2276 CXCursor *Cursors) {
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002277 if (NumTokens == 0)
2278 return;
2279
2280 // Any token we don't specifically annotate will have a NULL cursor.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002281 for (unsigned I = 0; I != NumTokens; ++I)
2282 Cursors[I] = clang_getNullCursor();
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002283
2284 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2285 if (!CXXUnit || !Tokens)
2286 return;
2287
Douglas Gregorbdf60622010-03-05 21:16:25 +00002288 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
2289
Douglas Gregor0396f462010-03-19 05:22:59 +00002290 // Determine the region of interest, which contains all of the tokens.
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002291 SourceRange RegionOfInterest;
2292 RegionOfInterest.setBegin(
2293 cxloc::translateSourceLocation(clang_getTokenLocation(TU, Tokens[0])));
2294 SourceLocation End
Douglas Gregor0396f462010-03-19 05:22:59 +00002295 = cxloc::translateSourceLocation(clang_getTokenLocation(TU,
2296 Tokens[NumTokens - 1]));
Daniel Dunbard52864b2010-02-14 10:02:57 +00002297 RegionOfInterest.setEnd(CXXUnit->getPreprocessor().getLocForEndOfToken(End));
Douglas Gregor2507fa82010-03-19 00:18:31 +00002298
Douglas Gregor0396f462010-03-19 05:22:59 +00002299 // A mapping from the source locations found when re-lexing or traversing the
2300 // region of interest to the corresponding cursors.
2301 AnnotateTokensData Annotated;
2302
2303 // Relex the tokens within the source range to look for preprocessing
2304 // directives.
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002305 SourceManager &SourceMgr = CXXUnit->getSourceManager();
2306 std::pair<FileID, unsigned> BeginLocInfo
2307 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
2308 std::pair<FileID, unsigned> EndLocInfo
2309 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
2310
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002311 llvm::StringRef Buffer;
Douglas Gregor0396f462010-03-19 05:22:59 +00002312 bool Invalid = false;
2313 if (BeginLocInfo.first == EndLocInfo.first &&
2314 ((Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid)),true) &&
2315 !Invalid) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002316 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
2317 CXXUnit->getASTContext().getLangOptions(),
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002318 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
2319 Buffer.end());
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002320 Lex.SetCommentRetentionState(true);
2321
2322 // Lex tokens in raw mode until we hit the end of the range, to avoid
2323 // entering #includes or expanding macros.
Douglas Gregor48072312010-03-18 15:23:44 +00002324 while (true) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002325 Token Tok;
2326 Lex.LexFromRawLexer(Tok);
2327
2328 reprocess:
2329 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
2330 // We have found a preprocessing directive. Gobble it up so that we
2331 // don't see it while preprocessing these tokens later, but keep track of
2332 // all of the token locations inside this preprocessing directive so that
2333 // we can annotate them appropriately.
2334 //
2335 // FIXME: Some simple tests here could identify macro definitions and
2336 // #undefs, to provide specific cursor kinds for those.
2337 std::vector<SourceLocation> Locations;
2338 do {
2339 Locations.push_back(Tok.getLocation());
2340 Lex.LexFromRawLexer(Tok);
2341 } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
2342
2343 using namespace cxcursor;
2344 CXCursor Cursor
2345 = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
2346 Locations.back()),
2347 CXXUnit);
2348 for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
2349 Annotated[Locations[I].getRawEncoding()] = Cursor;
2350 }
2351
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002352 if (Tok.isAtStartOfLine())
2353 goto reprocess;
2354
2355 continue;
2356 }
2357
Douglas Gregor48072312010-03-18 15:23:44 +00002358 if (Tok.is(tok::eof))
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002359 break;
2360 }
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002361 }
Douglas Gregor0396f462010-03-19 05:22:59 +00002362
2363 // Annotate all of the source locations in the region of interest that map to
2364 // a specific cursor.
2365 CXCursor Parent = clang_getTranslationUnitCursor(CXXUnit);
2366 CursorVisitor AnnotateVis(CXXUnit, AnnotateTokensVisitor, &Annotated,
2367 Decl::MaxPCHLevel, RegionOfInterest);
2368 AnnotateVis.VisitChildren(Parent);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002369
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002370 for (unsigned I = 0; I != NumTokens; ++I) {
2371 // Determine whether we saw a cursor at this token's location.
2372 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
2373 if (Pos == Annotated.end())
2374 continue;
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002375
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002376 Cursors[I] = Pos->second;
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002377 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002378}
2379
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002380void clang_disposeTokens(CXTranslationUnit TU,
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002381 CXToken *Tokens, unsigned NumTokens) {
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002382 free(Tokens);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002383}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002384
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002385} // end: extern "C"
2386
2387//===----------------------------------------------------------------------===//
Ted Kremenek16b42592010-03-03 06:36:57 +00002388// Operations for querying linkage of a cursor.
2389//===----------------------------------------------------------------------===//
2390
2391extern "C" {
2392CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
Douglas Gregor0396f462010-03-19 05:22:59 +00002393 if (!clang_isDeclaration(cursor.kind))
2394 return CXLinkage_Invalid;
2395
Ted Kremenek16b42592010-03-03 06:36:57 +00002396 Decl *D = cxcursor::getCursorDecl(cursor);
2397 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
2398 switch (ND->getLinkage()) {
2399 case NoLinkage: return CXLinkage_NoLinkage;
2400 case InternalLinkage: return CXLinkage_Internal;
2401 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
2402 case ExternalLinkage: return CXLinkage_External;
2403 };
2404
2405 return CXLinkage_Invalid;
2406}
2407} // end: extern "C"
2408
2409//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00002410// CXString Operations.
2411//===----------------------------------------------------------------------===//
2412
2413extern "C" {
2414const char *clang_getCString(CXString string) {
2415 return string.Spelling;
2416}
2417
2418void clang_disposeString(CXString string) {
2419 if (string.MustFreeString && string.Spelling)
2420 free((void*)string.Spelling);
2421}
Ted Kremenek04bb7162010-01-22 22:44:15 +00002422
Ted Kremenekfb480492010-01-13 21:46:36 +00002423} // end: extern "C"
Ted Kremenek04bb7162010-01-22 22:44:15 +00002424
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002425namespace clang { namespace cxstring {
2426CXString createCXString(const char *String, bool DupString){
2427 CXString Str;
2428 if (DupString) {
2429 Str.Spelling = strdup(String);
2430 Str.MustFreeString = 1;
2431 } else {
2432 Str.Spelling = String;
2433 Str.MustFreeString = 0;
2434 }
2435 return Str;
2436}
2437
2438CXString createCXString(llvm::StringRef String, bool DupString) {
2439 CXString Result;
2440 if (DupString || (!String.empty() && String.data()[String.size()] != 0)) {
2441 char *Spelling = (char *)malloc(String.size() + 1);
2442 memmove(Spelling, String.data(), String.size());
2443 Spelling[String.size()] = 0;
2444 Result.Spelling = Spelling;
2445 Result.MustFreeString = 1;
2446 } else {
2447 Result.Spelling = String.data();
2448 Result.MustFreeString = 0;
2449 }
2450 return Result;
2451}
2452}}
2453
Ted Kremenek04bb7162010-01-22 22:44:15 +00002454//===----------------------------------------------------------------------===//
2455// Misc. utility functions.
2456//===----------------------------------------------------------------------===//
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002457
Ted Kremenek04bb7162010-01-22 22:44:15 +00002458extern "C" {
2459
Ted Kremeneka2a9d6e2010-02-12 22:54:40 +00002460CXString clang_getClangVersion() {
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002461 return createCXString(getClangFullVersion());
Ted Kremenek04bb7162010-01-22 22:44:15 +00002462}
2463
2464} // end: extern "C"