blob: 01130e22773ddb6790ee198233f9b446b88286b5 [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 Gregor788f5a12010-03-20 00:41:21 +0000237
238 std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
239 getPreprocessedEntities();
240
Douglas Gregorb1373d02010-01-20 20:59:29 +0000241 bool VisitChildren(CXCursor Parent);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000242
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000243 // Declaration visitors
Ted Kremenek09dfa372010-02-18 05:46:33 +0000244 bool VisitAttributes(Decl *D);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000245 bool VisitDeclContext(DeclContext *DC);
Ted Kremenek4540c9c2010-02-18 18:47:08 +0000246 bool VisitTranslationUnitDecl(TranslationUnitDecl *D);
247 bool VisitTypedefDecl(TypedefDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000248 bool VisitTagDecl(TagDecl *D);
249 bool VisitEnumConstantDecl(EnumConstantDecl *D);
250 bool VisitDeclaratorDecl(DeclaratorDecl *DD);
251 bool VisitFunctionDecl(FunctionDecl *ND);
252 bool VisitFieldDecl(FieldDecl *D);
Ted Kremenek4540c9c2010-02-18 18:47:08 +0000253 bool VisitVarDecl(VarDecl *);
Ted Kremenek79758f62010-02-18 22:36:18 +0000254 bool VisitObjCMethodDecl(ObjCMethodDecl *ND);
255 bool VisitObjCContainerDecl(ObjCContainerDecl *D);
256 bool VisitObjCCategoryDecl(ObjCCategoryDecl *ND);
257 bool VisitObjCProtocolDecl(ObjCProtocolDecl *PID);
258 bool VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
259 bool VisitObjCImplDecl(ObjCImplDecl *D);
260 bool VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
261 bool VisitObjCImplementationDecl(ObjCImplementationDecl *D);
262 // FIXME: ObjCPropertyDecl requires TypeSourceInfo, getter/setter locations,
263 // etc.
264 // FIXME: ObjCCompatibleAliasDecl requires aliased-class locations.
265 bool VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D);
266 bool VisitObjCClassDecl(ObjCClassDecl *D);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000267
268 // Type visitors
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000269 // FIXME: QualifiedTypeLoc doesn't provide any location information
270 bool VisitBuiltinTypeLoc(BuiltinTypeLoc TL);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000271 bool VisitTypedefTypeLoc(TypedefTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000272 bool VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL);
273 bool VisitTagTypeLoc(TagTypeLoc TL);
274 // FIXME: TemplateTypeParmTypeLoc doesn't provide any location information
275 bool VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL);
276 bool VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL);
277 bool VisitPointerTypeLoc(PointerTypeLoc TL);
278 bool VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL);
279 bool VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL);
280 bool VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL);
281 bool VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL);
282 bool VisitFunctionTypeLoc(FunctionTypeLoc TL);
283 bool VisitArrayTypeLoc(ArrayTypeLoc TL);
Douglas Gregor2332c112010-01-21 20:48:56 +0000284 // FIXME: Implement for TemplateSpecializationTypeLoc
285 // FIXME: Implement visitors here when the unimplemented TypeLocs get
286 // implemented
287 bool VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL);
288 bool VisitTypeOfTypeLoc(TypeOfTypeLoc TL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000289
Douglas Gregora59e3902010-01-21 23:27:09 +0000290 // Statement visitors
291 bool VisitStmt(Stmt *S);
292 bool VisitDeclStmt(DeclStmt *S);
Douglas Gregorf5bab412010-01-22 01:00:11 +0000293 // FIXME: LabelStmt label?
294 bool VisitIfStmt(IfStmt *S);
295 bool VisitSwitchStmt(SwitchStmt *S);
Douglas Gregor263b47b2010-01-25 16:12:32 +0000296 bool VisitWhileStmt(WhileStmt *S);
297 bool VisitForStmt(ForStmt *S);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000298
Douglas Gregor336fd812010-01-23 00:40:08 +0000299 // Expression visitors
300 bool VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E);
301 bool VisitExplicitCastExpr(ExplicitCastExpr *E);
302 bool VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
Douglas Gregorc2350e52010-03-08 16:40:19 +0000303 bool VisitObjCMessageExpr(ObjCMessageExpr *E);
Steve Naroff89922f82009-08-31 00:59:03 +0000304};
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000305
Ted Kremenekab188932010-01-05 19:32:54 +0000306} // end anonymous namespace
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000307
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000308RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000309 return RangeCompare(TU->getSourceManager(), R, RegionOfInterest);
310}
311
Douglas Gregorb1373d02010-01-20 20:59:29 +0000312/// \brief Visit the given cursor and, if requested by the visitor,
313/// its children.
314///
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000315/// \param Cursor the cursor to visit.
316///
317/// \param CheckRegionOfInterest if true, then the caller already checked that
318/// this cursor is within the region of interest.
319///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000320/// \returns true if the visitation should be aborted, false if it
321/// should continue.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000322bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
Douglas Gregorb1373d02010-01-20 20:59:29 +0000323 if (clang_isInvalid(Cursor.kind))
324 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000325
Douglas Gregorb1373d02010-01-20 20:59:29 +0000326 if (clang_isDeclaration(Cursor.kind)) {
327 Decl *D = getCursorDecl(Cursor);
328 assert(D && "Invalid declaration cursor");
329 if (D->getPCHLevel() > MaxPCHLevel)
330 return false;
331
332 if (D->isImplicit())
333 return false;
334 }
335
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000336 // If we have a range of interest, and this cursor doesn't intersect with it,
337 // we're done.
338 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
Daniel Dunbarf408f322010-02-14 08:32:05 +0000339 SourceRange Range =
340 cxloc::translateCXSourceRange(clang_getCursorExtent(Cursor));
341 if (Range.isInvalid() || CompareRegionOfInterest(Range))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000342 return false;
343 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000344
Douglas Gregorb1373d02010-01-20 20:59:29 +0000345 switch (Visitor(Cursor, Parent, ClientData)) {
346 case CXChildVisit_Break:
347 return true;
348
349 case CXChildVisit_Continue:
350 return false;
351
352 case CXChildVisit_Recurse:
353 return VisitChildren(Cursor);
354 }
355
Douglas Gregorfd643772010-01-25 16:45:46 +0000356 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000357}
358
Douglas Gregor788f5a12010-03-20 00:41:21 +0000359std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
360CursorVisitor::getPreprocessedEntities() {
361 PreprocessingRecord &PPRec
362 = *TU->getPreprocessor().getPreprocessingRecord();
363
364 bool OnlyLocalDecls
365 = !TU->isMainFileAST() && TU->getOnlyLocalDecls();
366
367 // There is no region of interest; we have to walk everything.
368 if (RegionOfInterest.isInvalid())
369 return std::make_pair(PPRec.begin(OnlyLocalDecls),
370 PPRec.end(OnlyLocalDecls));
371
372 // Find the file in which the region of interest lands.
373 SourceManager &SM = TU->getSourceManager();
374 std::pair<FileID, unsigned> Begin
375 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getBegin());
376 std::pair<FileID, unsigned> End
377 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getEnd());
378
379 // The region of interest spans files; we have to walk everything.
380 if (Begin.first != End.first)
381 return std::make_pair(PPRec.begin(OnlyLocalDecls),
382 PPRec.end(OnlyLocalDecls));
383
384 ASTUnit::PreprocessedEntitiesByFileMap &ByFileMap
385 = TU->getPreprocessedEntitiesByFile();
386 if (ByFileMap.empty()) {
387 // Build the mapping from files to sets of preprocessed entities.
388 for (PreprocessingRecord::iterator E = PPRec.begin(OnlyLocalDecls),
389 EEnd = PPRec.end(OnlyLocalDecls);
390 E != EEnd; ++E) {
391 std::pair<FileID, unsigned> P
392 = SM.getDecomposedInstantiationLoc((*E)->getSourceRange().getBegin());
393 ByFileMap[P.first].push_back(*E);
394 }
395 }
396
397 return std::make_pair(ByFileMap[Begin.first].begin(),
398 ByFileMap[Begin.first].end());
399}
400
Douglas Gregorb1373d02010-01-20 20:59:29 +0000401/// \brief Visit the children of the given cursor.
402///
403/// \returns true if the visitation should be aborted, false if it
404/// should continue.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000405bool CursorVisitor::VisitChildren(CXCursor Cursor) {
Douglas Gregora59e3902010-01-21 23:27:09 +0000406 if (clang_isReference(Cursor.kind)) {
407 // By definition, references have no children.
408 return false;
409 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000410
411 // Set the Parent field to Cursor, then back to its old value once we're
Douglas Gregorb1373d02010-01-20 20:59:29 +0000412 // done.
413 class SetParentRAII {
414 CXCursor &Parent;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000415 Decl *&StmtParent;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000416 CXCursor OldParent;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000417
Douglas Gregorb1373d02010-01-20 20:59:29 +0000418 public:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000419 SetParentRAII(CXCursor &Parent, Decl *&StmtParent, CXCursor NewParent)
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000420 : Parent(Parent), StmtParent(StmtParent), OldParent(Parent)
Douglas Gregorb1373d02010-01-20 20:59:29 +0000421 {
422 Parent = NewParent;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000423 if (clang_isDeclaration(Parent.kind))
424 StmtParent = getCursorDecl(Parent);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000425 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000426
Douglas Gregorb1373d02010-01-20 20:59:29 +0000427 ~SetParentRAII() {
428 Parent = OldParent;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000429 if (clang_isDeclaration(Parent.kind))
430 StmtParent = getCursorDecl(Parent);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000431 }
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000432 } SetParent(Parent, StmtParent, Cursor);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000433
Douglas Gregorb1373d02010-01-20 20:59:29 +0000434 if (clang_isDeclaration(Cursor.kind)) {
435 Decl *D = getCursorDecl(Cursor);
436 assert(D && "Invalid declaration cursor");
Ted Kremenek539311e2010-02-18 18:47:01 +0000437 return VisitAttributes(D) || Visit(D);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000438 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000439
Douglas Gregora59e3902010-01-21 23:27:09 +0000440 if (clang_isStatement(Cursor.kind))
441 return Visit(getCursorStmt(Cursor));
442 if (clang_isExpression(Cursor.kind))
443 return Visit(getCursorExpr(Cursor));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000444
Douglas Gregorb1373d02010-01-20 20:59:29 +0000445 if (clang_isTranslationUnit(Cursor.kind)) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000446 ASTUnit *CXXUnit = getCursorASTUnit(Cursor);
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000447 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
448 RegionOfInterest.isInvalid()) {
Douglas Gregor7b691f332010-01-20 21:13:59 +0000449 const std::vector<Decl*> &TLDs = CXXUnit->getTopLevelDecls();
450 for (std::vector<Decl*>::const_iterator it = TLDs.begin(),
451 ie = TLDs.end(); it != ie; ++it) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000452 if (Visit(MakeCXCursor(*it, CXXUnit), true))
Douglas Gregor7b691f332010-01-20 21:13:59 +0000453 return true;
454 }
Douglas Gregor0396f462010-03-19 05:22:59 +0000455 } else if (VisitDeclContext(
456 CXXUnit->getASTContext().getTranslationUnitDecl()))
457 return true;
Bob Wilson3178cb62010-03-19 03:57:57 +0000458
Douglas Gregor0396f462010-03-19 05:22:59 +0000459 // Walk the preprocessing record.
Daniel Dunbar8de30ff2010-03-20 01:11:56 +0000460 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000461 // FIXME: Once we have the ability to deserialize a preprocessing record,
462 // do so.
Douglas Gregor788f5a12010-03-20 00:41:21 +0000463 PreprocessingRecord::iterator E, EEnd;
464 for (llvm::tie(E, EEnd) = getPreprocessedEntities(); E != EEnd; ++E) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000465 if (MacroInstantiation *MI = dyn_cast<MacroInstantiation>(*E)) {
466 if (Visit(MakeMacroInstantiationCursor(MI, CXXUnit)))
467 return true;
Douglas Gregor788f5a12010-03-20 00:41:21 +0000468
Douglas Gregor0396f462010-03-19 05:22:59 +0000469 continue;
470 }
471
472 if (MacroDefinition *MD = dyn_cast<MacroDefinition>(*E)) {
473 if (Visit(MakeMacroDefinitionCursor(MD, CXXUnit)))
474 return true;
475
476 continue;
477 }
478 }
479 }
Douglas Gregor7b691f332010-01-20 21:13:59 +0000480 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000481 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000482
Douglas Gregorb1373d02010-01-20 20:59:29 +0000483 // Nothing to visit at the moment.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000484 return false;
485}
486
Douglas Gregorb1373d02010-01-20 20:59:29 +0000487bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000488 for (DeclContext::decl_iterator
Douglas Gregorb1373d02010-01-20 20:59:29 +0000489 I = DC->decls_begin(), E = DC->decls_end(); I != E; ++I) {
Ted Kremenek09dfa372010-02-18 05:46:33 +0000490
Daniel Dunbard52864b2010-02-14 10:02:57 +0000491 CXCursor Cursor = MakeCXCursor(*I, TU);
492
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000493 if (RegionOfInterest.isValid()) {
Daniel Dunbard52864b2010-02-14 10:02:57 +0000494 SourceRange Range =
495 cxloc::translateCXSourceRange(clang_getCursorExtent(Cursor));
496 if (Range.isInvalid())
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000497 continue;
Daniel Dunbard52864b2010-02-14 10:02:57 +0000498
499 switch (CompareRegionOfInterest(Range)) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000500 case RangeBefore:
501 // This declaration comes before the region of interest; skip it.
502 continue;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000503
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000504 case RangeAfter:
505 // This declaration comes after the region of interest; we're done.
506 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000507
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000508 case RangeOverlap:
509 // This declaration overlaps the region of interest; visit it.
510 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000511 }
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000512 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000513
Daniel Dunbard52864b2010-02-14 10:02:57 +0000514 if (Visit(Cursor, true))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000515 return true;
516 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000517
Douglas Gregorb1373d02010-01-20 20:59:29 +0000518 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000519}
520
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000521bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
522 llvm_unreachable("Translation units are visited directly by Visit()");
523 return false;
524}
525
526bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
527 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
528 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000529
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000530 return false;
531}
532
533bool CursorVisitor::VisitTagDecl(TagDecl *D) {
534 return VisitDeclContext(D);
535}
536
537bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
538 if (Expr *Init = D->getInitExpr())
539 return Visit(MakeCXCursor(Init, StmtParent, TU));
540 return false;
541}
542
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000543bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
544 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
545 if (Visit(TSInfo->getTypeLoc()))
546 return true;
547
548 return false;
549}
550
Douglas Gregorb1373d02010-01-20 20:59:29 +0000551bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000552 if (VisitDeclaratorDecl(ND))
553 return true;
554
Douglas Gregora59e3902010-01-21 23:27:09 +0000555 if (ND->isThisDeclarationADefinition() &&
556 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
557 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000558
Douglas Gregorb1373d02010-01-20 20:59:29 +0000559 return false;
560}
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000561
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000562bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
563 if (VisitDeclaratorDecl(D))
564 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000565
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000566 if (Expr *BitWidth = D->getBitWidth())
567 return Visit(MakeCXCursor(BitWidth, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000568
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000569 return false;
570}
571
572bool CursorVisitor::VisitVarDecl(VarDecl *D) {
573 if (VisitDeclaratorDecl(D))
574 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000575
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000576 if (Expr *Init = D->getInit())
577 return Visit(MakeCXCursor(Init, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000578
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000579 return false;
580}
581
582bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
Douglas Gregor4bc1cb62010-03-08 14:59:44 +0000583 if (TypeSourceInfo *TSInfo = ND->getResultTypeSourceInfo())
584 if (Visit(TSInfo->getTypeLoc()))
585 return true;
586
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000587 for (ObjCMethodDecl::param_iterator P = ND->param_begin(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000588 PEnd = ND->param_end();
589 P != PEnd; ++P) {
590 if (Visit(MakeCXCursor(*P, TU)))
591 return true;
592 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000593
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000594 if (ND->isThisDeclarationADefinition() &&
595 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
596 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000597
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000598 return false;
599}
600
Douglas Gregora59e3902010-01-21 23:27:09 +0000601bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
602 return VisitDeclContext(D);
603}
604
Douglas Gregorb1373d02010-01-20 20:59:29 +0000605bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000606 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
607 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000608 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000609
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000610 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
611 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
612 E = ND->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000613 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000614 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000615
Douglas Gregora59e3902010-01-21 23:27:09 +0000616 return VisitObjCContainerDecl(ND);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000617}
618
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000619bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
620 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
621 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
622 E = PID->protocol_end(); I != E; ++I, ++PL)
623 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
624 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000625
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000626 return VisitObjCContainerDecl(PID);
627}
628
Douglas Gregorb1373d02010-01-20 20:59:29 +0000629bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000630 // Issue callbacks for super class.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000631 if (D->getSuperClass() &&
632 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000633 D->getSuperClassLoc(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000634 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000635 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000636
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000637 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
638 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
639 E = D->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000640 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000641 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000642
Douglas Gregora59e3902010-01-21 23:27:09 +0000643 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000644}
645
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000646bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
647 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000648}
649
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000650bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
Ted Kremenekebfa3392010-03-19 20:39:03 +0000651 // 'ID' could be null when dealing with invalid code.
652 if (ObjCInterfaceDecl *ID = D->getClassInterface())
653 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
654 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000655
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000656 return VisitObjCImplDecl(D);
657}
658
659bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
660#if 0
661 // Issue callbacks for super class.
662 // FIXME: No source location information!
663 if (D->getSuperClass() &&
664 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000665 D->getSuperClassLoc(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000666 TU)))
667 return true;
668#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000669
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000670 return VisitObjCImplDecl(D);
671}
672
673bool CursorVisitor::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D) {
674 ObjCForwardProtocolDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
675 for (ObjCForwardProtocolDecl::protocol_iterator I = D->protocol_begin(),
676 E = D->protocol_end();
677 I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000678 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000679 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000680
681 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000682}
683
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000684bool CursorVisitor::VisitObjCClassDecl(ObjCClassDecl *D) {
685 for (ObjCClassDecl::iterator C = D->begin(), CEnd = D->end(); C != CEnd; ++C)
686 if (Visit(MakeCursorObjCClassRef(C->getInterface(), C->getLocation(), TU)))
687 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000688
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000689 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000690}
691
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000692bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
693 ASTContext &Context = TU->getASTContext();
694
695 // Some builtin types (such as Objective-C's "id", "sel", and
696 // "Class") have associated declarations. Create cursors for those.
697 QualType VisitType;
698 switch (TL.getType()->getAs<BuiltinType>()->getKind()) {
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000699 case BuiltinType::Void:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000700 case BuiltinType::Bool:
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000701 case BuiltinType::Char_U:
702 case BuiltinType::UChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000703 case BuiltinType::Char16:
704 case BuiltinType::Char32:
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000705 case BuiltinType::UShort:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000706 case BuiltinType::UInt:
707 case BuiltinType::ULong:
708 case BuiltinType::ULongLong:
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000709 case BuiltinType::UInt128:
710 case BuiltinType::Char_S:
711 case BuiltinType::SChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000712 case BuiltinType::WChar:
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000713 case BuiltinType::Short:
714 case BuiltinType::Int:
715 case BuiltinType::Long:
716 case BuiltinType::LongLong:
717 case BuiltinType::Int128:
718 case BuiltinType::Float:
719 case BuiltinType::Double:
720 case BuiltinType::LongDouble:
721 case BuiltinType::NullPtr:
722 case BuiltinType::Overload:
723 case BuiltinType::Dependent:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000724 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000725
726 case BuiltinType::UndeducedAuto: // FIXME: Deserves a cursor?
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000727 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000728
Ted Kremenekc4174cc2010-02-18 18:52:18 +0000729 case BuiltinType::ObjCId:
730 VisitType = Context.getObjCIdType();
731 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000732
733 case BuiltinType::ObjCClass:
734 VisitType = Context.getObjCClassType();
735 break;
736
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000737 case BuiltinType::ObjCSel:
738 VisitType = Context.getObjCSelType();
739 break;
740 }
741
742 if (!VisitType.isNull()) {
743 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000744 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000745 TU));
746 }
747
748 return false;
749}
750
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000751bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
752 return Visit(MakeCursorTypeRef(TL.getTypedefDecl(), TL.getNameLoc(), TU));
753}
754
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000755bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
756 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
757}
758
759bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
760 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
761}
762
763bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
764 if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
765 return true;
766
767 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
768 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
769 TU)))
770 return true;
771 }
772
773 return false;
774}
775
776bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
777 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseTypeLoc()))
778 return true;
779
780 if (TL.hasProtocolsAsWritten()) {
781 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000782 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I),
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000783 TL.getProtocolLoc(I),
784 TU)))
785 return true;
786 }
787 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000788
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000789 return false;
790}
791
792bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
793 return Visit(TL.getPointeeLoc());
794}
795
796bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
797 return Visit(TL.getPointeeLoc());
798}
799
800bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
801 return Visit(TL.getPointeeLoc());
802}
803
804bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000805 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000806}
807
808bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000809 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000810}
811
812bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
813 if (Visit(TL.getResultLoc()))
814 return true;
815
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000816 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
817 if (Visit(MakeCXCursor(TL.getArg(I), TU)))
818 return true;
819
820 return false;
821}
822
823bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
824 if (Visit(TL.getElementLoc()))
825 return true;
826
827 if (Expr *Size = TL.getSizeExpr())
828 return Visit(MakeCXCursor(Size, StmtParent, TU));
829
830 return false;
831}
832
Douglas Gregor2332c112010-01-21 20:48:56 +0000833bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
834 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
835}
836
837bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
838 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
839 return Visit(TSInfo->getTypeLoc());
840
841 return false;
842}
843
Douglas Gregora59e3902010-01-21 23:27:09 +0000844bool CursorVisitor::VisitStmt(Stmt *S) {
845 for (Stmt::child_iterator Child = S->child_begin(), ChildEnd = S->child_end();
846 Child != ChildEnd; ++Child) {
Daniel Dunbar54d67ca2010-01-25 00:40:30 +0000847 if (*Child && Visit(MakeCXCursor(*Child, StmtParent, TU)))
Douglas Gregora59e3902010-01-21 23:27:09 +0000848 return true;
849 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000850
Douglas Gregora59e3902010-01-21 23:27:09 +0000851 return false;
852}
853
854bool CursorVisitor::VisitDeclStmt(DeclStmt *S) {
855 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
856 D != DEnd; ++D) {
Douglas Gregor263b47b2010-01-25 16:12:32 +0000857 if (*D && Visit(MakeCXCursor(*D, TU)))
Douglas Gregora59e3902010-01-21 23:27:09 +0000858 return true;
859 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000860
Douglas Gregora59e3902010-01-21 23:27:09 +0000861 return false;
862}
863
Douglas Gregorf5bab412010-01-22 01:00:11 +0000864bool CursorVisitor::VisitIfStmt(IfStmt *S) {
865 if (VarDecl *Var = S->getConditionVariable()) {
866 if (Visit(MakeCXCursor(Var, TU)))
867 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000868 }
869
Douglas Gregor263b47b2010-01-25 16:12:32 +0000870 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
871 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +0000872 if (S->getThen() && Visit(MakeCXCursor(S->getThen(), StmtParent, TU)))
873 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +0000874 if (S->getElse() && Visit(MakeCXCursor(S->getElse(), StmtParent, TU)))
875 return true;
876
877 return false;
878}
879
880bool CursorVisitor::VisitSwitchStmt(SwitchStmt *S) {
881 if (VarDecl *Var = S->getConditionVariable()) {
882 if (Visit(MakeCXCursor(Var, TU)))
883 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000884 }
885
Douglas Gregor263b47b2010-01-25 16:12:32 +0000886 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
887 return true;
888 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
889 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000890
Douglas Gregor263b47b2010-01-25 16:12:32 +0000891 return false;
892}
893
894bool CursorVisitor::VisitWhileStmt(WhileStmt *S) {
895 if (VarDecl *Var = S->getConditionVariable()) {
896 if (Visit(MakeCXCursor(Var, TU)))
897 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000898 }
899
Douglas Gregor263b47b2010-01-25 16:12:32 +0000900 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
901 return true;
902 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
Douglas Gregorf5bab412010-01-22 01:00:11 +0000903 return true;
904
Douglas Gregor263b47b2010-01-25 16:12:32 +0000905 return false;
906}
907
908bool CursorVisitor::VisitForStmt(ForStmt *S) {
909 if (S->getInit() && Visit(MakeCXCursor(S->getInit(), StmtParent, TU)))
910 return true;
911 if (VarDecl *Var = S->getConditionVariable()) {
912 if (Visit(MakeCXCursor(Var, TU)))
913 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000914 }
915
Douglas Gregor263b47b2010-01-25 16:12:32 +0000916 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
917 return true;
918 if (S->getInc() && Visit(MakeCXCursor(S->getInc(), StmtParent, TU)))
919 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +0000920 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
921 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000922
Douglas Gregorf5bab412010-01-22 01:00:11 +0000923 return false;
924}
925
Douglas Gregor336fd812010-01-23 00:40:08 +0000926bool CursorVisitor::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E) {
927 if (E->isArgumentType()) {
928 if (TypeSourceInfo *TSInfo = E->getArgumentTypeInfo())
929 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000930
Douglas Gregor336fd812010-01-23 00:40:08 +0000931 return false;
932 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000933
Douglas Gregor336fd812010-01-23 00:40:08 +0000934 return VisitExpr(E);
935}
936
937bool CursorVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
938 if (TypeSourceInfo *TSInfo = E->getTypeInfoAsWritten())
939 if (Visit(TSInfo->getTypeLoc()))
940 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000941
Douglas Gregor336fd812010-01-23 00:40:08 +0000942 return VisitCastExpr(E);
943}
944
945bool CursorVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
946 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
947 if (Visit(TSInfo->getTypeLoc()))
948 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000949
Douglas Gregor336fd812010-01-23 00:40:08 +0000950 return VisitExpr(E);
951}
952
Douglas Gregorc2350e52010-03-08 16:40:19 +0000953bool CursorVisitor::VisitObjCMessageExpr(ObjCMessageExpr *E) {
954 ObjCMessageExpr::ClassInfo CI = E->getClassInfo();
955 if (CI.Decl && Visit(MakeCursorObjCClassRef(CI.Decl, CI.Loc, TU)))
956 return true;
957
958 return VisitExpr(E);
959}
960
Ted Kremenek09dfa372010-02-18 05:46:33 +0000961bool CursorVisitor::VisitAttributes(Decl *D) {
962 for (const Attr *A = D->getAttrs(); A; A = A->getNext())
963 if (Visit(MakeCXCursor(A, D, TU)))
964 return true;
965
966 return false;
967}
968
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000969extern "C" {
Douglas Gregor0a812cf2010-02-18 23:07:20 +0000970CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
971 int displayDiagnostics) {
Douglas Gregora030b7c2010-01-22 20:35:53 +0000972 CIndexer *CIdxr = new CIndexer();
Steve Naroffe56b4ba2009-10-20 14:46:24 +0000973 if (excludeDeclarationsFromPCH)
974 CIdxr->setOnlyLocalDecls();
Douglas Gregor0a812cf2010-02-18 23:07:20 +0000975 if (displayDiagnostics)
976 CIdxr->setDisplayDiagnostics();
Steve Naroffe56b4ba2009-10-20 14:46:24 +0000977 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +0000978}
979
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000980void clang_disposeIndex(CXIndex CIdx) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +0000981 if (CIdx)
982 delete static_cast<CIndexer *>(CIdx);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +0000983}
984
Daniel Dunbar8506dde2009-12-03 01:54:28 +0000985void clang_setUseExternalASTGeneration(CXIndex CIdx, int value) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +0000986 if (CIdx) {
987 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
988 CXXIdx->setUseExternalASTGeneration(value);
989 }
Daniel Dunbar8506dde2009-12-03 01:54:28 +0000990}
991
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000992CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
Douglas Gregora88084b2010-02-18 18:08:43 +0000993 const char *ast_filename) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +0000994 if (!CIdx)
995 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000996
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000997 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000998
Douglas Gregor28019772010-04-05 23:52:57 +0000999 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
1000 return ASTUnit::LoadFromPCHFile(ast_filename, Diags,
Douglas Gregora88084b2010-02-18 18:08:43 +00001001 CXXIdx->getOnlyLocalDecls(),
1002 0, 0, true);
Steve Naroff600866c2009-08-27 19:51:58 +00001003}
1004
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001005CXTranslationUnit
1006clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
1007 const char *source_filename,
1008 int num_command_line_args,
Douglas Gregor4db64a42010-01-23 00:14:00 +00001009 const char **command_line_args,
1010 unsigned num_unsaved_files,
Douglas Gregora88084b2010-02-18 18:08:43 +00001011 struct CXUnsavedFile *unsaved_files) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001012 if (!CIdx)
1013 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001014
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001015 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
1016
Douglas Gregor5352ac02010-01-28 00:27:43 +00001017 // Configure the diagnostics.
1018 DiagnosticOptions DiagOpts;
Douglas Gregor28019772010-04-05 23:52:57 +00001019 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
1020 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001021
Douglas Gregor4db64a42010-01-23 00:14:00 +00001022 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
1023 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattnera0a270c2010-04-05 22:42:27 +00001024 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001025 const llvm::MemoryBuffer *Buffer
Chris Lattnera0a270c2010-04-05 22:42:27 +00001026 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregor4db64a42010-01-23 00:14:00 +00001027 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
1028 Buffer));
1029 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001030
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001031 if (!CXXIdx->getUseExternalASTGeneration()) {
1032 llvm::SmallVector<const char *, 16> Args;
1033
1034 // The 'source_filename' argument is optional. If the caller does not
1035 // specify it then it is assumed that the source file is specified
1036 // in the actual argument list.
1037 if (source_filename)
1038 Args.push_back(source_filename);
1039 Args.insert(Args.end(), command_line_args,
1040 command_line_args + num_command_line_args);
Douglas Gregor94dc8f62010-03-19 16:15:56 +00001041 Args.push_back("-Xclang");
1042 Args.push_back("-detailed-preprocessing-record");
Douglas Gregor5352ac02010-01-28 00:27:43 +00001043 unsigned NumErrors = Diags->getNumErrors();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001044
Ted Kremenek29b72842010-01-07 22:49:05 +00001045#ifdef USE_CRASHTRACER
1046 ArgsCrashTracerInfo ACTI(Args);
Ted Kremenek8a8da7d2010-01-06 03:42:32 +00001047#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001048
Daniel Dunbar94220972009-12-05 02:17:18 +00001049 llvm::OwningPtr<ASTUnit> Unit(
1050 ASTUnit::LoadFromCommandLine(Args.data(), Args.data() + Args.size(),
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001051 Diags,
Daniel Dunbar869824e2009-12-13 03:46:13 +00001052 CXXIdx->getClangResourcesPath(),
Daniel Dunbar94220972009-12-05 02:17:18 +00001053 CXXIdx->getOnlyLocalDecls(),
Douglas Gregor4db64a42010-01-23 00:14:00 +00001054 RemappedFiles.data(),
Douglas Gregora88084b2010-02-18 18:08:43 +00001055 RemappedFiles.size(),
Douglas Gregor94dc8f62010-03-19 16:15:56 +00001056 /*CaptureDiagnostics=*/true));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001057
Daniel Dunbar94220972009-12-05 02:17:18 +00001058 // FIXME: Until we have broader testing, just drop the entire AST if we
1059 // encountered an error.
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001060 if (NumErrors != Diags->getNumErrors()) {
Ted Kremenek34f6a322010-03-05 22:43:29 +00001061 // Make sure to check that 'Unit' is non-NULL.
1062 if (CXXIdx->getDisplayDiagnostics() && Unit.get()) {
Douglas Gregor405634b2010-04-05 18:10:21 +00001063 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
1064 DEnd = Unit->stored_diag_end();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001065 D != DEnd; ++D) {
1066 CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOptions());
Douglas Gregor274f1902010-02-22 23:17:23 +00001067 CXString Msg = clang_formatDiagnostic(&Diag,
1068 clang_defaultDiagnosticDisplayOptions());
1069 fprintf(stderr, "%s\n", clang_getCString(Msg));
1070 clang_disposeString(Msg);
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001071 }
Douglas Gregor274f1902010-02-22 23:17:23 +00001072#ifdef LLVM_ON_WIN32
1073 // On Windows, force a flush, since there may be multiple copies of
1074 // stderr and stdout in the file system, all with different buffers
1075 // but writing to the same device.
1076 fflush(stderr);
Ted Kremenek83c51842010-03-26 01:34:51 +00001077#endif
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001078 }
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001079 }
Daniel Dunbar94220972009-12-05 02:17:18 +00001080
1081 return Unit.take();
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001082 }
1083
Ted Kremenek139ba862009-10-22 00:03:57 +00001084 // Build up the arguments for invoking 'clang'.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001085 std::vector<const char *> argv;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001086
Ted Kremenek139ba862009-10-22 00:03:57 +00001087 // First add the complete path to the 'clang' executable.
1088 llvm::sys::Path ClangPath = static_cast<CIndexer *>(CIdx)->getClangPath();
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00001089 argv.push_back(ClangPath.c_str());
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001090
Ted Kremenek139ba862009-10-22 00:03:57 +00001091 // Add the '-emit-ast' option as our execution mode for 'clang'.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001092 argv.push_back("-emit-ast");
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001093
Ted Kremenek139ba862009-10-22 00:03:57 +00001094 // The 'source_filename' argument is optional. If the caller does not
1095 // specify it then it is assumed that the source file is specified
1096 // in the actual argument list.
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001097 if (source_filename)
1098 argv.push_back(source_filename);
Ted Kremenek139ba862009-10-22 00:03:57 +00001099
Steve Naroff37b5ac22009-10-15 20:50:09 +00001100 // Generate a temporary name for the AST file.
Ted Kremenek139ba862009-10-22 00:03:57 +00001101 argv.push_back("-o");
Benjamin Kramerc2a98162010-03-13 21:22:49 +00001102 char astTmpFile[L_tmpnam];
1103 argv.push_back(tmpnam(astTmpFile));
Ted Kremenek139ba862009-10-22 00:03:57 +00001104
Douglas Gregor4db64a42010-01-23 00:14:00 +00001105 // Remap any unsaved files to temporary files.
1106 std::vector<llvm::sys::Path> TemporaryFiles;
1107 std::vector<std::string> RemapArgs;
1108 if (RemapFiles(num_unsaved_files, unsaved_files, RemapArgs, TemporaryFiles))
1109 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001110
Douglas Gregor4db64a42010-01-23 00:14:00 +00001111 // The pointers into the elements of RemapArgs are stable because we
1112 // won't be adding anything to RemapArgs after this point.
1113 for (unsigned i = 0, e = RemapArgs.size(); i != e; ++i)
1114 argv.push_back(RemapArgs[i].c_str());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001115
Ted Kremenek139ba862009-10-22 00:03:57 +00001116 // Process the compiler options, stripping off '-o', '-c', '-fsyntax-only'.
1117 for (int i = 0; i < num_command_line_args; ++i)
1118 if (const char *arg = command_line_args[i]) {
1119 if (strcmp(arg, "-o") == 0) {
1120 ++i; // Also skip the matching argument.
1121 continue;
1122 }
1123 if (strcmp(arg, "-emit-ast") == 0 ||
1124 strcmp(arg, "-c") == 0 ||
1125 strcmp(arg, "-fsyntax-only") == 0) {
1126 continue;
1127 }
1128
1129 // Keep the argument.
1130 argv.push_back(arg);
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001131 }
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001132
Douglas Gregord93256e2010-01-28 06:00:51 +00001133 // Generate a temporary name for the diagnostics file.
Benjamin Kramerc2a98162010-03-13 21:22:49 +00001134 char tmpFileResults[L_tmpnam];
1135 char *tmpResultsFileName = tmpnam(tmpFileResults);
1136 llvm::sys::Path DiagnosticsFile(tmpResultsFileName);
Douglas Gregord93256e2010-01-28 06:00:51 +00001137 TemporaryFiles.push_back(DiagnosticsFile);
1138 argv.push_back("-fdiagnostics-binary");
1139
Douglas Gregor94dc8f62010-03-19 16:15:56 +00001140 argv.push_back("-Xclang");
1141 argv.push_back("-detailed-preprocessing-record");
1142
Ted Kremenek139ba862009-10-22 00:03:57 +00001143 // Add the null terminator.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001144 argv.push_back(NULL);
1145
Ted Kremenekfeb15e32009-10-26 22:14:08 +00001146 // Invoke 'clang'.
1147 llvm::sys::Path DevNull; // leave empty, causes redirection to /dev/null
1148 // on Unix or NUL (Windows).
Ted Kremenek379afec2009-10-22 03:24:01 +00001149 std::string ErrMsg;
Douglas Gregord93256e2010-01-28 06:00:51 +00001150 const llvm::sys::Path *Redirects[] = { &DevNull, &DevNull, &DiagnosticsFile,
1151 NULL };
Ted Kremenek379afec2009-10-22 03:24:01 +00001152 llvm::sys::Program::ExecuteAndWait(ClangPath, &argv[0], /* env */ NULL,
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001153 /* redirects */ &Redirects[0],
Ted Kremenek379afec2009-10-22 03:24:01 +00001154 /* secondsToWait */ 0, /* memoryLimits */ 0, &ErrMsg);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001155
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001156 if (!ErrMsg.empty()) {
1157 std::string AllArgs;
Ted Kremenek379afec2009-10-22 03:24:01 +00001158 for (std::vector<const char*>::iterator I = argv.begin(), E = argv.end();
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001159 I != E; ++I) {
1160 AllArgs += ' ';
Ted Kremenek779e5f42009-10-26 22:08:39 +00001161 if (*I)
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001162 AllArgs += *I;
Ted Kremenek779e5f42009-10-26 22:08:39 +00001163 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001164
Daniel Dunbar32141c82010-02-23 20:23:45 +00001165 Diags->Report(diag::err_fe_invoking) << AllArgs << ErrMsg;
Ted Kremenek379afec2009-10-22 03:24:01 +00001166 }
Benjamin Kramer0829a832009-10-18 11:19:36 +00001167
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001168 ASTUnit *ATU = ASTUnit::LoadFromPCHFile(astTmpFile, Diags,
Douglas Gregor4db64a42010-01-23 00:14:00 +00001169 CXXIdx->getOnlyLocalDecls(),
Douglas Gregor4db64a42010-01-23 00:14:00 +00001170 RemappedFiles.data(),
Douglas Gregora88084b2010-02-18 18:08:43 +00001171 RemappedFiles.size(),
1172 /*CaptureDiagnostics=*/true);
Douglas Gregora88084b2010-02-18 18:08:43 +00001173 if (ATU) {
1174 LoadSerializedDiagnostics(DiagnosticsFile,
1175 num_unsaved_files, unsaved_files,
1176 ATU->getFileManager(),
1177 ATU->getSourceManager(),
Douglas Gregor405634b2010-04-05 18:10:21 +00001178 ATU->getStoredDiagnostics());
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001179 } else if (CXXIdx->getDisplayDiagnostics()) {
1180 // We failed to load the ASTUnit, but we can still deserialize the
1181 // diagnostics and emit them.
1182 FileManager FileMgr;
Douglas Gregorf715ca12010-03-16 00:06:06 +00001183 Diagnostic Diag;
1184 SourceManager SourceMgr(Diag);
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001185 // FIXME: Faked LangOpts!
1186 LangOptions LangOpts;
1187 llvm::SmallVector<StoredDiagnostic, 4> Diags;
1188 LoadSerializedDiagnostics(DiagnosticsFile,
1189 num_unsaved_files, unsaved_files,
1190 FileMgr, SourceMgr, Diags);
1191 for (llvm::SmallVector<StoredDiagnostic, 4>::iterator D = Diags.begin(),
1192 DEnd = Diags.end();
1193 D != DEnd; ++D) {
1194 CXStoredDiagnostic Diag(*D, LangOpts);
Douglas Gregor274f1902010-02-22 23:17:23 +00001195 CXString Msg = clang_formatDiagnostic(&Diag,
1196 clang_defaultDiagnosticDisplayOptions());
1197 fprintf(stderr, "%s\n", clang_getCString(Msg));
1198 clang_disposeString(Msg);
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001199 }
Douglas Gregor274f1902010-02-22 23:17:23 +00001200
1201#ifdef LLVM_ON_WIN32
1202 // On Windows, force a flush, since there may be multiple copies of
1203 // stderr and stdout in the file system, all with different buffers
1204 // but writing to the same device.
1205 fflush(stderr);
1206#endif
Douglas Gregora88084b2010-02-18 18:08:43 +00001207 }
Douglas Gregord93256e2010-01-28 06:00:51 +00001208
Douglas Gregor313e26c2010-02-18 23:35:40 +00001209 if (ATU) {
1210 // Make the translation unit responsible for destroying all temporary files.
1211 for (unsigned i = 0, e = TemporaryFiles.size(); i != e; ++i)
1212 ATU->addTemporaryFile(TemporaryFiles[i]);
1213 ATU->addTemporaryFile(llvm::sys::Path(ATU->getPCHFileName()));
1214 } else {
1215 // Destroy all of the temporary files now; they can't be referenced any
1216 // longer.
1217 llvm::sys::Path(astTmpFile).eraseFromDisk();
1218 for (unsigned i = 0, e = TemporaryFiles.size(); i != e; ++i)
1219 TemporaryFiles[i].eraseFromDisk();
1220 }
1221
Steve Naroffe19944c2009-10-15 22:23:48 +00001222 return ATU;
Steve Naroff5b7d8e22009-10-15 20:04:39 +00001223}
1224
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001225void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001226 if (CTUnit)
1227 delete static_cast<ASTUnit *>(CTUnit);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00001228}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001229
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001230CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001231 if (!CTUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001232 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001233
Steve Naroff77accc12009-09-03 18:19:54 +00001234 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001235 return createCXString(CXXUnit->getOriginalSourceFileName(), true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +00001236}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +00001237
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001238CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001239 CXCursor Result = { CXCursor_TranslationUnit, { 0, 0, TU } };
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001240 return Result;
1241}
1242
Ted Kremenekfb480492010-01-13 21:46:36 +00001243} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +00001244
Ted Kremenekfb480492010-01-13 21:46:36 +00001245//===----------------------------------------------------------------------===//
Douglas Gregor1db19de2010-01-19 21:36:55 +00001246// CXSourceLocation and CXSourceRange Operations.
1247//===----------------------------------------------------------------------===//
1248
Douglas Gregorb9790342010-01-22 21:44:22 +00001249extern "C" {
1250CXSourceLocation clang_getNullLocation() {
Douglas Gregor5352ac02010-01-28 00:27:43 +00001251 CXSourceLocation Result = { { 0, 0 }, 0 };
Douglas Gregorb9790342010-01-22 21:44:22 +00001252 return Result;
1253}
1254
1255unsigned clang_equalLocations(CXSourceLocation loc1, CXSourceLocation loc2) {
Daniel Dunbar90a6b9e2010-01-30 23:58:27 +00001256 return (loc1.ptr_data[0] == loc2.ptr_data[0] &&
1257 loc1.ptr_data[1] == loc2.ptr_data[1] &&
1258 loc1.int_data == loc2.int_data);
Douglas Gregorb9790342010-01-22 21:44:22 +00001259}
1260
1261CXSourceLocation clang_getLocation(CXTranslationUnit tu,
1262 CXFile file,
1263 unsigned line,
1264 unsigned column) {
1265 if (!tu)
1266 return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001267
Douglas Gregorb9790342010-01-22 21:44:22 +00001268 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
1269 SourceLocation SLoc
1270 = CXXUnit->getSourceManager().getLocation(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001271 static_cast<const FileEntry *>(file),
Douglas Gregorb9790342010-01-22 21:44:22 +00001272 line, column);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001273
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00001274 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
Douglas Gregorb9790342010-01-22 21:44:22 +00001275}
1276
Douglas Gregor5352ac02010-01-28 00:27:43 +00001277CXSourceRange clang_getNullRange() {
1278 CXSourceRange Result = { { 0, 0 }, 0, 0 };
1279 return Result;
1280}
Daniel Dunbard52864b2010-02-14 10:02:57 +00001281
Douglas Gregor5352ac02010-01-28 00:27:43 +00001282CXSourceRange clang_getRange(CXSourceLocation begin, CXSourceLocation end) {
1283 if (begin.ptr_data[0] != end.ptr_data[0] ||
1284 begin.ptr_data[1] != end.ptr_data[1])
1285 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001286
1287 CXSourceRange Result = { { begin.ptr_data[0], begin.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00001288 begin.int_data, end.int_data };
Douglas Gregorb9790342010-01-22 21:44:22 +00001289 return Result;
1290}
1291
Douglas Gregor46766dc2010-01-26 19:19:08 +00001292void clang_getInstantiationLocation(CXSourceLocation location,
1293 CXFile *file,
1294 unsigned *line,
1295 unsigned *column,
1296 unsigned *offset) {
Douglas Gregor1db19de2010-01-19 21:36:55 +00001297 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
1298
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00001299 if (!location.ptr_data[0] || Loc.isInvalid()) {
Douglas Gregor46766dc2010-01-26 19:19:08 +00001300 if (file)
1301 *file = 0;
1302 if (line)
1303 *line = 0;
1304 if (column)
1305 *column = 0;
1306 if (offset)
1307 *offset = 0;
1308 return;
1309 }
1310
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00001311 const SourceManager &SM =
1312 *static_cast<const SourceManager*>(location.ptr_data[0]);
Douglas Gregor1db19de2010-01-19 21:36:55 +00001313 SourceLocation InstLoc = SM.getInstantiationLoc(Loc);
Douglas Gregor1db19de2010-01-19 21:36:55 +00001314
1315 if (file)
1316 *file = (void *)SM.getFileEntryForID(SM.getFileID(InstLoc));
1317 if (line)
1318 *line = SM.getInstantiationLineNumber(InstLoc);
1319 if (column)
1320 *column = SM.getInstantiationColumnNumber(InstLoc);
Douglas Gregore69517c2010-01-26 03:07:15 +00001321 if (offset)
Douglas Gregor46766dc2010-01-26 19:19:08 +00001322 *offset = SM.getDecomposedLoc(InstLoc).second;
Douglas Gregore69517c2010-01-26 03:07:15 +00001323}
1324
Douglas Gregor1db19de2010-01-19 21:36:55 +00001325CXSourceLocation clang_getRangeStart(CXSourceRange range) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001326 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00001327 range.begin_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00001328 return Result;
1329}
1330
1331CXSourceLocation clang_getRangeEnd(CXSourceRange range) {
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00001332 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00001333 range.end_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00001334 return Result;
1335}
1336
Douglas Gregorb9790342010-01-22 21:44:22 +00001337} // end: extern "C"
1338
Douglas Gregor1db19de2010-01-19 21:36:55 +00001339//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00001340// CXFile Operations.
1341//===----------------------------------------------------------------------===//
1342
1343extern "C" {
Ted Kremenek74844072010-02-17 00:41:20 +00001344CXString clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00001345 if (!SFile)
Ted Kremenek74844072010-02-17 00:41:20 +00001346 return createCXString(NULL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001347
Steve Naroff88145032009-10-27 14:35:18 +00001348 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Ted Kremenek74844072010-02-17 00:41:20 +00001349 return createCXString(FEnt->getName());
Steve Naroff88145032009-10-27 14:35:18 +00001350}
1351
1352time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00001353 if (!SFile)
1354 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001355
Steve Naroff88145032009-10-27 14:35:18 +00001356 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
1357 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +00001358}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001359
Douglas Gregorb9790342010-01-22 21:44:22 +00001360CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
1361 if (!tu)
1362 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001363
Douglas Gregorb9790342010-01-22 21:44:22 +00001364 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001365
Douglas Gregorb9790342010-01-22 21:44:22 +00001366 FileManager &FMgr = CXXUnit->getFileManager();
1367 const FileEntry *File = FMgr.getFile(file_name, file_name+strlen(file_name));
1368 return const_cast<FileEntry *>(File);
1369}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001370
Ted Kremenekfb480492010-01-13 21:46:36 +00001371} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +00001372
Ted Kremenekfb480492010-01-13 21:46:36 +00001373//===----------------------------------------------------------------------===//
1374// CXCursor Operations.
1375//===----------------------------------------------------------------------===//
1376
Ted Kremenekfb480492010-01-13 21:46:36 +00001377static Decl *getDeclFromExpr(Stmt *E) {
1378 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
1379 return RefExpr->getDecl();
1380 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
1381 return ME->getMemberDecl();
1382 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
1383 return RE->getDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001384
Ted Kremenekfb480492010-01-13 21:46:36 +00001385 if (CallExpr *CE = dyn_cast<CallExpr>(E))
1386 return getDeclFromExpr(CE->getCallee());
1387 if (CastExpr *CE = dyn_cast<CastExpr>(E))
1388 return getDeclFromExpr(CE->getSubExpr());
1389 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
1390 return OME->getMethodDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001391
Ted Kremenekfb480492010-01-13 21:46:36 +00001392 return 0;
1393}
1394
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00001395static SourceLocation getLocationFromExpr(Expr *E) {
1396 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
1397 return /*FIXME:*/Msg->getLeftLoc();
1398 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
1399 return DRE->getLocation();
1400 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
1401 return Member->getMemberLoc();
1402 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
1403 return Ivar->getLocation();
1404 return E->getLocStart();
1405}
1406
Ted Kremenekfb480492010-01-13 21:46:36 +00001407extern "C" {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001408
1409unsigned clang_visitChildren(CXCursor parent,
Douglas Gregorb1373d02010-01-20 20:59:29 +00001410 CXCursorVisitor visitor,
1411 CXClientData client_data) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001412 ASTUnit *CXXUnit = getCursorASTUnit(parent);
Douglas Gregorb1373d02010-01-20 20:59:29 +00001413
1414 unsigned PCHLevel = Decl::MaxPCHLevel;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001415
Douglas Gregorb1373d02010-01-20 20:59:29 +00001416 // Set the PCHLevel to filter out unwanted decls if requested.
1417 if (CXXUnit->getOnlyLocalDecls()) {
1418 PCHLevel = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001419
Douglas Gregorb1373d02010-01-20 20:59:29 +00001420 // If the main input was an AST, bump the level.
1421 if (CXXUnit->isMainFileAST())
1422 ++PCHLevel;
1423 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001424
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001425 CursorVisitor CursorVis(CXXUnit, visitor, client_data, PCHLevel);
Douglas Gregorb1373d02010-01-20 20:59:29 +00001426 return CursorVis.VisitChildren(parent);
1427}
1428
Douglas Gregor78205d42010-01-20 21:45:58 +00001429static CXString getDeclSpelling(Decl *D) {
1430 NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
1431 if (!ND)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001432 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001433
Douglas Gregor78205d42010-01-20 21:45:58 +00001434 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001435 return createCXString(OMD->getSelector().getAsString());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001436
Douglas Gregor78205d42010-01-20 21:45:58 +00001437 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
1438 // No, this isn't the same as the code below. getIdentifier() is non-virtual
1439 // and returns different names. NamedDecl returns the class name and
1440 // ObjCCategoryImplDecl returns the category name.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001441 return createCXString(CIMP->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001442
Douglas Gregor78205d42010-01-20 21:45:58 +00001443 if (ND->getIdentifier())
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001444 return createCXString(ND->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001445
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001446 return createCXString("");
Douglas Gregor78205d42010-01-20 21:45:58 +00001447}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001448
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001449CXString clang_getCursorSpelling(CXCursor C) {
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001450 if (clang_isTranslationUnit(C.kind))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001451 return clang_getTranslationUnitSpelling(C.data[2]);
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001452
Steve Narofff334b4e2009-09-02 18:26:48 +00001453 if (clang_isReference(C.kind)) {
1454 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00001455 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +00001456 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001457 return createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00001458 }
1459 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +00001460 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001461 return createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00001462 }
1463 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +00001464 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +00001465 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001466 return createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00001467 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001468 case CXCursor_TypeRef: {
1469 TypeDecl *Type = getCursorTypeRef(C).first;
1470 assert(Type && "Missing type decl");
1471
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001472 return createCXString(getCursorContext(C).getTypeDeclType(Type).
1473 getAsString());
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001474 }
1475
Daniel Dunbaracca7252009-11-30 20:42:49 +00001476 default:
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001477 return createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +00001478 }
1479 }
Douglas Gregor97b98722010-01-19 23:20:36 +00001480
1481 if (clang_isExpression(C.kind)) {
1482 Decl *D = getDeclFromExpr(getCursorExpr(C));
1483 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +00001484 return getDeclSpelling(D);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001485 return createCXString("");
Douglas Gregor97b98722010-01-19 23:20:36 +00001486 }
1487
Douglas Gregor4ae8f292010-03-18 17:52:52 +00001488 if (C.kind == CXCursor_MacroInstantiation)
1489 return createCXString(getCursorMacroInstantiation(C)->getName()
1490 ->getNameStart());
1491
Douglas Gregor572feb22010-03-18 18:04:21 +00001492 if (C.kind == CXCursor_MacroDefinition)
1493 return createCXString(getCursorMacroDefinition(C)->getName()
1494 ->getNameStart());
1495
Douglas Gregor60cbfac2010-01-25 16:56:17 +00001496 if (clang_isDeclaration(C.kind))
1497 return getDeclSpelling(getCursorDecl(C));
Ted Kremeneke68fff62010-02-17 00:41:32 +00001498
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001499 return createCXString("");
Steve Narofff334b4e2009-09-02 18:26:48 +00001500}
1501
Ted Kremeneke68fff62010-02-17 00:41:32 +00001502CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00001503 switch (Kind) {
Ted Kremeneke68fff62010-02-17 00:41:32 +00001504 case CXCursor_FunctionDecl:
1505 return createCXString("FunctionDecl");
1506 case CXCursor_TypedefDecl:
1507 return createCXString("TypedefDecl");
1508 case CXCursor_EnumDecl:
1509 return createCXString("EnumDecl");
1510 case CXCursor_EnumConstantDecl:
1511 return createCXString("EnumConstantDecl");
1512 case CXCursor_StructDecl:
1513 return createCXString("StructDecl");
1514 case CXCursor_UnionDecl:
1515 return createCXString("UnionDecl");
1516 case CXCursor_ClassDecl:
1517 return createCXString("ClassDecl");
1518 case CXCursor_FieldDecl:
1519 return createCXString("FieldDecl");
1520 case CXCursor_VarDecl:
1521 return createCXString("VarDecl");
1522 case CXCursor_ParmDecl:
1523 return createCXString("ParmDecl");
1524 case CXCursor_ObjCInterfaceDecl:
1525 return createCXString("ObjCInterfaceDecl");
1526 case CXCursor_ObjCCategoryDecl:
1527 return createCXString("ObjCCategoryDecl");
1528 case CXCursor_ObjCProtocolDecl:
1529 return createCXString("ObjCProtocolDecl");
1530 case CXCursor_ObjCPropertyDecl:
1531 return createCXString("ObjCPropertyDecl");
1532 case CXCursor_ObjCIvarDecl:
1533 return createCXString("ObjCIvarDecl");
1534 case CXCursor_ObjCInstanceMethodDecl:
1535 return createCXString("ObjCInstanceMethodDecl");
1536 case CXCursor_ObjCClassMethodDecl:
1537 return createCXString("ObjCClassMethodDecl");
1538 case CXCursor_ObjCImplementationDecl:
1539 return createCXString("ObjCImplementationDecl");
1540 case CXCursor_ObjCCategoryImplDecl:
1541 return createCXString("ObjCCategoryImplDecl");
1542 case CXCursor_UnexposedDecl:
1543 return createCXString("UnexposedDecl");
1544 case CXCursor_ObjCSuperClassRef:
1545 return createCXString("ObjCSuperClassRef");
1546 case CXCursor_ObjCProtocolRef:
1547 return createCXString("ObjCProtocolRef");
1548 case CXCursor_ObjCClassRef:
1549 return createCXString("ObjCClassRef");
1550 case CXCursor_TypeRef:
1551 return createCXString("TypeRef");
1552 case CXCursor_UnexposedExpr:
1553 return createCXString("UnexposedExpr");
1554 case CXCursor_DeclRefExpr:
1555 return createCXString("DeclRefExpr");
1556 case CXCursor_MemberRefExpr:
1557 return createCXString("MemberRefExpr");
1558 case CXCursor_CallExpr:
1559 return createCXString("CallExpr");
1560 case CXCursor_ObjCMessageExpr:
1561 return createCXString("ObjCMessageExpr");
1562 case CXCursor_UnexposedStmt:
1563 return createCXString("UnexposedStmt");
1564 case CXCursor_InvalidFile:
1565 return createCXString("InvalidFile");
Ted Kremenek292db642010-03-19 20:39:05 +00001566 case CXCursor_InvalidCode:
1567 return createCXString("InvalidCode");
Ted Kremeneke68fff62010-02-17 00:41:32 +00001568 case CXCursor_NoDeclFound:
1569 return createCXString("NoDeclFound");
1570 case CXCursor_NotImplemented:
1571 return createCXString("NotImplemented");
1572 case CXCursor_TranslationUnit:
1573 return createCXString("TranslationUnit");
Ted Kremeneke77f4432010-02-18 03:09:07 +00001574 case CXCursor_UnexposedAttr:
1575 return createCXString("UnexposedAttr");
1576 case CXCursor_IBActionAttr:
1577 return createCXString("attribute(ibaction)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00001578 case CXCursor_IBOutletAttr:
1579 return createCXString("attribute(iboutlet)");
1580 case CXCursor_PreprocessingDirective:
1581 return createCXString("preprocessing directive");
Douglas Gregor572feb22010-03-18 18:04:21 +00001582 case CXCursor_MacroDefinition:
1583 return createCXString("macro definition");
Douglas Gregor48072312010-03-18 15:23:44 +00001584 case CXCursor_MacroInstantiation:
1585 return createCXString("macro instantiation");
Steve Naroff89922f82009-08-31 00:59:03 +00001586 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00001587
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00001588 llvm_unreachable("Unhandled CXCursorKind");
Ted Kremeneke68fff62010-02-17 00:41:32 +00001589 return createCXString(NULL);
Steve Naroff600866c2009-08-27 19:51:58 +00001590}
Steve Naroff89922f82009-08-31 00:59:03 +00001591
Ted Kremeneke68fff62010-02-17 00:41:32 +00001592enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
1593 CXCursor parent,
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001594 CXClientData client_data) {
1595 CXCursor *BestCursor = static_cast<CXCursor *>(client_data);
1596 *BestCursor = cursor;
1597 return CXChildVisit_Recurse;
1598}
Ted Kremeneke68fff62010-02-17 00:41:32 +00001599
Douglas Gregorb9790342010-01-22 21:44:22 +00001600CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
1601 if (!TU)
Ted Kremenekf4629892010-01-14 01:51:23 +00001602 return clang_getNullCursor();
Ted Kremeneke68fff62010-02-17 00:41:32 +00001603
Douglas Gregorb9790342010-01-22 21:44:22 +00001604 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
1605
Douglas Gregorbdf60622010-03-05 21:16:25 +00001606 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
1607
Ted Kremeneka297de22010-01-25 22:34:44 +00001608 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001609 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
1610 if (SLoc.isValid()) {
Daniel Dunbard52864b2010-02-14 10:02:57 +00001611 SourceRange RegionOfInterest(SLoc, SLoc.getFileLocWithOffset(1));
Ted Kremeneke68fff62010-02-17 00:41:32 +00001612
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001613 // FIXME: Would be great to have a "hint" cursor, then walk from that
1614 // hint cursor upward until we find a cursor whose source range encloses
1615 // the region of interest, rather than starting from the translation unit.
1616 CXCursor Parent = clang_getTranslationUnitCursor(CXXUnit);
Ted Kremeneke68fff62010-02-17 00:41:32 +00001617 CursorVisitor CursorVis(CXXUnit, GetCursorVisitor, &Result,
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001618 Decl::MaxPCHLevel, RegionOfInterest);
1619 CursorVis.VisitChildren(Parent);
Steve Naroff77128dd2009-09-15 20:25:34 +00001620 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00001621 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00001622}
1623
Ted Kremenek73885552009-11-17 19:28:59 +00001624CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00001625 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00001626}
1627
1628unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00001629 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00001630}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001631
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001632unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00001633 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
1634}
1635
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001636unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +00001637 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
1638}
Steve Naroff2d4d6292009-08-31 14:26:51 +00001639
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001640unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00001641 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
1642}
1643
Douglas Gregor97b98722010-01-19 23:20:36 +00001644unsigned clang_isExpression(enum CXCursorKind K) {
1645 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
1646}
1647
1648unsigned clang_isStatement(enum CXCursorKind K) {
1649 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
1650}
1651
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001652unsigned clang_isTranslationUnit(enum CXCursorKind K) {
1653 return K == CXCursor_TranslationUnit;
1654}
1655
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00001656unsigned clang_isPreprocessing(enum CXCursorKind K) {
1657 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
1658}
1659
Ted Kremenekad6eff62010-03-08 21:17:29 +00001660unsigned clang_isUnexposed(enum CXCursorKind K) {
1661 switch (K) {
1662 case CXCursor_UnexposedDecl:
1663 case CXCursor_UnexposedExpr:
1664 case CXCursor_UnexposedStmt:
1665 case CXCursor_UnexposedAttr:
1666 return true;
1667 default:
1668 return false;
1669 }
1670}
1671
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001672CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00001673 return C.kind;
1674}
1675
Douglas Gregor98258af2010-01-18 22:46:11 +00001676CXSourceLocation clang_getCursorLocation(CXCursor C) {
1677 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00001678 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001679 case CXCursor_ObjCSuperClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00001680 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1681 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001682 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001683 }
1684
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001685 case CXCursor_ObjCProtocolRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00001686 std::pair<ObjCProtocolDecl *, SourceLocation> P
1687 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001688 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001689 }
1690
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001691 case CXCursor_ObjCClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00001692 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1693 = getCursorObjCClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001694 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001695 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001696
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001697 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001698 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001699 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001700 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001701
Douglas Gregorf46034a2010-01-18 23:41:10 +00001702 default:
1703 // FIXME: Need a way to enumerate all non-reference cases.
1704 llvm_unreachable("Missed a reference kind");
1705 }
Douglas Gregor98258af2010-01-18 22:46:11 +00001706 }
Douglas Gregor97b98722010-01-19 23:20:36 +00001707
1708 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001709 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00001710 getLocationFromExpr(getCursorExpr(C)));
1711
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00001712 if (C.kind == CXCursor_PreprocessingDirective) {
1713 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
1714 return cxloc::translateSourceLocation(getCursorContext(C), L);
1715 }
Douglas Gregor48072312010-03-18 15:23:44 +00001716
1717 if (C.kind == CXCursor_MacroInstantiation) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00001718 SourceLocation L
1719 = cxcursor::getCursorMacroInstantiation(C)->getSourceRange().getBegin();
Douglas Gregor48072312010-03-18 15:23:44 +00001720 return cxloc::translateSourceLocation(getCursorContext(C), L);
1721 }
Douglas Gregor572feb22010-03-18 18:04:21 +00001722
1723 if (C.kind == CXCursor_MacroDefinition) {
1724 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
1725 return cxloc::translateSourceLocation(getCursorContext(C), L);
1726 }
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00001727
Douglas Gregor5352ac02010-01-28 00:27:43 +00001728 if (!getCursorDecl(C))
1729 return clang_getNullLocation();
Douglas Gregor98258af2010-01-18 22:46:11 +00001730
Douglas Gregorf46034a2010-01-18 23:41:10 +00001731 Decl *D = getCursorDecl(C);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001732 SourceLocation Loc = D->getLocation();
1733 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
1734 Loc = Class->getClassLoc();
Douglas Gregor2ca54fe2010-03-22 15:53:50 +00001735 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00001736}
Douglas Gregora7bde202010-01-19 00:34:46 +00001737
1738CXSourceRange clang_getCursorExtent(CXCursor C) {
1739 if (clang_isReference(C.kind)) {
1740 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001741 case CXCursor_ObjCSuperClassRef: {
Douglas Gregora7bde202010-01-19 00:34:46 +00001742 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1743 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001744 return cxloc::translateSourceRange(P.first->getASTContext(), P.second);
Douglas Gregora7bde202010-01-19 00:34:46 +00001745 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001746
1747 case CXCursor_ObjCProtocolRef: {
Douglas Gregora7bde202010-01-19 00:34:46 +00001748 std::pair<ObjCProtocolDecl *, SourceLocation> P
1749 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001750 return cxloc::translateSourceRange(P.first->getASTContext(), P.second);
Douglas Gregora7bde202010-01-19 00:34:46 +00001751 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001752
1753 case CXCursor_ObjCClassRef: {
Douglas Gregora7bde202010-01-19 00:34:46 +00001754 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1755 = getCursorObjCClassRef(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001756
Ted Kremeneka297de22010-01-25 22:34:44 +00001757 return cxloc::translateSourceRange(P.first->getASTContext(), P.second);
Douglas Gregora7bde202010-01-19 00:34:46 +00001758 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001759
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001760 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001761 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001762 return cxloc::translateSourceRange(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001763 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001764
Douglas Gregora7bde202010-01-19 00:34:46 +00001765 default:
1766 // FIXME: Need a way to enumerate all non-reference cases.
1767 llvm_unreachable("Missed a reference kind");
1768 }
1769 }
Douglas Gregor97b98722010-01-19 23:20:36 +00001770
1771 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001772 return cxloc::translateSourceRange(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00001773 getCursorExpr(C)->getSourceRange());
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001774
1775 if (clang_isStatement(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001776 return cxloc::translateSourceRange(getCursorContext(C),
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001777 getCursorStmt(C)->getSourceRange());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001778
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00001779 if (C.kind == CXCursor_PreprocessingDirective) {
1780 SourceRange R = cxcursor::getCursorPreprocessingDirective(C);
1781 return cxloc::translateSourceRange(getCursorContext(C), R);
1782 }
Douglas Gregor48072312010-03-18 15:23:44 +00001783
1784 if (C.kind == CXCursor_MacroInstantiation) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00001785 SourceRange R = cxcursor::getCursorMacroInstantiation(C)->getSourceRange();
Douglas Gregor48072312010-03-18 15:23:44 +00001786 return cxloc::translateSourceRange(getCursorContext(C), R);
1787 }
Douglas Gregor572feb22010-03-18 18:04:21 +00001788
1789 if (C.kind == CXCursor_MacroDefinition) {
1790 SourceRange R = cxcursor::getCursorMacroDefinition(C)->getSourceRange();
1791 return cxloc::translateSourceRange(getCursorContext(C), R);
1792 }
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00001793
Douglas Gregor5352ac02010-01-28 00:27:43 +00001794 if (!getCursorDecl(C))
1795 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001796
Douglas Gregora7bde202010-01-19 00:34:46 +00001797 Decl *D = getCursorDecl(C);
Douglas Gregor2ca54fe2010-03-22 15:53:50 +00001798 return cxloc::translateSourceRange(getCursorContext(C), D->getSourceRange());
Douglas Gregora7bde202010-01-19 00:34:46 +00001799}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001800
1801CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001802 if (clang_isInvalid(C.kind))
1803 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001804
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001805 ASTUnit *CXXUnit = getCursorASTUnit(C);
Douglas Gregorb6998662010-01-19 19:34:47 +00001806 if (clang_isDeclaration(C.kind))
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001807 return C;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001808
Douglas Gregor97b98722010-01-19 23:20:36 +00001809 if (clang_isExpression(C.kind)) {
1810 Decl *D = getDeclFromExpr(getCursorExpr(C));
1811 if (D)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001812 return MakeCXCursor(D, CXXUnit);
Douglas Gregor97b98722010-01-19 23:20:36 +00001813 return clang_getNullCursor();
1814 }
1815
Douglas Gregorbf7efa22010-03-18 18:23:03 +00001816 if (C.kind == CXCursor_MacroInstantiation) {
1817 if (MacroDefinition *Def = getCursorMacroInstantiation(C)->getDefinition())
1818 return MakeMacroDefinitionCursor(Def, CXXUnit);
1819 }
1820
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001821 if (!clang_isReference(C.kind))
1822 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001823
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001824 switch (C.kind) {
1825 case CXCursor_ObjCSuperClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001826 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001827
1828 case CXCursor_ObjCProtocolRef: {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001829 return MakeCXCursor(getCursorObjCProtocolRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001830
1831 case CXCursor_ObjCClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001832 return MakeCXCursor(getCursorObjCClassRef(C).first, CXXUnit);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001833
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001834 case CXCursor_TypeRef:
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001835 return MakeCXCursor(getCursorTypeRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001836
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001837 default:
1838 // We would prefer to enumerate all non-reference cursor kinds here.
1839 llvm_unreachable("Unhandled reference cursor kind");
1840 break;
1841 }
1842 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001843
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001844 return clang_getNullCursor();
1845}
1846
Douglas Gregorb6998662010-01-19 19:34:47 +00001847CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001848 if (clang_isInvalid(C.kind))
1849 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001850
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001851 ASTUnit *CXXUnit = getCursorASTUnit(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001852
Douglas Gregorb6998662010-01-19 19:34:47 +00001853 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00001854 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00001855 C = clang_getCursorReferenced(C);
1856 WasReference = true;
1857 }
1858
Douglas Gregorbf7efa22010-03-18 18:23:03 +00001859 if (C.kind == CXCursor_MacroInstantiation)
1860 return clang_getCursorReferenced(C);
1861
Douglas Gregorb6998662010-01-19 19:34:47 +00001862 if (!clang_isDeclaration(C.kind))
1863 return clang_getNullCursor();
1864
1865 Decl *D = getCursorDecl(C);
1866 if (!D)
1867 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001868
Douglas Gregorb6998662010-01-19 19:34:47 +00001869 switch (D->getKind()) {
1870 // Declaration kinds that don't really separate the notions of
1871 // declaration and definition.
1872 case Decl::Namespace:
1873 case Decl::Typedef:
1874 case Decl::TemplateTypeParm:
1875 case Decl::EnumConstant:
1876 case Decl::Field:
1877 case Decl::ObjCIvar:
1878 case Decl::ObjCAtDefsField:
1879 case Decl::ImplicitParam:
1880 case Decl::ParmVar:
1881 case Decl::NonTypeTemplateParm:
1882 case Decl::TemplateTemplateParm:
1883 case Decl::ObjCCategoryImpl:
1884 case Decl::ObjCImplementation:
1885 case Decl::LinkageSpec:
1886 case Decl::ObjCPropertyImpl:
1887 case Decl::FileScopeAsm:
1888 case Decl::StaticAssert:
1889 case Decl::Block:
1890 return C;
1891
1892 // Declaration kinds that don't make any sense here, but are
1893 // nonetheless harmless.
1894 case Decl::TranslationUnit:
1895 case Decl::Template:
1896 case Decl::ObjCContainer:
1897 break;
1898
1899 // Declaration kinds for which the definition is not resolvable.
1900 case Decl::UnresolvedUsingTypename:
1901 case Decl::UnresolvedUsingValue:
1902 break;
1903
1904 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001905 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
1906 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001907
1908 case Decl::NamespaceAlias:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001909 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001910
1911 case Decl::Enum:
1912 case Decl::Record:
1913 case Decl::CXXRecord:
1914 case Decl::ClassTemplateSpecialization:
1915 case Decl::ClassTemplatePartialSpecialization:
Douglas Gregor952b0172010-02-11 01:04:33 +00001916 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001917 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001918 return clang_getNullCursor();
1919
1920 case Decl::Function:
1921 case Decl::CXXMethod:
1922 case Decl::CXXConstructor:
1923 case Decl::CXXDestructor:
1924 case Decl::CXXConversion: {
1925 const FunctionDecl *Def = 0;
1926 if (cast<FunctionDecl>(D)->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001927 return MakeCXCursor(const_cast<FunctionDecl *>(Def), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001928 return clang_getNullCursor();
1929 }
1930
1931 case Decl::Var: {
Sebastian Redl31310a22010-02-01 20:16:42 +00001932 // Ask the variable if it has a definition.
1933 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
1934 return MakeCXCursor(Def, CXXUnit);
1935 return clang_getNullCursor();
Douglas Gregorb6998662010-01-19 19:34:47 +00001936 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001937
Douglas Gregorb6998662010-01-19 19:34:47 +00001938 case Decl::FunctionTemplate: {
1939 const FunctionDecl *Def = 0;
1940 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001941 return MakeCXCursor(Def->getDescribedFunctionTemplate(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001942 return clang_getNullCursor();
1943 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001944
Douglas Gregorb6998662010-01-19 19:34:47 +00001945 case Decl::ClassTemplate: {
1946 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
Douglas Gregor952b0172010-02-11 01:04:33 +00001947 ->getDefinition())
Douglas Gregorb6998662010-01-19 19:34:47 +00001948 return MakeCXCursor(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001949 cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001950 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001951 return clang_getNullCursor();
1952 }
1953
1954 case Decl::Using: {
1955 UsingDecl *Using = cast<UsingDecl>(D);
1956 CXCursor Def = clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001957 for (UsingDecl::shadow_iterator S = Using->shadow_begin(),
1958 SEnd = Using->shadow_end();
Douglas Gregorb6998662010-01-19 19:34:47 +00001959 S != SEnd; ++S) {
1960 if (Def != clang_getNullCursor()) {
1961 // FIXME: We have no way to return multiple results.
1962 return clang_getNullCursor();
1963 }
1964
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001965 Def = clang_getCursorDefinition(MakeCXCursor((*S)->getTargetDecl(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001966 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00001967 }
1968
1969 return Def;
1970 }
1971
1972 case Decl::UsingShadow:
1973 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001974 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001975 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00001976
1977 case Decl::ObjCMethod: {
1978 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
1979 if (Method->isThisDeclarationADefinition())
1980 return C;
1981
1982 // Dig out the method definition in the associated
1983 // @implementation, if we have it.
1984 // FIXME: The ASTs should make finding the definition easier.
1985 if (ObjCInterfaceDecl *Class
1986 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
1987 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
1988 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
1989 Method->isInstanceMethod()))
1990 if (Def->isThisDeclarationADefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001991 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001992
1993 return clang_getNullCursor();
1994 }
1995
1996 case Decl::ObjCCategory:
1997 if (ObjCCategoryImplDecl *Impl
1998 = cast<ObjCCategoryDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001999 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002000 return clang_getNullCursor();
2001
2002 case Decl::ObjCProtocol:
2003 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
2004 return C;
2005 return clang_getNullCursor();
2006
2007 case Decl::ObjCInterface:
2008 // There are two notions of a "definition" for an Objective-C
2009 // class: the interface and its implementation. When we resolved a
2010 // reference to an Objective-C class, produce the @interface as
2011 // the definition; when we were provided with the interface,
2012 // produce the @implementation as the definition.
2013 if (WasReference) {
2014 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
2015 return C;
2016 } else if (ObjCImplementationDecl *Impl
2017 = cast<ObjCInterfaceDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002018 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002019 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002020
Douglas Gregorb6998662010-01-19 19:34:47 +00002021 case Decl::ObjCProperty:
2022 // FIXME: We don't really know where to find the
2023 // ObjCPropertyImplDecls that implement this property.
2024 return clang_getNullCursor();
2025
2026 case Decl::ObjCCompatibleAlias:
2027 if (ObjCInterfaceDecl *Class
2028 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
2029 if (!Class->isForwardDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002030 return MakeCXCursor(Class, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002031
Douglas Gregorb6998662010-01-19 19:34:47 +00002032 return clang_getNullCursor();
2033
2034 case Decl::ObjCForwardProtocol: {
2035 ObjCForwardProtocolDecl *Forward = cast<ObjCForwardProtocolDecl>(D);
2036 if (Forward->protocol_size() == 1)
2037 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002038 MakeCXCursor(*Forward->protocol_begin(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002039 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002040
2041 // FIXME: Cannot return multiple definitions.
2042 return clang_getNullCursor();
2043 }
2044
2045 case Decl::ObjCClass: {
2046 ObjCClassDecl *Class = cast<ObjCClassDecl>(D);
2047 if (Class->size() == 1) {
2048 ObjCInterfaceDecl *IFace = Class->begin()->getInterface();
2049 if (!IFace->isForwardDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002050 return MakeCXCursor(IFace, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002051 return clang_getNullCursor();
2052 }
2053
2054 // FIXME: Cannot return multiple definitions.
2055 return clang_getNullCursor();
2056 }
2057
2058 case Decl::Friend:
2059 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002060 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002061 return clang_getNullCursor();
2062
2063 case Decl::FriendTemplate:
2064 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002065 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002066 return clang_getNullCursor();
2067 }
2068
2069 return clang_getNullCursor();
2070}
2071
2072unsigned clang_isCursorDefinition(CXCursor C) {
2073 if (!clang_isDeclaration(C.kind))
2074 return 0;
2075
2076 return clang_getCursorDefinition(C) == C;
2077}
2078
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002079void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00002080 const char **startBuf,
2081 const char **endBuf,
2082 unsigned *startLine,
2083 unsigned *startColumn,
2084 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002085 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00002086 assert(getCursorDecl(C) && "CXCursor has null decl");
2087 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00002088 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
2089 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002090
Steve Naroff4ade6d62009-09-23 17:52:52 +00002091 SourceManager &SM = FD->getASTContext().getSourceManager();
2092 *startBuf = SM.getCharacterData(Body->getLBracLoc());
2093 *endBuf = SM.getCharacterData(Body->getRBracLoc());
2094 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
2095 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
2096 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
2097 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
2098}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002099
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002100void clang_enableStackTraces(void) {
2101 llvm::sys::PrintStackTraceOnErrorSignal();
2102}
2103
Ted Kremenekfb480492010-01-13 21:46:36 +00002104} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00002105
Ted Kremenekfb480492010-01-13 21:46:36 +00002106//===----------------------------------------------------------------------===//
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002107// Token-based Operations.
2108//===----------------------------------------------------------------------===//
2109
2110/* CXToken layout:
2111 * int_data[0]: a CXTokenKind
2112 * int_data[1]: starting token location
2113 * int_data[2]: token length
2114 * int_data[3]: reserved
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002115 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002116 * otherwise unused.
2117 */
2118extern "C" {
2119
2120CXTokenKind clang_getTokenKind(CXToken CXTok) {
2121 return static_cast<CXTokenKind>(CXTok.int_data[0]);
2122}
2123
2124CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
2125 switch (clang_getTokenKind(CXTok)) {
2126 case CXToken_Identifier:
2127 case CXToken_Keyword:
2128 // We know we have an IdentifierInfo*, so use that.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002129 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
2130 ->getNameStart());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002131
2132 case CXToken_Literal: {
2133 // We have stashed the starting pointer in the ptr_data field. Use it.
2134 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002135 return createCXString(llvm::StringRef(Text, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002136 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002137
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002138 case CXToken_Punctuation:
2139 case CXToken_Comment:
2140 break;
2141 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002142
2143 // We have to find the starting buffer pointer the hard way, by
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002144 // deconstructing the source location.
2145 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2146 if (!CXXUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002147 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002148
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002149 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
2150 std::pair<FileID, unsigned> LocInfo
2151 = CXXUnit->getSourceManager().getDecomposedLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +00002152 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002153 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00002154 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
2155 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00002156 return createCXString("");
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002157
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002158 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002159}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002160
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002161CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
2162 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2163 if (!CXXUnit)
2164 return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002165
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002166 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
2167 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
2168}
2169
2170CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
2171 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregor5352ac02010-01-28 00:27:43 +00002172 if (!CXXUnit)
2173 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002174
2175 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002176 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
2177}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002178
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002179void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
2180 CXToken **Tokens, unsigned *NumTokens) {
2181 if (Tokens)
2182 *Tokens = 0;
2183 if (NumTokens)
2184 *NumTokens = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002185
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002186 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2187 if (!CXXUnit || !Tokens || !NumTokens)
2188 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002189
Douglas Gregorbdf60622010-03-05 21:16:25 +00002190 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
2191
Daniel Dunbar85b988f2010-02-14 08:31:57 +00002192 SourceRange R = cxloc::translateCXSourceRange(Range);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002193 if (R.isInvalid())
2194 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002195
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002196 SourceManager &SourceMgr = CXXUnit->getSourceManager();
2197 std::pair<FileID, unsigned> BeginLocInfo
2198 = SourceMgr.getDecomposedLoc(R.getBegin());
2199 std::pair<FileID, unsigned> EndLocInfo
2200 = SourceMgr.getDecomposedLoc(R.getEnd());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002201
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002202 // Cannot tokenize across files.
2203 if (BeginLocInfo.first != EndLocInfo.first)
2204 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002205
2206 // Create a lexer
Douglas Gregorf715ca12010-03-16 00:06:06 +00002207 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002208 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00002209 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
Douglas Gregor47a3fcd2010-03-16 20:26:15 +00002210 if (Invalid)
2211 return;
Douglas Gregoraea67db2010-03-15 22:54:52 +00002212
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002213 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
2214 CXXUnit->getASTContext().getLangOptions(),
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002215 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002216 Lex.SetCommentRetentionState(true);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002217
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002218 // Lex tokens until we hit the end of the range.
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002219 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002220 llvm::SmallVector<CXToken, 32> CXTokens;
2221 Token Tok;
2222 do {
2223 // Lex the next token
2224 Lex.LexFromRawLexer(Tok);
2225 if (Tok.is(tok::eof))
2226 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002227
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002228 // Initialize the CXToken.
2229 CXToken CXTok;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002230
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002231 // - Common fields
2232 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
2233 CXTok.int_data[2] = Tok.getLength();
2234 CXTok.int_data[3] = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002235
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002236 // - Kind-specific fields
2237 if (Tok.isLiteral()) {
2238 CXTok.int_data[0] = CXToken_Literal;
2239 CXTok.ptr_data = (void *)Tok.getLiteralData();
2240 } else if (Tok.is(tok::identifier)) {
Douglas Gregoraea67db2010-03-15 22:54:52 +00002241 // Lookup the identifier to determine whether we have a keyword.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002242 std::pair<FileID, unsigned> LocInfo
2243 = SourceMgr.getDecomposedLoc(Tok.getLocation());
Douglas Gregorf715ca12010-03-16 00:06:06 +00002244 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002245 llvm::StringRef Buf
Douglas Gregorf715ca12010-03-16 00:06:06 +00002246 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
2247 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00002248 return;
2249
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002250 const char *StartPos = Buf.data() + LocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002251 IdentifierInfo *II
2252 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok, StartPos);
2253 CXTok.int_data[0] = II->getTokenID() == tok::identifier?
2254 CXToken_Identifier
2255 : CXToken_Keyword;
2256 CXTok.ptr_data = II;
2257 } else if (Tok.is(tok::comment)) {
2258 CXTok.int_data[0] = CXToken_Comment;
2259 CXTok.ptr_data = 0;
2260 } else {
2261 CXTok.int_data[0] = CXToken_Punctuation;
2262 CXTok.ptr_data = 0;
2263 }
2264 CXTokens.push_back(CXTok);
2265 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002266
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002267 if (CXTokens.empty())
2268 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002269
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002270 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
2271 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
2272 *NumTokens = CXTokens.size();
2273}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002274
2275typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
2276
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002277enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
2278 CXCursor parent,
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002279 CXClientData client_data) {
2280 AnnotateTokensData *Data = static_cast<AnnotateTokensData *>(client_data);
2281
2282 // We only annotate the locations of declarations, simple
2283 // references, and expressions which directly reference something.
2284 CXCursorKind Kind = clang_getCursorKind(cursor);
2285 if (clang_isDeclaration(Kind) || clang_isReference(Kind)) {
2286 // Okay: We can annotate the location of this declaration with the
2287 // declaration or reference
2288 } else if (clang_isExpression(cursor.kind)) {
2289 if (Kind != CXCursor_DeclRefExpr &&
2290 Kind != CXCursor_MemberRefExpr &&
2291 Kind != CXCursor_ObjCMessageExpr)
2292 return CXChildVisit_Recurse;
2293
2294 CXCursor Referenced = clang_getCursorReferenced(cursor);
2295 if (Referenced == cursor || Referenced == clang_getNullCursor())
2296 return CXChildVisit_Recurse;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002297
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002298 // Okay: we can annotate the location of this expression
Douglas Gregor0396f462010-03-19 05:22:59 +00002299 } else if (clang_isPreprocessing(cursor.kind)) {
2300 // We can always annotate a preprocessing directive/macro instantiation.
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002301 } else {
2302 // Nothing to annotate
2303 return CXChildVisit_Recurse;
2304 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002305
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002306 CXSourceLocation Loc = clang_getCursorLocation(cursor);
2307 (*Data)[Loc.int_data] = cursor;
2308 return CXChildVisit_Recurse;
2309}
2310
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002311void clang_annotateTokens(CXTranslationUnit TU,
2312 CXToken *Tokens, unsigned NumTokens,
2313 CXCursor *Cursors) {
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002314 if (NumTokens == 0)
2315 return;
2316
2317 // Any token we don't specifically annotate will have a NULL cursor.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002318 for (unsigned I = 0; I != NumTokens; ++I)
2319 Cursors[I] = clang_getNullCursor();
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002320
2321 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2322 if (!CXXUnit || !Tokens)
2323 return;
2324
Douglas Gregorbdf60622010-03-05 21:16:25 +00002325 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
2326
Douglas Gregor0396f462010-03-19 05:22:59 +00002327 // Determine the region of interest, which contains all of the tokens.
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002328 SourceRange RegionOfInterest;
2329 RegionOfInterest.setBegin(
2330 cxloc::translateSourceLocation(clang_getTokenLocation(TU, Tokens[0])));
2331 SourceLocation End
Douglas Gregor09d9fa12010-04-05 16:10:30 +00002332 = cxloc::translateSourceLocation(clang_getTokenLocation(TU,
Douglas Gregor0396f462010-03-19 05:22:59 +00002333 Tokens[NumTokens - 1]));
Daniel Dunbard52864b2010-02-14 10:02:57 +00002334 RegionOfInterest.setEnd(CXXUnit->getPreprocessor().getLocForEndOfToken(End));
Douglas Gregor2507fa82010-03-19 00:18:31 +00002335
Douglas Gregor0396f462010-03-19 05:22:59 +00002336 // A mapping from the source locations found when re-lexing or traversing the
2337 // region of interest to the corresponding cursors.
2338 AnnotateTokensData Annotated;
2339
2340 // Relex the tokens within the source range to look for preprocessing
2341 // directives.
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002342 SourceManager &SourceMgr = CXXUnit->getSourceManager();
2343 std::pair<FileID, unsigned> BeginLocInfo
2344 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
2345 std::pair<FileID, unsigned> EndLocInfo
2346 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
2347
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002348 llvm::StringRef Buffer;
Douglas Gregor0396f462010-03-19 05:22:59 +00002349 bool Invalid = false;
2350 if (BeginLocInfo.first == EndLocInfo.first &&
2351 ((Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid)),true) &&
2352 !Invalid) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002353 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
2354 CXXUnit->getASTContext().getLangOptions(),
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002355 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
2356 Buffer.end());
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002357 Lex.SetCommentRetentionState(true);
2358
2359 // Lex tokens in raw mode until we hit the end of the range, to avoid
2360 // entering #includes or expanding macros.
Douglas Gregor48072312010-03-18 15:23:44 +00002361 while (true) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002362 Token Tok;
2363 Lex.LexFromRawLexer(Tok);
2364
2365 reprocess:
2366 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
2367 // We have found a preprocessing directive. Gobble it up so that we
2368 // don't see it while preprocessing these tokens later, but keep track of
2369 // all of the token locations inside this preprocessing directive so that
2370 // we can annotate them appropriately.
2371 //
2372 // FIXME: Some simple tests here could identify macro definitions and
2373 // #undefs, to provide specific cursor kinds for those.
2374 std::vector<SourceLocation> Locations;
2375 do {
2376 Locations.push_back(Tok.getLocation());
2377 Lex.LexFromRawLexer(Tok);
2378 } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
2379
2380 using namespace cxcursor;
2381 CXCursor Cursor
2382 = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
2383 Locations.back()),
2384 CXXUnit);
2385 for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
2386 Annotated[Locations[I].getRawEncoding()] = Cursor;
2387 }
2388
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002389 if (Tok.isAtStartOfLine())
2390 goto reprocess;
2391
2392 continue;
2393 }
2394
Douglas Gregor48072312010-03-18 15:23:44 +00002395 if (Tok.is(tok::eof))
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002396 break;
2397 }
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002398 }
Douglas Gregor0396f462010-03-19 05:22:59 +00002399
2400 // Annotate all of the source locations in the region of interest that map to
2401 // a specific cursor.
2402 CXCursor Parent = clang_getTranslationUnitCursor(CXXUnit);
2403 CursorVisitor AnnotateVis(CXXUnit, AnnotateTokensVisitor, &Annotated,
2404 Decl::MaxPCHLevel, RegionOfInterest);
2405 AnnotateVis.VisitChildren(Parent);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002406
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002407 for (unsigned I = 0; I != NumTokens; ++I) {
2408 // Determine whether we saw a cursor at this token's location.
2409 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
2410 if (Pos == Annotated.end())
2411 continue;
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002412
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002413 Cursors[I] = Pos->second;
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002414 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002415}
2416
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002417void clang_disposeTokens(CXTranslationUnit TU,
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002418 CXToken *Tokens, unsigned NumTokens) {
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002419 free(Tokens);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002420}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002421
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002422} // end: extern "C"
2423
2424//===----------------------------------------------------------------------===//
Ted Kremenek16b42592010-03-03 06:36:57 +00002425// Operations for querying linkage of a cursor.
2426//===----------------------------------------------------------------------===//
2427
2428extern "C" {
2429CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
Douglas Gregor0396f462010-03-19 05:22:59 +00002430 if (!clang_isDeclaration(cursor.kind))
2431 return CXLinkage_Invalid;
2432
Ted Kremenek16b42592010-03-03 06:36:57 +00002433 Decl *D = cxcursor::getCursorDecl(cursor);
2434 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
2435 switch (ND->getLinkage()) {
2436 case NoLinkage: return CXLinkage_NoLinkage;
2437 case InternalLinkage: return CXLinkage_Internal;
2438 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
2439 case ExternalLinkage: return CXLinkage_External;
2440 };
2441
2442 return CXLinkage_Invalid;
2443}
2444} // end: extern "C"
2445
2446//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00002447// CXString Operations.
2448//===----------------------------------------------------------------------===//
2449
2450extern "C" {
2451const char *clang_getCString(CXString string) {
2452 return string.Spelling;
2453}
2454
2455void clang_disposeString(CXString string) {
2456 if (string.MustFreeString && string.Spelling)
2457 free((void*)string.Spelling);
2458}
Ted Kremenek04bb7162010-01-22 22:44:15 +00002459
Ted Kremenekfb480492010-01-13 21:46:36 +00002460} // end: extern "C"
Ted Kremenek04bb7162010-01-22 22:44:15 +00002461
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002462namespace clang { namespace cxstring {
2463CXString createCXString(const char *String, bool DupString){
2464 CXString Str;
2465 if (DupString) {
2466 Str.Spelling = strdup(String);
2467 Str.MustFreeString = 1;
2468 } else {
2469 Str.Spelling = String;
2470 Str.MustFreeString = 0;
2471 }
2472 return Str;
2473}
2474
2475CXString createCXString(llvm::StringRef String, bool DupString) {
2476 CXString Result;
2477 if (DupString || (!String.empty() && String.data()[String.size()] != 0)) {
2478 char *Spelling = (char *)malloc(String.size() + 1);
2479 memmove(Spelling, String.data(), String.size());
2480 Spelling[String.size()] = 0;
2481 Result.Spelling = Spelling;
2482 Result.MustFreeString = 1;
2483 } else {
2484 Result.Spelling = String.data();
2485 Result.MustFreeString = 0;
2486 }
2487 return Result;
2488}
2489}}
2490
Ted Kremenek04bb7162010-01-22 22:44:15 +00002491//===----------------------------------------------------------------------===//
2492// Misc. utility functions.
2493//===----------------------------------------------------------------------===//
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002494
Ted Kremenek04bb7162010-01-22 22:44:15 +00002495extern "C" {
2496
Ted Kremeneka2a9d6e2010-02-12 22:54:40 +00002497CXString clang_getClangVersion() {
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002498 return createCXString(getClangFullVersion());
Ted Kremenek04bb7162010-01-22 22:44:15 +00002499}
2500
2501} // end: extern "C"