blob: 2b56bfb7d109d4a65fa29d39eea0ae63373936b0 [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 Gregor3687e9d2010-04-05 21:10:19 +0000999 return ASTUnit::LoadFromPCHFile(ast_filename, DefaultDiag(),
Douglas Gregora88084b2010-02-18 18:08:43 +00001000 CXXIdx->getOnlyLocalDecls(),
1001 0, 0, true);
Steve Naroff600866c2009-08-27 19:51:58 +00001002}
1003
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001004CXTranslationUnit
1005clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
1006 const char *source_filename,
1007 int num_command_line_args,
Douglas Gregor4db64a42010-01-23 00:14:00 +00001008 const char **command_line_args,
1009 unsigned num_unsaved_files,
Douglas Gregora88084b2010-02-18 18:08:43 +00001010 struct CXUnsavedFile *unsaved_files) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001011 if (!CIdx)
1012 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001013
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001014 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
1015
Douglas Gregor5352ac02010-01-28 00:27:43 +00001016 // Configure the diagnostics.
1017 DiagnosticOptions DiagOpts;
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001018 llvm::MaybeOwningPtr<Diagnostic> Diags;
1019 Diags.reset(CompilerInstance::createDiagnostics(DiagOpts, 0, 0), true);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001020
Douglas Gregor4db64a42010-01-23 00:14:00 +00001021 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
1022 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattnera0a270c2010-04-05 22:42:27 +00001023 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001024 const llvm::MemoryBuffer *Buffer
Chris Lattnera0a270c2010-04-05 22:42:27 +00001025 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregor4db64a42010-01-23 00:14:00 +00001026 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
1027 Buffer));
1028 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001029
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001030 if (!CXXIdx->getUseExternalASTGeneration()) {
1031 llvm::SmallVector<const char *, 16> Args;
1032
1033 // The 'source_filename' argument is optional. If the caller does not
1034 // specify it then it is assumed that the source file is specified
1035 // in the actual argument list.
1036 if (source_filename)
1037 Args.push_back(source_filename);
1038 Args.insert(Args.end(), command_line_args,
1039 command_line_args + num_command_line_args);
Douglas Gregor94dc8f62010-03-19 16:15:56 +00001040 Args.push_back("-Xclang");
1041 Args.push_back("-detailed-preprocessing-record");
Douglas Gregor5352ac02010-01-28 00:27:43 +00001042 unsigned NumErrors = Diags->getNumErrors();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001043
Ted Kremenek29b72842010-01-07 22:49:05 +00001044#ifdef USE_CRASHTRACER
1045 ArgsCrashTracerInfo ACTI(Args);
Ted Kremenek8a8da7d2010-01-06 03:42:32 +00001046#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001047
Daniel Dunbar94220972009-12-05 02:17:18 +00001048 llvm::OwningPtr<ASTUnit> Unit(
1049 ASTUnit::LoadFromCommandLine(Args.data(), Args.data() + Args.size(),
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001050 Diags,
Daniel Dunbar869824e2009-12-13 03:46:13 +00001051 CXXIdx->getClangResourcesPath(),
Daniel Dunbar94220972009-12-05 02:17:18 +00001052 CXXIdx->getOnlyLocalDecls(),
Douglas Gregor4db64a42010-01-23 00:14:00 +00001053 RemappedFiles.data(),
Douglas Gregora88084b2010-02-18 18:08:43 +00001054 RemappedFiles.size(),
Douglas Gregor94dc8f62010-03-19 16:15:56 +00001055 /*CaptureDiagnostics=*/true));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001056
Daniel Dunbar94220972009-12-05 02:17:18 +00001057 // FIXME: Until we have broader testing, just drop the entire AST if we
1058 // encountered an error.
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001059 if (NumErrors != Diags->getNumErrors()) {
Ted Kremenek34f6a322010-03-05 22:43:29 +00001060 // Make sure to check that 'Unit' is non-NULL.
1061 if (CXXIdx->getDisplayDiagnostics() && Unit.get()) {
Douglas Gregor405634b2010-04-05 18:10:21 +00001062 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
1063 DEnd = Unit->stored_diag_end();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001064 D != DEnd; ++D) {
1065 CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOptions());
Douglas Gregor274f1902010-02-22 23:17:23 +00001066 CXString Msg = clang_formatDiagnostic(&Diag,
1067 clang_defaultDiagnosticDisplayOptions());
1068 fprintf(stderr, "%s\n", clang_getCString(Msg));
1069 clang_disposeString(Msg);
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001070 }
Douglas Gregor274f1902010-02-22 23:17:23 +00001071#ifdef LLVM_ON_WIN32
1072 // On Windows, force a flush, since there may be multiple copies of
1073 // stderr and stdout in the file system, all with different buffers
1074 // but writing to the same device.
1075 fflush(stderr);
Ted Kremenek83c51842010-03-26 01:34:51 +00001076#endif
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001077 }
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001078 }
Daniel Dunbar94220972009-12-05 02:17:18 +00001079
1080 return Unit.take();
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001081 }
1082
Ted Kremenek139ba862009-10-22 00:03:57 +00001083 // Build up the arguments for invoking 'clang'.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001084 std::vector<const char *> argv;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001085
Ted Kremenek139ba862009-10-22 00:03:57 +00001086 // First add the complete path to the 'clang' executable.
1087 llvm::sys::Path ClangPath = static_cast<CIndexer *>(CIdx)->getClangPath();
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00001088 argv.push_back(ClangPath.c_str());
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001089
Ted Kremenek139ba862009-10-22 00:03:57 +00001090 // Add the '-emit-ast' option as our execution mode for 'clang'.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001091 argv.push_back("-emit-ast");
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001092
Ted Kremenek139ba862009-10-22 00:03:57 +00001093 // The 'source_filename' argument is optional. If the caller does not
1094 // specify it then it is assumed that the source file is specified
1095 // in the actual argument list.
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001096 if (source_filename)
1097 argv.push_back(source_filename);
Ted Kremenek139ba862009-10-22 00:03:57 +00001098
Steve Naroff37b5ac22009-10-15 20:50:09 +00001099 // Generate a temporary name for the AST file.
Ted Kremenek139ba862009-10-22 00:03:57 +00001100 argv.push_back("-o");
Benjamin Kramerc2a98162010-03-13 21:22:49 +00001101 char astTmpFile[L_tmpnam];
1102 argv.push_back(tmpnam(astTmpFile));
Ted Kremenek139ba862009-10-22 00:03:57 +00001103
Douglas Gregor4db64a42010-01-23 00:14:00 +00001104 // Remap any unsaved files to temporary files.
1105 std::vector<llvm::sys::Path> TemporaryFiles;
1106 std::vector<std::string> RemapArgs;
1107 if (RemapFiles(num_unsaved_files, unsaved_files, RemapArgs, TemporaryFiles))
1108 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001109
Douglas Gregor4db64a42010-01-23 00:14:00 +00001110 // The pointers into the elements of RemapArgs are stable because we
1111 // won't be adding anything to RemapArgs after this point.
1112 for (unsigned i = 0, e = RemapArgs.size(); i != e; ++i)
1113 argv.push_back(RemapArgs[i].c_str());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001114
Ted Kremenek139ba862009-10-22 00:03:57 +00001115 // Process the compiler options, stripping off '-o', '-c', '-fsyntax-only'.
1116 for (int i = 0; i < num_command_line_args; ++i)
1117 if (const char *arg = command_line_args[i]) {
1118 if (strcmp(arg, "-o") == 0) {
1119 ++i; // Also skip the matching argument.
1120 continue;
1121 }
1122 if (strcmp(arg, "-emit-ast") == 0 ||
1123 strcmp(arg, "-c") == 0 ||
1124 strcmp(arg, "-fsyntax-only") == 0) {
1125 continue;
1126 }
1127
1128 // Keep the argument.
1129 argv.push_back(arg);
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001130 }
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001131
Douglas Gregord93256e2010-01-28 06:00:51 +00001132 // Generate a temporary name for the diagnostics file.
Benjamin Kramerc2a98162010-03-13 21:22:49 +00001133 char tmpFileResults[L_tmpnam];
1134 char *tmpResultsFileName = tmpnam(tmpFileResults);
1135 llvm::sys::Path DiagnosticsFile(tmpResultsFileName);
Douglas Gregord93256e2010-01-28 06:00:51 +00001136 TemporaryFiles.push_back(DiagnosticsFile);
1137 argv.push_back("-fdiagnostics-binary");
1138
Douglas Gregor94dc8f62010-03-19 16:15:56 +00001139 argv.push_back("-Xclang");
1140 argv.push_back("-detailed-preprocessing-record");
1141
Ted Kremenek139ba862009-10-22 00:03:57 +00001142 // Add the null terminator.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001143 argv.push_back(NULL);
1144
Ted Kremenekfeb15e32009-10-26 22:14:08 +00001145 // Invoke 'clang'.
1146 llvm::sys::Path DevNull; // leave empty, causes redirection to /dev/null
1147 // on Unix or NUL (Windows).
Ted Kremenek379afec2009-10-22 03:24:01 +00001148 std::string ErrMsg;
Douglas Gregord93256e2010-01-28 06:00:51 +00001149 const llvm::sys::Path *Redirects[] = { &DevNull, &DevNull, &DiagnosticsFile,
1150 NULL };
Ted Kremenek379afec2009-10-22 03:24:01 +00001151 llvm::sys::Program::ExecuteAndWait(ClangPath, &argv[0], /* env */ NULL,
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001152 /* redirects */ &Redirects[0],
Ted Kremenek379afec2009-10-22 03:24:01 +00001153 /* secondsToWait */ 0, /* memoryLimits */ 0, &ErrMsg);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001154
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001155 if (!ErrMsg.empty()) {
1156 std::string AllArgs;
Ted Kremenek379afec2009-10-22 03:24:01 +00001157 for (std::vector<const char*>::iterator I = argv.begin(), E = argv.end();
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001158 I != E; ++I) {
1159 AllArgs += ' ';
Ted Kremenek779e5f42009-10-26 22:08:39 +00001160 if (*I)
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001161 AllArgs += *I;
Ted Kremenek779e5f42009-10-26 22:08:39 +00001162 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001163
Daniel Dunbar32141c82010-02-23 20:23:45 +00001164 Diags->Report(diag::err_fe_invoking) << AllArgs << ErrMsg;
Ted Kremenek379afec2009-10-22 03:24:01 +00001165 }
Benjamin Kramer0829a832009-10-18 11:19:36 +00001166
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001167 ASTUnit *ATU = ASTUnit::LoadFromPCHFile(astTmpFile, Diags,
Douglas Gregor4db64a42010-01-23 00:14:00 +00001168 CXXIdx->getOnlyLocalDecls(),
Douglas Gregor4db64a42010-01-23 00:14:00 +00001169 RemappedFiles.data(),
Douglas Gregora88084b2010-02-18 18:08:43 +00001170 RemappedFiles.size(),
1171 /*CaptureDiagnostics=*/true);
Douglas Gregora88084b2010-02-18 18:08:43 +00001172 if (ATU) {
1173 LoadSerializedDiagnostics(DiagnosticsFile,
1174 num_unsaved_files, unsaved_files,
1175 ATU->getFileManager(),
1176 ATU->getSourceManager(),
Douglas Gregor405634b2010-04-05 18:10:21 +00001177 ATU->getStoredDiagnostics());
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001178 } else if (CXXIdx->getDisplayDiagnostics()) {
1179 // We failed to load the ASTUnit, but we can still deserialize the
1180 // diagnostics and emit them.
1181 FileManager FileMgr;
Douglas Gregorf715ca12010-03-16 00:06:06 +00001182 Diagnostic Diag;
1183 SourceManager SourceMgr(Diag);
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001184 // FIXME: Faked LangOpts!
1185 LangOptions LangOpts;
1186 llvm::SmallVector<StoredDiagnostic, 4> Diags;
1187 LoadSerializedDiagnostics(DiagnosticsFile,
1188 num_unsaved_files, unsaved_files,
1189 FileMgr, SourceMgr, Diags);
1190 for (llvm::SmallVector<StoredDiagnostic, 4>::iterator D = Diags.begin(),
1191 DEnd = Diags.end();
1192 D != DEnd; ++D) {
1193 CXStoredDiagnostic Diag(*D, LangOpts);
Douglas Gregor274f1902010-02-22 23:17:23 +00001194 CXString Msg = clang_formatDiagnostic(&Diag,
1195 clang_defaultDiagnosticDisplayOptions());
1196 fprintf(stderr, "%s\n", clang_getCString(Msg));
1197 clang_disposeString(Msg);
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001198 }
Douglas Gregor274f1902010-02-22 23:17:23 +00001199
1200#ifdef LLVM_ON_WIN32
1201 // On Windows, force a flush, since there may be multiple copies of
1202 // stderr and stdout in the file system, all with different buffers
1203 // but writing to the same device.
1204 fflush(stderr);
1205#endif
Douglas Gregora88084b2010-02-18 18:08:43 +00001206 }
Douglas Gregord93256e2010-01-28 06:00:51 +00001207
Douglas Gregor313e26c2010-02-18 23:35:40 +00001208 if (ATU) {
1209 // Make the translation unit responsible for destroying all temporary files.
1210 for (unsigned i = 0, e = TemporaryFiles.size(); i != e; ++i)
1211 ATU->addTemporaryFile(TemporaryFiles[i]);
1212 ATU->addTemporaryFile(llvm::sys::Path(ATU->getPCHFileName()));
1213 } else {
1214 // Destroy all of the temporary files now; they can't be referenced any
1215 // longer.
1216 llvm::sys::Path(astTmpFile).eraseFromDisk();
1217 for (unsigned i = 0, e = TemporaryFiles.size(); i != e; ++i)
1218 TemporaryFiles[i].eraseFromDisk();
1219 }
1220
Steve Naroffe19944c2009-10-15 22:23:48 +00001221 return ATU;
Steve Naroff5b7d8e22009-10-15 20:04:39 +00001222}
1223
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001224void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001225 if (CTUnit)
1226 delete static_cast<ASTUnit *>(CTUnit);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00001227}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001228
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001229CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001230 if (!CTUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001231 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001232
Steve Naroff77accc12009-09-03 18:19:54 +00001233 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001234 return createCXString(CXXUnit->getOriginalSourceFileName(), true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +00001235}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +00001236
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001237CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001238 CXCursor Result = { CXCursor_TranslationUnit, { 0, 0, TU } };
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001239 return Result;
1240}
1241
Ted Kremenekfb480492010-01-13 21:46:36 +00001242} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +00001243
Ted Kremenekfb480492010-01-13 21:46:36 +00001244//===----------------------------------------------------------------------===//
Douglas Gregor1db19de2010-01-19 21:36:55 +00001245// CXSourceLocation and CXSourceRange Operations.
1246//===----------------------------------------------------------------------===//
1247
Douglas Gregorb9790342010-01-22 21:44:22 +00001248extern "C" {
1249CXSourceLocation clang_getNullLocation() {
Douglas Gregor5352ac02010-01-28 00:27:43 +00001250 CXSourceLocation Result = { { 0, 0 }, 0 };
Douglas Gregorb9790342010-01-22 21:44:22 +00001251 return Result;
1252}
1253
1254unsigned clang_equalLocations(CXSourceLocation loc1, CXSourceLocation loc2) {
Daniel Dunbar90a6b9e2010-01-30 23:58:27 +00001255 return (loc1.ptr_data[0] == loc2.ptr_data[0] &&
1256 loc1.ptr_data[1] == loc2.ptr_data[1] &&
1257 loc1.int_data == loc2.int_data);
Douglas Gregorb9790342010-01-22 21:44:22 +00001258}
1259
1260CXSourceLocation clang_getLocation(CXTranslationUnit tu,
1261 CXFile file,
1262 unsigned line,
1263 unsigned column) {
1264 if (!tu)
1265 return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001266
Douglas Gregorb9790342010-01-22 21:44:22 +00001267 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
1268 SourceLocation SLoc
1269 = CXXUnit->getSourceManager().getLocation(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001270 static_cast<const FileEntry *>(file),
Douglas Gregorb9790342010-01-22 21:44:22 +00001271 line, column);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001272
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00001273 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
Douglas Gregorb9790342010-01-22 21:44:22 +00001274}
1275
Douglas Gregor5352ac02010-01-28 00:27:43 +00001276CXSourceRange clang_getNullRange() {
1277 CXSourceRange Result = { { 0, 0 }, 0, 0 };
1278 return Result;
1279}
Daniel Dunbard52864b2010-02-14 10:02:57 +00001280
Douglas Gregor5352ac02010-01-28 00:27:43 +00001281CXSourceRange clang_getRange(CXSourceLocation begin, CXSourceLocation end) {
1282 if (begin.ptr_data[0] != end.ptr_data[0] ||
1283 begin.ptr_data[1] != end.ptr_data[1])
1284 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001285
1286 CXSourceRange Result = { { begin.ptr_data[0], begin.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00001287 begin.int_data, end.int_data };
Douglas Gregorb9790342010-01-22 21:44:22 +00001288 return Result;
1289}
1290
Douglas Gregor46766dc2010-01-26 19:19:08 +00001291void clang_getInstantiationLocation(CXSourceLocation location,
1292 CXFile *file,
1293 unsigned *line,
1294 unsigned *column,
1295 unsigned *offset) {
Douglas Gregor1db19de2010-01-19 21:36:55 +00001296 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
1297
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00001298 if (!location.ptr_data[0] || Loc.isInvalid()) {
Douglas Gregor46766dc2010-01-26 19:19:08 +00001299 if (file)
1300 *file = 0;
1301 if (line)
1302 *line = 0;
1303 if (column)
1304 *column = 0;
1305 if (offset)
1306 *offset = 0;
1307 return;
1308 }
1309
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00001310 const SourceManager &SM =
1311 *static_cast<const SourceManager*>(location.ptr_data[0]);
Douglas Gregor1db19de2010-01-19 21:36:55 +00001312 SourceLocation InstLoc = SM.getInstantiationLoc(Loc);
Douglas Gregor1db19de2010-01-19 21:36:55 +00001313
1314 if (file)
1315 *file = (void *)SM.getFileEntryForID(SM.getFileID(InstLoc));
1316 if (line)
1317 *line = SM.getInstantiationLineNumber(InstLoc);
1318 if (column)
1319 *column = SM.getInstantiationColumnNumber(InstLoc);
Douglas Gregore69517c2010-01-26 03:07:15 +00001320 if (offset)
Douglas Gregor46766dc2010-01-26 19:19:08 +00001321 *offset = SM.getDecomposedLoc(InstLoc).second;
Douglas Gregore69517c2010-01-26 03:07:15 +00001322}
1323
Douglas Gregor1db19de2010-01-19 21:36:55 +00001324CXSourceLocation clang_getRangeStart(CXSourceRange range) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001325 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00001326 range.begin_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00001327 return Result;
1328}
1329
1330CXSourceLocation clang_getRangeEnd(CXSourceRange range) {
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00001331 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00001332 range.end_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00001333 return Result;
1334}
1335
Douglas Gregorb9790342010-01-22 21:44:22 +00001336} // end: extern "C"
1337
Douglas Gregor1db19de2010-01-19 21:36:55 +00001338//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00001339// CXFile Operations.
1340//===----------------------------------------------------------------------===//
1341
1342extern "C" {
Ted Kremenek74844072010-02-17 00:41:20 +00001343CXString clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00001344 if (!SFile)
Ted Kremenek74844072010-02-17 00:41:20 +00001345 return createCXString(NULL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001346
Steve Naroff88145032009-10-27 14:35:18 +00001347 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Ted Kremenek74844072010-02-17 00:41:20 +00001348 return createCXString(FEnt->getName());
Steve Naroff88145032009-10-27 14:35:18 +00001349}
1350
1351time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00001352 if (!SFile)
1353 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001354
Steve Naroff88145032009-10-27 14:35:18 +00001355 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
1356 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +00001357}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001358
Douglas Gregorb9790342010-01-22 21:44:22 +00001359CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
1360 if (!tu)
1361 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001362
Douglas Gregorb9790342010-01-22 21:44:22 +00001363 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001364
Douglas Gregorb9790342010-01-22 21:44:22 +00001365 FileManager &FMgr = CXXUnit->getFileManager();
1366 const FileEntry *File = FMgr.getFile(file_name, file_name+strlen(file_name));
1367 return const_cast<FileEntry *>(File);
1368}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001369
Ted Kremenekfb480492010-01-13 21:46:36 +00001370} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +00001371
Ted Kremenekfb480492010-01-13 21:46:36 +00001372//===----------------------------------------------------------------------===//
1373// CXCursor Operations.
1374//===----------------------------------------------------------------------===//
1375
Ted Kremenekfb480492010-01-13 21:46:36 +00001376static Decl *getDeclFromExpr(Stmt *E) {
1377 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
1378 return RefExpr->getDecl();
1379 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
1380 return ME->getMemberDecl();
1381 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
1382 return RE->getDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001383
Ted Kremenekfb480492010-01-13 21:46:36 +00001384 if (CallExpr *CE = dyn_cast<CallExpr>(E))
1385 return getDeclFromExpr(CE->getCallee());
1386 if (CastExpr *CE = dyn_cast<CastExpr>(E))
1387 return getDeclFromExpr(CE->getSubExpr());
1388 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
1389 return OME->getMethodDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001390
Ted Kremenekfb480492010-01-13 21:46:36 +00001391 return 0;
1392}
1393
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00001394static SourceLocation getLocationFromExpr(Expr *E) {
1395 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
1396 return /*FIXME:*/Msg->getLeftLoc();
1397 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
1398 return DRE->getLocation();
1399 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
1400 return Member->getMemberLoc();
1401 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
1402 return Ivar->getLocation();
1403 return E->getLocStart();
1404}
1405
Ted Kremenekfb480492010-01-13 21:46:36 +00001406extern "C" {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001407
1408unsigned clang_visitChildren(CXCursor parent,
Douglas Gregorb1373d02010-01-20 20:59:29 +00001409 CXCursorVisitor visitor,
1410 CXClientData client_data) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001411 ASTUnit *CXXUnit = getCursorASTUnit(parent);
Douglas Gregorb1373d02010-01-20 20:59:29 +00001412
1413 unsigned PCHLevel = Decl::MaxPCHLevel;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001414
Douglas Gregorb1373d02010-01-20 20:59:29 +00001415 // Set the PCHLevel to filter out unwanted decls if requested.
1416 if (CXXUnit->getOnlyLocalDecls()) {
1417 PCHLevel = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001418
Douglas Gregorb1373d02010-01-20 20:59:29 +00001419 // If the main input was an AST, bump the level.
1420 if (CXXUnit->isMainFileAST())
1421 ++PCHLevel;
1422 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001423
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001424 CursorVisitor CursorVis(CXXUnit, visitor, client_data, PCHLevel);
Douglas Gregorb1373d02010-01-20 20:59:29 +00001425 return CursorVis.VisitChildren(parent);
1426}
1427
Douglas Gregor78205d42010-01-20 21:45:58 +00001428static CXString getDeclSpelling(Decl *D) {
1429 NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
1430 if (!ND)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001431 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001432
Douglas Gregor78205d42010-01-20 21:45:58 +00001433 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001434 return createCXString(OMD->getSelector().getAsString());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001435
Douglas Gregor78205d42010-01-20 21:45:58 +00001436 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
1437 // No, this isn't the same as the code below. getIdentifier() is non-virtual
1438 // and returns different names. NamedDecl returns the class name and
1439 // ObjCCategoryImplDecl returns the category name.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001440 return createCXString(CIMP->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001441
Douglas Gregor78205d42010-01-20 21:45:58 +00001442 if (ND->getIdentifier())
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001443 return createCXString(ND->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001444
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001445 return createCXString("");
Douglas Gregor78205d42010-01-20 21:45:58 +00001446}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001447
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001448CXString clang_getCursorSpelling(CXCursor C) {
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001449 if (clang_isTranslationUnit(C.kind))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001450 return clang_getTranslationUnitSpelling(C.data[2]);
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001451
Steve Narofff334b4e2009-09-02 18:26:48 +00001452 if (clang_isReference(C.kind)) {
1453 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00001454 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +00001455 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001456 return createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00001457 }
1458 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +00001459 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001460 return createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00001461 }
1462 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +00001463 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +00001464 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001465 return createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00001466 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001467 case CXCursor_TypeRef: {
1468 TypeDecl *Type = getCursorTypeRef(C).first;
1469 assert(Type && "Missing type decl");
1470
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001471 return createCXString(getCursorContext(C).getTypeDeclType(Type).
1472 getAsString());
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001473 }
1474
Daniel Dunbaracca7252009-11-30 20:42:49 +00001475 default:
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001476 return createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +00001477 }
1478 }
Douglas Gregor97b98722010-01-19 23:20:36 +00001479
1480 if (clang_isExpression(C.kind)) {
1481 Decl *D = getDeclFromExpr(getCursorExpr(C));
1482 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +00001483 return getDeclSpelling(D);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001484 return createCXString("");
Douglas Gregor97b98722010-01-19 23:20:36 +00001485 }
1486
Douglas Gregor4ae8f292010-03-18 17:52:52 +00001487 if (C.kind == CXCursor_MacroInstantiation)
1488 return createCXString(getCursorMacroInstantiation(C)->getName()
1489 ->getNameStart());
1490
Douglas Gregor572feb22010-03-18 18:04:21 +00001491 if (C.kind == CXCursor_MacroDefinition)
1492 return createCXString(getCursorMacroDefinition(C)->getName()
1493 ->getNameStart());
1494
Douglas Gregor60cbfac2010-01-25 16:56:17 +00001495 if (clang_isDeclaration(C.kind))
1496 return getDeclSpelling(getCursorDecl(C));
Ted Kremeneke68fff62010-02-17 00:41:32 +00001497
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001498 return createCXString("");
Steve Narofff334b4e2009-09-02 18:26:48 +00001499}
1500
Ted Kremeneke68fff62010-02-17 00:41:32 +00001501CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00001502 switch (Kind) {
Ted Kremeneke68fff62010-02-17 00:41:32 +00001503 case CXCursor_FunctionDecl:
1504 return createCXString("FunctionDecl");
1505 case CXCursor_TypedefDecl:
1506 return createCXString("TypedefDecl");
1507 case CXCursor_EnumDecl:
1508 return createCXString("EnumDecl");
1509 case CXCursor_EnumConstantDecl:
1510 return createCXString("EnumConstantDecl");
1511 case CXCursor_StructDecl:
1512 return createCXString("StructDecl");
1513 case CXCursor_UnionDecl:
1514 return createCXString("UnionDecl");
1515 case CXCursor_ClassDecl:
1516 return createCXString("ClassDecl");
1517 case CXCursor_FieldDecl:
1518 return createCXString("FieldDecl");
1519 case CXCursor_VarDecl:
1520 return createCXString("VarDecl");
1521 case CXCursor_ParmDecl:
1522 return createCXString("ParmDecl");
1523 case CXCursor_ObjCInterfaceDecl:
1524 return createCXString("ObjCInterfaceDecl");
1525 case CXCursor_ObjCCategoryDecl:
1526 return createCXString("ObjCCategoryDecl");
1527 case CXCursor_ObjCProtocolDecl:
1528 return createCXString("ObjCProtocolDecl");
1529 case CXCursor_ObjCPropertyDecl:
1530 return createCXString("ObjCPropertyDecl");
1531 case CXCursor_ObjCIvarDecl:
1532 return createCXString("ObjCIvarDecl");
1533 case CXCursor_ObjCInstanceMethodDecl:
1534 return createCXString("ObjCInstanceMethodDecl");
1535 case CXCursor_ObjCClassMethodDecl:
1536 return createCXString("ObjCClassMethodDecl");
1537 case CXCursor_ObjCImplementationDecl:
1538 return createCXString("ObjCImplementationDecl");
1539 case CXCursor_ObjCCategoryImplDecl:
1540 return createCXString("ObjCCategoryImplDecl");
1541 case CXCursor_UnexposedDecl:
1542 return createCXString("UnexposedDecl");
1543 case CXCursor_ObjCSuperClassRef:
1544 return createCXString("ObjCSuperClassRef");
1545 case CXCursor_ObjCProtocolRef:
1546 return createCXString("ObjCProtocolRef");
1547 case CXCursor_ObjCClassRef:
1548 return createCXString("ObjCClassRef");
1549 case CXCursor_TypeRef:
1550 return createCXString("TypeRef");
1551 case CXCursor_UnexposedExpr:
1552 return createCXString("UnexposedExpr");
1553 case CXCursor_DeclRefExpr:
1554 return createCXString("DeclRefExpr");
1555 case CXCursor_MemberRefExpr:
1556 return createCXString("MemberRefExpr");
1557 case CXCursor_CallExpr:
1558 return createCXString("CallExpr");
1559 case CXCursor_ObjCMessageExpr:
1560 return createCXString("ObjCMessageExpr");
1561 case CXCursor_UnexposedStmt:
1562 return createCXString("UnexposedStmt");
1563 case CXCursor_InvalidFile:
1564 return createCXString("InvalidFile");
Ted Kremenek292db642010-03-19 20:39:05 +00001565 case CXCursor_InvalidCode:
1566 return createCXString("InvalidCode");
Ted Kremeneke68fff62010-02-17 00:41:32 +00001567 case CXCursor_NoDeclFound:
1568 return createCXString("NoDeclFound");
1569 case CXCursor_NotImplemented:
1570 return createCXString("NotImplemented");
1571 case CXCursor_TranslationUnit:
1572 return createCXString("TranslationUnit");
Ted Kremeneke77f4432010-02-18 03:09:07 +00001573 case CXCursor_UnexposedAttr:
1574 return createCXString("UnexposedAttr");
1575 case CXCursor_IBActionAttr:
1576 return createCXString("attribute(ibaction)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00001577 case CXCursor_IBOutletAttr:
1578 return createCXString("attribute(iboutlet)");
1579 case CXCursor_PreprocessingDirective:
1580 return createCXString("preprocessing directive");
Douglas Gregor572feb22010-03-18 18:04:21 +00001581 case CXCursor_MacroDefinition:
1582 return createCXString("macro definition");
Douglas Gregor48072312010-03-18 15:23:44 +00001583 case CXCursor_MacroInstantiation:
1584 return createCXString("macro instantiation");
Steve Naroff89922f82009-08-31 00:59:03 +00001585 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00001586
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00001587 llvm_unreachable("Unhandled CXCursorKind");
Ted Kremeneke68fff62010-02-17 00:41:32 +00001588 return createCXString(NULL);
Steve Naroff600866c2009-08-27 19:51:58 +00001589}
Steve Naroff89922f82009-08-31 00:59:03 +00001590
Ted Kremeneke68fff62010-02-17 00:41:32 +00001591enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
1592 CXCursor parent,
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001593 CXClientData client_data) {
1594 CXCursor *BestCursor = static_cast<CXCursor *>(client_data);
1595 *BestCursor = cursor;
1596 return CXChildVisit_Recurse;
1597}
Ted Kremeneke68fff62010-02-17 00:41:32 +00001598
Douglas Gregorb9790342010-01-22 21:44:22 +00001599CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
1600 if (!TU)
Ted Kremenekf4629892010-01-14 01:51:23 +00001601 return clang_getNullCursor();
Ted Kremeneke68fff62010-02-17 00:41:32 +00001602
Douglas Gregorb9790342010-01-22 21:44:22 +00001603 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
1604
Douglas Gregorbdf60622010-03-05 21:16:25 +00001605 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
1606
Ted Kremeneka297de22010-01-25 22:34:44 +00001607 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001608 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
1609 if (SLoc.isValid()) {
Daniel Dunbard52864b2010-02-14 10:02:57 +00001610 SourceRange RegionOfInterest(SLoc, SLoc.getFileLocWithOffset(1));
Ted Kremeneke68fff62010-02-17 00:41:32 +00001611
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001612 // FIXME: Would be great to have a "hint" cursor, then walk from that
1613 // hint cursor upward until we find a cursor whose source range encloses
1614 // the region of interest, rather than starting from the translation unit.
1615 CXCursor Parent = clang_getTranslationUnitCursor(CXXUnit);
Ted Kremeneke68fff62010-02-17 00:41:32 +00001616 CursorVisitor CursorVis(CXXUnit, GetCursorVisitor, &Result,
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001617 Decl::MaxPCHLevel, RegionOfInterest);
1618 CursorVis.VisitChildren(Parent);
Steve Naroff77128dd2009-09-15 20:25:34 +00001619 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00001620 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00001621}
1622
Ted Kremenek73885552009-11-17 19:28:59 +00001623CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00001624 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00001625}
1626
1627unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00001628 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00001629}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001630
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001631unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00001632 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
1633}
1634
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001635unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +00001636 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
1637}
Steve Naroff2d4d6292009-08-31 14:26:51 +00001638
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001639unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00001640 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
1641}
1642
Douglas Gregor97b98722010-01-19 23:20:36 +00001643unsigned clang_isExpression(enum CXCursorKind K) {
1644 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
1645}
1646
1647unsigned clang_isStatement(enum CXCursorKind K) {
1648 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
1649}
1650
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001651unsigned clang_isTranslationUnit(enum CXCursorKind K) {
1652 return K == CXCursor_TranslationUnit;
1653}
1654
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00001655unsigned clang_isPreprocessing(enum CXCursorKind K) {
1656 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
1657}
1658
Ted Kremenekad6eff62010-03-08 21:17:29 +00001659unsigned clang_isUnexposed(enum CXCursorKind K) {
1660 switch (K) {
1661 case CXCursor_UnexposedDecl:
1662 case CXCursor_UnexposedExpr:
1663 case CXCursor_UnexposedStmt:
1664 case CXCursor_UnexposedAttr:
1665 return true;
1666 default:
1667 return false;
1668 }
1669}
1670
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001671CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00001672 return C.kind;
1673}
1674
Douglas Gregor98258af2010-01-18 22:46:11 +00001675CXSourceLocation clang_getCursorLocation(CXCursor C) {
1676 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00001677 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001678 case CXCursor_ObjCSuperClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00001679 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1680 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001681 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001682 }
1683
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001684 case CXCursor_ObjCProtocolRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00001685 std::pair<ObjCProtocolDecl *, SourceLocation> P
1686 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001687 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001688 }
1689
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001690 case CXCursor_ObjCClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00001691 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1692 = getCursorObjCClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001693 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001694 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001695
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001696 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001697 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001698 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001699 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001700
Douglas Gregorf46034a2010-01-18 23:41:10 +00001701 default:
1702 // FIXME: Need a way to enumerate all non-reference cases.
1703 llvm_unreachable("Missed a reference kind");
1704 }
Douglas Gregor98258af2010-01-18 22:46:11 +00001705 }
Douglas Gregor97b98722010-01-19 23:20:36 +00001706
1707 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001708 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00001709 getLocationFromExpr(getCursorExpr(C)));
1710
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00001711 if (C.kind == CXCursor_PreprocessingDirective) {
1712 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
1713 return cxloc::translateSourceLocation(getCursorContext(C), L);
1714 }
Douglas Gregor48072312010-03-18 15:23:44 +00001715
1716 if (C.kind == CXCursor_MacroInstantiation) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00001717 SourceLocation L
1718 = cxcursor::getCursorMacroInstantiation(C)->getSourceRange().getBegin();
Douglas Gregor48072312010-03-18 15:23:44 +00001719 return cxloc::translateSourceLocation(getCursorContext(C), L);
1720 }
Douglas Gregor572feb22010-03-18 18:04:21 +00001721
1722 if (C.kind == CXCursor_MacroDefinition) {
1723 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
1724 return cxloc::translateSourceLocation(getCursorContext(C), L);
1725 }
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00001726
Douglas Gregor5352ac02010-01-28 00:27:43 +00001727 if (!getCursorDecl(C))
1728 return clang_getNullLocation();
Douglas Gregor98258af2010-01-18 22:46:11 +00001729
Douglas Gregorf46034a2010-01-18 23:41:10 +00001730 Decl *D = getCursorDecl(C);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001731 SourceLocation Loc = D->getLocation();
1732 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
1733 Loc = Class->getClassLoc();
Douglas Gregor2ca54fe2010-03-22 15:53:50 +00001734 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00001735}
Douglas Gregora7bde202010-01-19 00:34:46 +00001736
1737CXSourceRange clang_getCursorExtent(CXCursor C) {
1738 if (clang_isReference(C.kind)) {
1739 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001740 case CXCursor_ObjCSuperClassRef: {
Douglas Gregora7bde202010-01-19 00:34:46 +00001741 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1742 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001743 return cxloc::translateSourceRange(P.first->getASTContext(), P.second);
Douglas Gregora7bde202010-01-19 00:34:46 +00001744 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001745
1746 case CXCursor_ObjCProtocolRef: {
Douglas Gregora7bde202010-01-19 00:34:46 +00001747 std::pair<ObjCProtocolDecl *, SourceLocation> P
1748 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001749 return cxloc::translateSourceRange(P.first->getASTContext(), P.second);
Douglas Gregora7bde202010-01-19 00:34:46 +00001750 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001751
1752 case CXCursor_ObjCClassRef: {
Douglas Gregora7bde202010-01-19 00:34:46 +00001753 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1754 = getCursorObjCClassRef(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001755
Ted Kremeneka297de22010-01-25 22:34:44 +00001756 return cxloc::translateSourceRange(P.first->getASTContext(), P.second);
Douglas Gregora7bde202010-01-19 00:34:46 +00001757 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001758
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001759 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001760 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001761 return cxloc::translateSourceRange(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001762 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001763
Douglas Gregora7bde202010-01-19 00:34:46 +00001764 default:
1765 // FIXME: Need a way to enumerate all non-reference cases.
1766 llvm_unreachable("Missed a reference kind");
1767 }
1768 }
Douglas Gregor97b98722010-01-19 23:20:36 +00001769
1770 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001771 return cxloc::translateSourceRange(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00001772 getCursorExpr(C)->getSourceRange());
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001773
1774 if (clang_isStatement(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001775 return cxloc::translateSourceRange(getCursorContext(C),
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001776 getCursorStmt(C)->getSourceRange());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001777
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00001778 if (C.kind == CXCursor_PreprocessingDirective) {
1779 SourceRange R = cxcursor::getCursorPreprocessingDirective(C);
1780 return cxloc::translateSourceRange(getCursorContext(C), R);
1781 }
Douglas Gregor48072312010-03-18 15:23:44 +00001782
1783 if (C.kind == CXCursor_MacroInstantiation) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00001784 SourceRange R = cxcursor::getCursorMacroInstantiation(C)->getSourceRange();
Douglas Gregor48072312010-03-18 15:23:44 +00001785 return cxloc::translateSourceRange(getCursorContext(C), R);
1786 }
Douglas Gregor572feb22010-03-18 18:04:21 +00001787
1788 if (C.kind == CXCursor_MacroDefinition) {
1789 SourceRange R = cxcursor::getCursorMacroDefinition(C)->getSourceRange();
1790 return cxloc::translateSourceRange(getCursorContext(C), R);
1791 }
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00001792
Douglas Gregor5352ac02010-01-28 00:27:43 +00001793 if (!getCursorDecl(C))
1794 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001795
Douglas Gregora7bde202010-01-19 00:34:46 +00001796 Decl *D = getCursorDecl(C);
Douglas Gregor2ca54fe2010-03-22 15:53:50 +00001797 return cxloc::translateSourceRange(getCursorContext(C), D->getSourceRange());
Douglas Gregora7bde202010-01-19 00:34:46 +00001798}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001799
1800CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001801 if (clang_isInvalid(C.kind))
1802 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001803
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001804 ASTUnit *CXXUnit = getCursorASTUnit(C);
Douglas Gregorb6998662010-01-19 19:34:47 +00001805 if (clang_isDeclaration(C.kind))
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001806 return C;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001807
Douglas Gregor97b98722010-01-19 23:20:36 +00001808 if (clang_isExpression(C.kind)) {
1809 Decl *D = getDeclFromExpr(getCursorExpr(C));
1810 if (D)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001811 return MakeCXCursor(D, CXXUnit);
Douglas Gregor97b98722010-01-19 23:20:36 +00001812 return clang_getNullCursor();
1813 }
1814
Douglas Gregorbf7efa22010-03-18 18:23:03 +00001815 if (C.kind == CXCursor_MacroInstantiation) {
1816 if (MacroDefinition *Def = getCursorMacroInstantiation(C)->getDefinition())
1817 return MakeMacroDefinitionCursor(Def, CXXUnit);
1818 }
1819
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001820 if (!clang_isReference(C.kind))
1821 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001822
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001823 switch (C.kind) {
1824 case CXCursor_ObjCSuperClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001825 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001826
1827 case CXCursor_ObjCProtocolRef: {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001828 return MakeCXCursor(getCursorObjCProtocolRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001829
1830 case CXCursor_ObjCClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001831 return MakeCXCursor(getCursorObjCClassRef(C).first, CXXUnit);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001832
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001833 case CXCursor_TypeRef:
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001834 return MakeCXCursor(getCursorTypeRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001835
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001836 default:
1837 // We would prefer to enumerate all non-reference cursor kinds here.
1838 llvm_unreachable("Unhandled reference cursor kind");
1839 break;
1840 }
1841 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001842
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001843 return clang_getNullCursor();
1844}
1845
Douglas Gregorb6998662010-01-19 19:34:47 +00001846CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001847 if (clang_isInvalid(C.kind))
1848 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001849
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001850 ASTUnit *CXXUnit = getCursorASTUnit(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001851
Douglas Gregorb6998662010-01-19 19:34:47 +00001852 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00001853 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00001854 C = clang_getCursorReferenced(C);
1855 WasReference = true;
1856 }
1857
Douglas Gregorbf7efa22010-03-18 18:23:03 +00001858 if (C.kind == CXCursor_MacroInstantiation)
1859 return clang_getCursorReferenced(C);
1860
Douglas Gregorb6998662010-01-19 19:34:47 +00001861 if (!clang_isDeclaration(C.kind))
1862 return clang_getNullCursor();
1863
1864 Decl *D = getCursorDecl(C);
1865 if (!D)
1866 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001867
Douglas Gregorb6998662010-01-19 19:34:47 +00001868 switch (D->getKind()) {
1869 // Declaration kinds that don't really separate the notions of
1870 // declaration and definition.
1871 case Decl::Namespace:
1872 case Decl::Typedef:
1873 case Decl::TemplateTypeParm:
1874 case Decl::EnumConstant:
1875 case Decl::Field:
1876 case Decl::ObjCIvar:
1877 case Decl::ObjCAtDefsField:
1878 case Decl::ImplicitParam:
1879 case Decl::ParmVar:
1880 case Decl::NonTypeTemplateParm:
1881 case Decl::TemplateTemplateParm:
1882 case Decl::ObjCCategoryImpl:
1883 case Decl::ObjCImplementation:
1884 case Decl::LinkageSpec:
1885 case Decl::ObjCPropertyImpl:
1886 case Decl::FileScopeAsm:
1887 case Decl::StaticAssert:
1888 case Decl::Block:
1889 return C;
1890
1891 // Declaration kinds that don't make any sense here, but are
1892 // nonetheless harmless.
1893 case Decl::TranslationUnit:
1894 case Decl::Template:
1895 case Decl::ObjCContainer:
1896 break;
1897
1898 // Declaration kinds for which the definition is not resolvable.
1899 case Decl::UnresolvedUsingTypename:
1900 case Decl::UnresolvedUsingValue:
1901 break;
1902
1903 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001904 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
1905 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001906
1907 case Decl::NamespaceAlias:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001908 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001909
1910 case Decl::Enum:
1911 case Decl::Record:
1912 case Decl::CXXRecord:
1913 case Decl::ClassTemplateSpecialization:
1914 case Decl::ClassTemplatePartialSpecialization:
Douglas Gregor952b0172010-02-11 01:04:33 +00001915 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001916 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001917 return clang_getNullCursor();
1918
1919 case Decl::Function:
1920 case Decl::CXXMethod:
1921 case Decl::CXXConstructor:
1922 case Decl::CXXDestructor:
1923 case Decl::CXXConversion: {
1924 const FunctionDecl *Def = 0;
1925 if (cast<FunctionDecl>(D)->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001926 return MakeCXCursor(const_cast<FunctionDecl *>(Def), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001927 return clang_getNullCursor();
1928 }
1929
1930 case Decl::Var: {
Sebastian Redl31310a22010-02-01 20:16:42 +00001931 // Ask the variable if it has a definition.
1932 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
1933 return MakeCXCursor(Def, CXXUnit);
1934 return clang_getNullCursor();
Douglas Gregorb6998662010-01-19 19:34:47 +00001935 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001936
Douglas Gregorb6998662010-01-19 19:34:47 +00001937 case Decl::FunctionTemplate: {
1938 const FunctionDecl *Def = 0;
1939 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001940 return MakeCXCursor(Def->getDescribedFunctionTemplate(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001941 return clang_getNullCursor();
1942 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001943
Douglas Gregorb6998662010-01-19 19:34:47 +00001944 case Decl::ClassTemplate: {
1945 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
Douglas Gregor952b0172010-02-11 01:04:33 +00001946 ->getDefinition())
Douglas Gregorb6998662010-01-19 19:34:47 +00001947 return MakeCXCursor(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001948 cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001949 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001950 return clang_getNullCursor();
1951 }
1952
1953 case Decl::Using: {
1954 UsingDecl *Using = cast<UsingDecl>(D);
1955 CXCursor Def = clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001956 for (UsingDecl::shadow_iterator S = Using->shadow_begin(),
1957 SEnd = Using->shadow_end();
Douglas Gregorb6998662010-01-19 19:34:47 +00001958 S != SEnd; ++S) {
1959 if (Def != clang_getNullCursor()) {
1960 // FIXME: We have no way to return multiple results.
1961 return clang_getNullCursor();
1962 }
1963
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001964 Def = clang_getCursorDefinition(MakeCXCursor((*S)->getTargetDecl(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001965 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00001966 }
1967
1968 return Def;
1969 }
1970
1971 case Decl::UsingShadow:
1972 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001973 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001974 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00001975
1976 case Decl::ObjCMethod: {
1977 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
1978 if (Method->isThisDeclarationADefinition())
1979 return C;
1980
1981 // Dig out the method definition in the associated
1982 // @implementation, if we have it.
1983 // FIXME: The ASTs should make finding the definition easier.
1984 if (ObjCInterfaceDecl *Class
1985 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
1986 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
1987 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
1988 Method->isInstanceMethod()))
1989 if (Def->isThisDeclarationADefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001990 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001991
1992 return clang_getNullCursor();
1993 }
1994
1995 case Decl::ObjCCategory:
1996 if (ObjCCategoryImplDecl *Impl
1997 = cast<ObjCCategoryDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001998 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001999 return clang_getNullCursor();
2000
2001 case Decl::ObjCProtocol:
2002 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
2003 return C;
2004 return clang_getNullCursor();
2005
2006 case Decl::ObjCInterface:
2007 // There are two notions of a "definition" for an Objective-C
2008 // class: the interface and its implementation. When we resolved a
2009 // reference to an Objective-C class, produce the @interface as
2010 // the definition; when we were provided with the interface,
2011 // produce the @implementation as the definition.
2012 if (WasReference) {
2013 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
2014 return C;
2015 } else if (ObjCImplementationDecl *Impl
2016 = cast<ObjCInterfaceDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002017 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002018 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002019
Douglas Gregorb6998662010-01-19 19:34:47 +00002020 case Decl::ObjCProperty:
2021 // FIXME: We don't really know where to find the
2022 // ObjCPropertyImplDecls that implement this property.
2023 return clang_getNullCursor();
2024
2025 case Decl::ObjCCompatibleAlias:
2026 if (ObjCInterfaceDecl *Class
2027 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
2028 if (!Class->isForwardDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002029 return MakeCXCursor(Class, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002030
Douglas Gregorb6998662010-01-19 19:34:47 +00002031 return clang_getNullCursor();
2032
2033 case Decl::ObjCForwardProtocol: {
2034 ObjCForwardProtocolDecl *Forward = cast<ObjCForwardProtocolDecl>(D);
2035 if (Forward->protocol_size() == 1)
2036 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002037 MakeCXCursor(*Forward->protocol_begin(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002038 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002039
2040 // FIXME: Cannot return multiple definitions.
2041 return clang_getNullCursor();
2042 }
2043
2044 case Decl::ObjCClass: {
2045 ObjCClassDecl *Class = cast<ObjCClassDecl>(D);
2046 if (Class->size() == 1) {
2047 ObjCInterfaceDecl *IFace = Class->begin()->getInterface();
2048 if (!IFace->isForwardDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002049 return MakeCXCursor(IFace, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002050 return clang_getNullCursor();
2051 }
2052
2053 // FIXME: Cannot return multiple definitions.
2054 return clang_getNullCursor();
2055 }
2056
2057 case Decl::Friend:
2058 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002059 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002060 return clang_getNullCursor();
2061
2062 case Decl::FriendTemplate:
2063 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002064 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002065 return clang_getNullCursor();
2066 }
2067
2068 return clang_getNullCursor();
2069}
2070
2071unsigned clang_isCursorDefinition(CXCursor C) {
2072 if (!clang_isDeclaration(C.kind))
2073 return 0;
2074
2075 return clang_getCursorDefinition(C) == C;
2076}
2077
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002078void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00002079 const char **startBuf,
2080 const char **endBuf,
2081 unsigned *startLine,
2082 unsigned *startColumn,
2083 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002084 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00002085 assert(getCursorDecl(C) && "CXCursor has null decl");
2086 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00002087 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
2088 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002089
Steve Naroff4ade6d62009-09-23 17:52:52 +00002090 SourceManager &SM = FD->getASTContext().getSourceManager();
2091 *startBuf = SM.getCharacterData(Body->getLBracLoc());
2092 *endBuf = SM.getCharacterData(Body->getRBracLoc());
2093 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
2094 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
2095 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
2096 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
2097}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002098
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002099void clang_enableStackTraces(void) {
2100 llvm::sys::PrintStackTraceOnErrorSignal();
2101}
2102
Ted Kremenekfb480492010-01-13 21:46:36 +00002103} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00002104
Ted Kremenekfb480492010-01-13 21:46:36 +00002105//===----------------------------------------------------------------------===//
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002106// Token-based Operations.
2107//===----------------------------------------------------------------------===//
2108
2109/* CXToken layout:
2110 * int_data[0]: a CXTokenKind
2111 * int_data[1]: starting token location
2112 * int_data[2]: token length
2113 * int_data[3]: reserved
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002114 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002115 * otherwise unused.
2116 */
2117extern "C" {
2118
2119CXTokenKind clang_getTokenKind(CXToken CXTok) {
2120 return static_cast<CXTokenKind>(CXTok.int_data[0]);
2121}
2122
2123CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
2124 switch (clang_getTokenKind(CXTok)) {
2125 case CXToken_Identifier:
2126 case CXToken_Keyword:
2127 // We know we have an IdentifierInfo*, so use that.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002128 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
2129 ->getNameStart());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002130
2131 case CXToken_Literal: {
2132 // We have stashed the starting pointer in the ptr_data field. Use it.
2133 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002134 return createCXString(llvm::StringRef(Text, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002135 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002136
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002137 case CXToken_Punctuation:
2138 case CXToken_Comment:
2139 break;
2140 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002141
2142 // We have to find the starting buffer pointer the hard way, by
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002143 // deconstructing the source location.
2144 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2145 if (!CXXUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002146 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002147
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002148 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
2149 std::pair<FileID, unsigned> LocInfo
2150 = CXXUnit->getSourceManager().getDecomposedLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +00002151 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002152 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00002153 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
2154 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00002155 return createCXString("");
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002156
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002157 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002158}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002159
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002160CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
2161 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2162 if (!CXXUnit)
2163 return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002164
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002165 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
2166 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
2167}
2168
2169CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
2170 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregor5352ac02010-01-28 00:27:43 +00002171 if (!CXXUnit)
2172 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002173
2174 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002175 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
2176}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002177
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002178void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
2179 CXToken **Tokens, unsigned *NumTokens) {
2180 if (Tokens)
2181 *Tokens = 0;
2182 if (NumTokens)
2183 *NumTokens = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002184
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002185 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2186 if (!CXXUnit || !Tokens || !NumTokens)
2187 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002188
Douglas Gregorbdf60622010-03-05 21:16:25 +00002189 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
2190
Daniel Dunbar85b988f2010-02-14 08:31:57 +00002191 SourceRange R = cxloc::translateCXSourceRange(Range);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002192 if (R.isInvalid())
2193 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002194
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002195 SourceManager &SourceMgr = CXXUnit->getSourceManager();
2196 std::pair<FileID, unsigned> BeginLocInfo
2197 = SourceMgr.getDecomposedLoc(R.getBegin());
2198 std::pair<FileID, unsigned> EndLocInfo
2199 = SourceMgr.getDecomposedLoc(R.getEnd());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002200
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002201 // Cannot tokenize across files.
2202 if (BeginLocInfo.first != EndLocInfo.first)
2203 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002204
2205 // Create a lexer
Douglas Gregorf715ca12010-03-16 00:06:06 +00002206 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002207 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00002208 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
Douglas Gregor47a3fcd2010-03-16 20:26:15 +00002209 if (Invalid)
2210 return;
Douglas Gregoraea67db2010-03-15 22:54:52 +00002211
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002212 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
2213 CXXUnit->getASTContext().getLangOptions(),
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002214 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002215 Lex.SetCommentRetentionState(true);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002216
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002217 // Lex tokens until we hit the end of the range.
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002218 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002219 llvm::SmallVector<CXToken, 32> CXTokens;
2220 Token Tok;
2221 do {
2222 // Lex the next token
2223 Lex.LexFromRawLexer(Tok);
2224 if (Tok.is(tok::eof))
2225 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002226
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002227 // Initialize the CXToken.
2228 CXToken CXTok;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002229
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002230 // - Common fields
2231 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
2232 CXTok.int_data[2] = Tok.getLength();
2233 CXTok.int_data[3] = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002234
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002235 // - Kind-specific fields
2236 if (Tok.isLiteral()) {
2237 CXTok.int_data[0] = CXToken_Literal;
2238 CXTok.ptr_data = (void *)Tok.getLiteralData();
2239 } else if (Tok.is(tok::identifier)) {
Douglas Gregoraea67db2010-03-15 22:54:52 +00002240 // Lookup the identifier to determine whether we have a keyword.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002241 std::pair<FileID, unsigned> LocInfo
2242 = SourceMgr.getDecomposedLoc(Tok.getLocation());
Douglas Gregorf715ca12010-03-16 00:06:06 +00002243 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002244 llvm::StringRef Buf
Douglas Gregorf715ca12010-03-16 00:06:06 +00002245 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
2246 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00002247 return;
2248
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002249 const char *StartPos = Buf.data() + LocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002250 IdentifierInfo *II
2251 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok, StartPos);
2252 CXTok.int_data[0] = II->getTokenID() == tok::identifier?
2253 CXToken_Identifier
2254 : CXToken_Keyword;
2255 CXTok.ptr_data = II;
2256 } else if (Tok.is(tok::comment)) {
2257 CXTok.int_data[0] = CXToken_Comment;
2258 CXTok.ptr_data = 0;
2259 } else {
2260 CXTok.int_data[0] = CXToken_Punctuation;
2261 CXTok.ptr_data = 0;
2262 }
2263 CXTokens.push_back(CXTok);
2264 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002265
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002266 if (CXTokens.empty())
2267 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002268
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002269 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
2270 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
2271 *NumTokens = CXTokens.size();
2272}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002273
2274typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
2275
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002276enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
2277 CXCursor parent,
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002278 CXClientData client_data) {
2279 AnnotateTokensData *Data = static_cast<AnnotateTokensData *>(client_data);
2280
2281 // We only annotate the locations of declarations, simple
2282 // references, and expressions which directly reference something.
2283 CXCursorKind Kind = clang_getCursorKind(cursor);
2284 if (clang_isDeclaration(Kind) || clang_isReference(Kind)) {
2285 // Okay: We can annotate the location of this declaration with the
2286 // declaration or reference
2287 } else if (clang_isExpression(cursor.kind)) {
2288 if (Kind != CXCursor_DeclRefExpr &&
2289 Kind != CXCursor_MemberRefExpr &&
2290 Kind != CXCursor_ObjCMessageExpr)
2291 return CXChildVisit_Recurse;
2292
2293 CXCursor Referenced = clang_getCursorReferenced(cursor);
2294 if (Referenced == cursor || Referenced == clang_getNullCursor())
2295 return CXChildVisit_Recurse;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002296
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002297 // Okay: we can annotate the location of this expression
Douglas Gregor0396f462010-03-19 05:22:59 +00002298 } else if (clang_isPreprocessing(cursor.kind)) {
2299 // We can always annotate a preprocessing directive/macro instantiation.
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002300 } else {
2301 // Nothing to annotate
2302 return CXChildVisit_Recurse;
2303 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002304
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002305 CXSourceLocation Loc = clang_getCursorLocation(cursor);
2306 (*Data)[Loc.int_data] = cursor;
2307 return CXChildVisit_Recurse;
2308}
2309
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002310void clang_annotateTokens(CXTranslationUnit TU,
2311 CXToken *Tokens, unsigned NumTokens,
2312 CXCursor *Cursors) {
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002313 if (NumTokens == 0)
2314 return;
2315
2316 // Any token we don't specifically annotate will have a NULL cursor.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002317 for (unsigned I = 0; I != NumTokens; ++I)
2318 Cursors[I] = clang_getNullCursor();
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002319
2320 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2321 if (!CXXUnit || !Tokens)
2322 return;
2323
Douglas Gregorbdf60622010-03-05 21:16:25 +00002324 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
2325
Douglas Gregor0396f462010-03-19 05:22:59 +00002326 // Determine the region of interest, which contains all of the tokens.
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002327 SourceRange RegionOfInterest;
2328 RegionOfInterest.setBegin(
2329 cxloc::translateSourceLocation(clang_getTokenLocation(TU, Tokens[0])));
2330 SourceLocation End
Douglas Gregor09d9fa12010-04-05 16:10:30 +00002331 = cxloc::translateSourceLocation(clang_getTokenLocation(TU,
Douglas Gregor0396f462010-03-19 05:22:59 +00002332 Tokens[NumTokens - 1]));
Daniel Dunbard52864b2010-02-14 10:02:57 +00002333 RegionOfInterest.setEnd(CXXUnit->getPreprocessor().getLocForEndOfToken(End));
Douglas Gregor2507fa82010-03-19 00:18:31 +00002334
Douglas Gregor0396f462010-03-19 05:22:59 +00002335 // A mapping from the source locations found when re-lexing or traversing the
2336 // region of interest to the corresponding cursors.
2337 AnnotateTokensData Annotated;
2338
2339 // Relex the tokens within the source range to look for preprocessing
2340 // directives.
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002341 SourceManager &SourceMgr = CXXUnit->getSourceManager();
2342 std::pair<FileID, unsigned> BeginLocInfo
2343 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
2344 std::pair<FileID, unsigned> EndLocInfo
2345 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
2346
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002347 llvm::StringRef Buffer;
Douglas Gregor0396f462010-03-19 05:22:59 +00002348 bool Invalid = false;
2349 if (BeginLocInfo.first == EndLocInfo.first &&
2350 ((Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid)),true) &&
2351 !Invalid) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002352 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
2353 CXXUnit->getASTContext().getLangOptions(),
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002354 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
2355 Buffer.end());
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002356 Lex.SetCommentRetentionState(true);
2357
2358 // Lex tokens in raw mode until we hit the end of the range, to avoid
2359 // entering #includes or expanding macros.
Douglas Gregor48072312010-03-18 15:23:44 +00002360 while (true) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002361 Token Tok;
2362 Lex.LexFromRawLexer(Tok);
2363
2364 reprocess:
2365 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
2366 // We have found a preprocessing directive. Gobble it up so that we
2367 // don't see it while preprocessing these tokens later, but keep track of
2368 // all of the token locations inside this preprocessing directive so that
2369 // we can annotate them appropriately.
2370 //
2371 // FIXME: Some simple tests here could identify macro definitions and
2372 // #undefs, to provide specific cursor kinds for those.
2373 std::vector<SourceLocation> Locations;
2374 do {
2375 Locations.push_back(Tok.getLocation());
2376 Lex.LexFromRawLexer(Tok);
2377 } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
2378
2379 using namespace cxcursor;
2380 CXCursor Cursor
2381 = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
2382 Locations.back()),
2383 CXXUnit);
2384 for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
2385 Annotated[Locations[I].getRawEncoding()] = Cursor;
2386 }
2387
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002388 if (Tok.isAtStartOfLine())
2389 goto reprocess;
2390
2391 continue;
2392 }
2393
Douglas Gregor48072312010-03-18 15:23:44 +00002394 if (Tok.is(tok::eof))
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002395 break;
2396 }
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002397 }
Douglas Gregor0396f462010-03-19 05:22:59 +00002398
2399 // Annotate all of the source locations in the region of interest that map to
2400 // a specific cursor.
2401 CXCursor Parent = clang_getTranslationUnitCursor(CXXUnit);
2402 CursorVisitor AnnotateVis(CXXUnit, AnnotateTokensVisitor, &Annotated,
2403 Decl::MaxPCHLevel, RegionOfInterest);
2404 AnnotateVis.VisitChildren(Parent);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002405
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002406 for (unsigned I = 0; I != NumTokens; ++I) {
2407 // Determine whether we saw a cursor at this token's location.
2408 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
2409 if (Pos == Annotated.end())
2410 continue;
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002411
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002412 Cursors[I] = Pos->second;
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002413 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002414}
2415
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002416void clang_disposeTokens(CXTranslationUnit TU,
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002417 CXToken *Tokens, unsigned NumTokens) {
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002418 free(Tokens);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002419}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002420
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002421} // end: extern "C"
2422
2423//===----------------------------------------------------------------------===//
Ted Kremenek16b42592010-03-03 06:36:57 +00002424// Operations for querying linkage of a cursor.
2425//===----------------------------------------------------------------------===//
2426
2427extern "C" {
2428CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
Douglas Gregor0396f462010-03-19 05:22:59 +00002429 if (!clang_isDeclaration(cursor.kind))
2430 return CXLinkage_Invalid;
2431
Ted Kremenek16b42592010-03-03 06:36:57 +00002432 Decl *D = cxcursor::getCursorDecl(cursor);
2433 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
2434 switch (ND->getLinkage()) {
2435 case NoLinkage: return CXLinkage_NoLinkage;
2436 case InternalLinkage: return CXLinkage_Internal;
2437 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
2438 case ExternalLinkage: return CXLinkage_External;
2439 };
2440
2441 return CXLinkage_Invalid;
2442}
2443} // end: extern "C"
2444
2445//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00002446// CXString Operations.
2447//===----------------------------------------------------------------------===//
2448
2449extern "C" {
2450const char *clang_getCString(CXString string) {
2451 return string.Spelling;
2452}
2453
2454void clang_disposeString(CXString string) {
2455 if (string.MustFreeString && string.Spelling)
2456 free((void*)string.Spelling);
2457}
Ted Kremenek04bb7162010-01-22 22:44:15 +00002458
Ted Kremenekfb480492010-01-13 21:46:36 +00002459} // end: extern "C"
Ted Kremenek04bb7162010-01-22 22:44:15 +00002460
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002461namespace clang { namespace cxstring {
2462CXString createCXString(const char *String, bool DupString){
2463 CXString Str;
2464 if (DupString) {
2465 Str.Spelling = strdup(String);
2466 Str.MustFreeString = 1;
2467 } else {
2468 Str.Spelling = String;
2469 Str.MustFreeString = 0;
2470 }
2471 return Str;
2472}
2473
2474CXString createCXString(llvm::StringRef String, bool DupString) {
2475 CXString Result;
2476 if (DupString || (!String.empty() && String.data()[String.size()] != 0)) {
2477 char *Spelling = (char *)malloc(String.size() + 1);
2478 memmove(Spelling, String.data(), String.size());
2479 Spelling[String.size()] = 0;
2480 Result.Spelling = Spelling;
2481 Result.MustFreeString = 1;
2482 } else {
2483 Result.Spelling = String.data();
2484 Result.MustFreeString = 0;
2485 }
2486 return Result;
2487}
2488}}
2489
Ted Kremenek04bb7162010-01-22 22:44:15 +00002490//===----------------------------------------------------------------------===//
2491// Misc. utility functions.
2492//===----------------------------------------------------------------------===//
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002493
Ted Kremenek04bb7162010-01-22 22:44:15 +00002494extern "C" {
2495
Ted Kremeneka2a9d6e2010-02-12 22:54:40 +00002496CXString clang_getClangVersion() {
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002497 return createCXString(getClangFullVersion());
Ted Kremenek04bb7162010-01-22 22:44:15 +00002498}
2499
2500} // end: extern "C"