blob: 08882168ffe44efefbb045101e20dfa18f9242d7 [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.
Douglas Gregor94dc8f62010-03-19 16:15:56 +0000460 if (PreprocessingRecord *PPRec
461 = CXXUnit->getPreprocessor().getPreprocessingRecord()) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000462 // FIXME: Once we have the ability to deserialize a preprocessing record,
463 // do so.
Douglas Gregor788f5a12010-03-20 00:41:21 +0000464 PreprocessingRecord::iterator E, EEnd;
465 for (llvm::tie(E, EEnd) = getPreprocessedEntities(); E != EEnd; ++E) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000466 if (MacroInstantiation *MI = dyn_cast<MacroInstantiation>(*E)) {
467 if (Visit(MakeMacroInstantiationCursor(MI, CXXUnit)))
468 return true;
Douglas Gregor788f5a12010-03-20 00:41:21 +0000469
Douglas Gregor0396f462010-03-19 05:22:59 +0000470 continue;
471 }
472
473 if (MacroDefinition *MD = dyn_cast<MacroDefinition>(*E)) {
474 if (Visit(MakeMacroDefinitionCursor(MD, CXXUnit)))
475 return true;
476
477 continue;
478 }
479 }
480 }
Douglas Gregor7b691f332010-01-20 21:13:59 +0000481 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000482 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000483
Douglas Gregorb1373d02010-01-20 20:59:29 +0000484 // Nothing to visit at the moment.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000485 return false;
486}
487
Douglas Gregorb1373d02010-01-20 20:59:29 +0000488bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000489 for (DeclContext::decl_iterator
Douglas Gregorb1373d02010-01-20 20:59:29 +0000490 I = DC->decls_begin(), E = DC->decls_end(); I != E; ++I) {
Ted Kremenek09dfa372010-02-18 05:46:33 +0000491
Daniel Dunbard52864b2010-02-14 10:02:57 +0000492 CXCursor Cursor = MakeCXCursor(*I, TU);
493
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000494 if (RegionOfInterest.isValid()) {
Daniel Dunbard52864b2010-02-14 10:02:57 +0000495 SourceRange Range =
496 cxloc::translateCXSourceRange(clang_getCursorExtent(Cursor));
497 if (Range.isInvalid())
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000498 continue;
Daniel Dunbard52864b2010-02-14 10:02:57 +0000499
500 switch (CompareRegionOfInterest(Range)) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000501 case RangeBefore:
502 // This declaration comes before the region of interest; skip it.
503 continue;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000504
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000505 case RangeAfter:
506 // This declaration comes after the region of interest; we're done.
507 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000508
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000509 case RangeOverlap:
510 // This declaration overlaps the region of interest; visit it.
511 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000512 }
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000513 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000514
Daniel Dunbard52864b2010-02-14 10:02:57 +0000515 if (Visit(Cursor, true))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000516 return true;
517 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000518
Douglas Gregorb1373d02010-01-20 20:59:29 +0000519 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000520}
521
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000522bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
523 llvm_unreachable("Translation units are visited directly by Visit()");
524 return false;
525}
526
527bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
528 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
529 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000530
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000531 return false;
532}
533
534bool CursorVisitor::VisitTagDecl(TagDecl *D) {
535 return VisitDeclContext(D);
536}
537
538bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
539 if (Expr *Init = D->getInitExpr())
540 return Visit(MakeCXCursor(Init, StmtParent, TU));
541 return false;
542}
543
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000544bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
545 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
546 if (Visit(TSInfo->getTypeLoc()))
547 return true;
548
549 return false;
550}
551
Douglas Gregorb1373d02010-01-20 20:59:29 +0000552bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000553 if (VisitDeclaratorDecl(ND))
554 return true;
555
Douglas Gregora59e3902010-01-21 23:27:09 +0000556 if (ND->isThisDeclarationADefinition() &&
557 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
558 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000559
Douglas Gregorb1373d02010-01-20 20:59:29 +0000560 return false;
561}
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000562
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000563bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
564 if (VisitDeclaratorDecl(D))
565 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000566
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000567 if (Expr *BitWidth = D->getBitWidth())
568 return Visit(MakeCXCursor(BitWidth, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000569
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000570 return false;
571}
572
573bool CursorVisitor::VisitVarDecl(VarDecl *D) {
574 if (VisitDeclaratorDecl(D))
575 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000576
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000577 if (Expr *Init = D->getInit())
578 return Visit(MakeCXCursor(Init, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000579
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000580 return false;
581}
582
583bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
Douglas Gregor4bc1cb62010-03-08 14:59:44 +0000584 if (TypeSourceInfo *TSInfo = ND->getResultTypeSourceInfo())
585 if (Visit(TSInfo->getTypeLoc()))
586 return true;
587
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000588 for (ObjCMethodDecl::param_iterator P = ND->param_begin(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000589 PEnd = ND->param_end();
590 P != PEnd; ++P) {
591 if (Visit(MakeCXCursor(*P, TU)))
592 return true;
593 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000594
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000595 if (ND->isThisDeclarationADefinition() &&
596 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
597 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000598
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000599 return false;
600}
601
Douglas Gregora59e3902010-01-21 23:27:09 +0000602bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
603 return VisitDeclContext(D);
604}
605
Douglas Gregorb1373d02010-01-20 20:59:29 +0000606bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000607 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
608 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000609 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000610
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000611 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
612 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
613 E = ND->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000614 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000615 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000616
Douglas Gregora59e3902010-01-21 23:27:09 +0000617 return VisitObjCContainerDecl(ND);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000618}
619
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000620bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
621 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
622 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
623 E = PID->protocol_end(); I != E; ++I, ++PL)
624 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
625 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000626
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000627 return VisitObjCContainerDecl(PID);
628}
629
Douglas Gregorb1373d02010-01-20 20:59:29 +0000630bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000631 // Issue callbacks for super class.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000632 if (D->getSuperClass() &&
633 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000634 D->getSuperClassLoc(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000635 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000636 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000637
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000638 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
639 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
640 E = D->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000641 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000642 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000643
Douglas Gregora59e3902010-01-21 23:27:09 +0000644 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000645}
646
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000647bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
648 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000649}
650
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000651bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
Ted Kremenekebfa3392010-03-19 20:39:03 +0000652 // 'ID' could be null when dealing with invalid code.
653 if (ObjCInterfaceDecl *ID = D->getClassInterface())
654 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
655 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000656
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000657 return VisitObjCImplDecl(D);
658}
659
660bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
661#if 0
662 // Issue callbacks for super class.
663 // FIXME: No source location information!
664 if (D->getSuperClass() &&
665 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000666 D->getSuperClassLoc(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000667 TU)))
668 return true;
669#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000670
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000671 return VisitObjCImplDecl(D);
672}
673
674bool CursorVisitor::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D) {
675 ObjCForwardProtocolDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
676 for (ObjCForwardProtocolDecl::protocol_iterator I = D->protocol_begin(),
677 E = D->protocol_end();
678 I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000679 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000680 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000681
682 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000683}
684
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000685bool CursorVisitor::VisitObjCClassDecl(ObjCClassDecl *D) {
686 for (ObjCClassDecl::iterator C = D->begin(), CEnd = D->end(); C != CEnd; ++C)
687 if (Visit(MakeCursorObjCClassRef(C->getInterface(), C->getLocation(), TU)))
688 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000689
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000690 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000691}
692
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000693bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
694 ASTContext &Context = TU->getASTContext();
695
696 // Some builtin types (such as Objective-C's "id", "sel", and
697 // "Class") have associated declarations. Create cursors for those.
698 QualType VisitType;
699 switch (TL.getType()->getAs<BuiltinType>()->getKind()) {
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000700 case BuiltinType::Void:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000701 case BuiltinType::Bool:
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000702 case BuiltinType::Char_U:
703 case BuiltinType::UChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000704 case BuiltinType::Char16:
705 case BuiltinType::Char32:
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000706 case BuiltinType::UShort:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000707 case BuiltinType::UInt:
708 case BuiltinType::ULong:
709 case BuiltinType::ULongLong:
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000710 case BuiltinType::UInt128:
711 case BuiltinType::Char_S:
712 case BuiltinType::SChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000713 case BuiltinType::WChar:
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000714 case BuiltinType::Short:
715 case BuiltinType::Int:
716 case BuiltinType::Long:
717 case BuiltinType::LongLong:
718 case BuiltinType::Int128:
719 case BuiltinType::Float:
720 case BuiltinType::Double:
721 case BuiltinType::LongDouble:
722 case BuiltinType::NullPtr:
723 case BuiltinType::Overload:
724 case BuiltinType::Dependent:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000725 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000726
727 case BuiltinType::UndeducedAuto: // FIXME: Deserves a cursor?
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000728 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000729
Ted Kremenekc4174cc2010-02-18 18:52:18 +0000730 case BuiltinType::ObjCId:
731 VisitType = Context.getObjCIdType();
732 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000733
734 case BuiltinType::ObjCClass:
735 VisitType = Context.getObjCClassType();
736 break;
737
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000738 case BuiltinType::ObjCSel:
739 VisitType = Context.getObjCSelType();
740 break;
741 }
742
743 if (!VisitType.isNull()) {
744 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000745 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000746 TU));
747 }
748
749 return false;
750}
751
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000752bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
753 return Visit(MakeCursorTypeRef(TL.getTypedefDecl(), TL.getNameLoc(), TU));
754}
755
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000756bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
757 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
758}
759
760bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
761 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
762}
763
764bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
765 if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
766 return true;
767
768 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
769 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
770 TU)))
771 return true;
772 }
773
774 return false;
775}
776
777bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
778 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseTypeLoc()))
779 return true;
780
781 if (TL.hasProtocolsAsWritten()) {
782 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000783 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I),
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000784 TL.getProtocolLoc(I),
785 TU)))
786 return true;
787 }
788 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000789
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000790 return false;
791}
792
793bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
794 return Visit(TL.getPointeeLoc());
795}
796
797bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
798 return Visit(TL.getPointeeLoc());
799}
800
801bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
802 return Visit(TL.getPointeeLoc());
803}
804
805bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000806 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000807}
808
809bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000810 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000811}
812
813bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
814 if (Visit(TL.getResultLoc()))
815 return true;
816
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000817 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
818 if (Visit(MakeCXCursor(TL.getArg(I), TU)))
819 return true;
820
821 return false;
822}
823
824bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
825 if (Visit(TL.getElementLoc()))
826 return true;
827
828 if (Expr *Size = TL.getSizeExpr())
829 return Visit(MakeCXCursor(Size, StmtParent, TU));
830
831 return false;
832}
833
Douglas Gregor2332c112010-01-21 20:48:56 +0000834bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
835 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
836}
837
838bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
839 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
840 return Visit(TSInfo->getTypeLoc());
841
842 return false;
843}
844
Douglas Gregora59e3902010-01-21 23:27:09 +0000845bool CursorVisitor::VisitStmt(Stmt *S) {
846 for (Stmt::child_iterator Child = S->child_begin(), ChildEnd = S->child_end();
847 Child != ChildEnd; ++Child) {
Daniel Dunbar54d67ca2010-01-25 00:40:30 +0000848 if (*Child && Visit(MakeCXCursor(*Child, StmtParent, TU)))
Douglas Gregora59e3902010-01-21 23:27:09 +0000849 return true;
850 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000851
Douglas Gregora59e3902010-01-21 23:27:09 +0000852 return false;
853}
854
855bool CursorVisitor::VisitDeclStmt(DeclStmt *S) {
856 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
857 D != DEnd; ++D) {
Douglas Gregor263b47b2010-01-25 16:12:32 +0000858 if (*D && Visit(MakeCXCursor(*D, TU)))
Douglas Gregora59e3902010-01-21 23:27:09 +0000859 return true;
860 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000861
Douglas Gregora59e3902010-01-21 23:27:09 +0000862 return false;
863}
864
Douglas Gregorf5bab412010-01-22 01:00:11 +0000865bool CursorVisitor::VisitIfStmt(IfStmt *S) {
866 if (VarDecl *Var = S->getConditionVariable()) {
867 if (Visit(MakeCXCursor(Var, TU)))
868 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000869 }
870
Douglas Gregor263b47b2010-01-25 16:12:32 +0000871 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
872 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +0000873 if (S->getThen() && Visit(MakeCXCursor(S->getThen(), StmtParent, TU)))
874 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +0000875 if (S->getElse() && Visit(MakeCXCursor(S->getElse(), StmtParent, TU)))
876 return true;
877
878 return false;
879}
880
881bool CursorVisitor::VisitSwitchStmt(SwitchStmt *S) {
882 if (VarDecl *Var = S->getConditionVariable()) {
883 if (Visit(MakeCXCursor(Var, TU)))
884 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000885 }
886
Douglas Gregor263b47b2010-01-25 16:12:32 +0000887 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
888 return true;
889 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
890 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000891
Douglas Gregor263b47b2010-01-25 16:12:32 +0000892 return false;
893}
894
895bool CursorVisitor::VisitWhileStmt(WhileStmt *S) {
896 if (VarDecl *Var = S->getConditionVariable()) {
897 if (Visit(MakeCXCursor(Var, TU)))
898 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000899 }
900
Douglas Gregor263b47b2010-01-25 16:12:32 +0000901 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
902 return true;
903 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
Douglas Gregorf5bab412010-01-22 01:00:11 +0000904 return true;
905
Douglas Gregor263b47b2010-01-25 16:12:32 +0000906 return false;
907}
908
909bool CursorVisitor::VisitForStmt(ForStmt *S) {
910 if (S->getInit() && Visit(MakeCXCursor(S->getInit(), StmtParent, TU)))
911 return true;
912 if (VarDecl *Var = S->getConditionVariable()) {
913 if (Visit(MakeCXCursor(Var, TU)))
914 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000915 }
916
Douglas Gregor263b47b2010-01-25 16:12:32 +0000917 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
918 return true;
919 if (S->getInc() && Visit(MakeCXCursor(S->getInc(), StmtParent, TU)))
920 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +0000921 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
922 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000923
Douglas Gregorf5bab412010-01-22 01:00:11 +0000924 return false;
925}
926
Douglas Gregor336fd812010-01-23 00:40:08 +0000927bool CursorVisitor::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E) {
928 if (E->isArgumentType()) {
929 if (TypeSourceInfo *TSInfo = E->getArgumentTypeInfo())
930 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000931
Douglas Gregor336fd812010-01-23 00:40:08 +0000932 return false;
933 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000934
Douglas Gregor336fd812010-01-23 00:40:08 +0000935 return VisitExpr(E);
936}
937
938bool CursorVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
939 if (TypeSourceInfo *TSInfo = E->getTypeInfoAsWritten())
940 if (Visit(TSInfo->getTypeLoc()))
941 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000942
Douglas Gregor336fd812010-01-23 00:40:08 +0000943 return VisitCastExpr(E);
944}
945
946bool CursorVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
947 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
948 if (Visit(TSInfo->getTypeLoc()))
949 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000950
Douglas Gregor336fd812010-01-23 00:40:08 +0000951 return VisitExpr(E);
952}
953
Douglas Gregorc2350e52010-03-08 16:40:19 +0000954bool CursorVisitor::VisitObjCMessageExpr(ObjCMessageExpr *E) {
955 ObjCMessageExpr::ClassInfo CI = E->getClassInfo();
956 if (CI.Decl && Visit(MakeCursorObjCClassRef(CI.Decl, CI.Loc, TU)))
957 return true;
958
959 return VisitExpr(E);
960}
961
Ted Kremenek09dfa372010-02-18 05:46:33 +0000962bool CursorVisitor::VisitAttributes(Decl *D) {
963 for (const Attr *A = D->getAttrs(); A; A = A->getNext())
964 if (Visit(MakeCXCursor(A, D, TU)))
965 return true;
966
967 return false;
968}
969
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000970extern "C" {
Douglas Gregor0a812cf2010-02-18 23:07:20 +0000971CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
972 int displayDiagnostics) {
Douglas Gregora030b7c2010-01-22 20:35:53 +0000973 CIndexer *CIdxr = new CIndexer();
Steve Naroffe56b4ba2009-10-20 14:46:24 +0000974 if (excludeDeclarationsFromPCH)
975 CIdxr->setOnlyLocalDecls();
Douglas Gregor0a812cf2010-02-18 23:07:20 +0000976 if (displayDiagnostics)
977 CIdxr->setDisplayDiagnostics();
Steve Naroffe56b4ba2009-10-20 14:46:24 +0000978 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +0000979}
980
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000981void clang_disposeIndex(CXIndex CIdx) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +0000982 if (CIdx)
983 delete static_cast<CIndexer *>(CIdx);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +0000984}
985
Daniel Dunbar8506dde2009-12-03 01:54:28 +0000986void clang_setUseExternalASTGeneration(CXIndex CIdx, int value) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +0000987 if (CIdx) {
988 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
989 CXXIdx->setUseExternalASTGeneration(value);
990 }
Daniel Dunbar8506dde2009-12-03 01:54:28 +0000991}
992
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000993CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
Douglas Gregora88084b2010-02-18 18:08:43 +0000994 const char *ast_filename) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +0000995 if (!CIdx)
996 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000997
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000998 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000999
Douglas Gregor5352ac02010-01-28 00:27:43 +00001000 // Configure the diagnostics.
1001 DiagnosticOptions DiagOpts;
1002 llvm::OwningPtr<Diagnostic> Diags;
1003 Diags.reset(CompilerInstance::createDiagnostics(DiagOpts, 0, 0));
Douglas Gregor5352ac02010-01-28 00:27:43 +00001004 return ASTUnit::LoadFromPCHFile(ast_filename, *Diags,
Douglas Gregora88084b2010-02-18 18:08:43 +00001005 CXXIdx->getOnlyLocalDecls(),
1006 0, 0, true);
Steve Naroff600866c2009-08-27 19:51:58 +00001007}
1008
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001009CXTranslationUnit
1010clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
1011 const char *source_filename,
1012 int num_command_line_args,
Douglas Gregor4db64a42010-01-23 00:14:00 +00001013 const char **command_line_args,
1014 unsigned num_unsaved_files,
Douglas Gregora88084b2010-02-18 18:08:43 +00001015 struct CXUnsavedFile *unsaved_files) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001016 if (!CIdx)
1017 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001018
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001019 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
1020
Douglas Gregor5352ac02010-01-28 00:27:43 +00001021 // Configure the diagnostics.
1022 DiagnosticOptions DiagOpts;
1023 llvm::OwningPtr<Diagnostic> Diags;
1024 Diags.reset(CompilerInstance::createDiagnostics(DiagOpts, 0, 0));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001025
Douglas Gregor4db64a42010-01-23 00:14:00 +00001026 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
1027 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001028 const llvm::MemoryBuffer *Buffer
Douglas Gregorc8dfe5e2010-02-27 01:32:48 +00001029 = llvm::MemoryBuffer::getMemBufferCopy(unsaved_files[I].Contents,
Douglas Gregor313e26c2010-02-18 23:35:40 +00001030 unsaved_files[I].Contents + unsaved_files[I].Length,
1031 unsaved_files[I].Filename);
Douglas Gregor4db64a42010-01-23 00:14:00 +00001032 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
1033 Buffer));
1034 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001035
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001036 if (!CXXIdx->getUseExternalASTGeneration()) {
1037 llvm::SmallVector<const char *, 16> Args;
1038
1039 // The 'source_filename' argument is optional. If the caller does not
1040 // specify it then it is assumed that the source file is specified
1041 // in the actual argument list.
1042 if (source_filename)
1043 Args.push_back(source_filename);
1044 Args.insert(Args.end(), command_line_args,
1045 command_line_args + num_command_line_args);
Douglas Gregor94dc8f62010-03-19 16:15:56 +00001046 Args.push_back("-Xclang");
1047 Args.push_back("-detailed-preprocessing-record");
Douglas Gregor5352ac02010-01-28 00:27:43 +00001048 unsigned NumErrors = Diags->getNumErrors();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001049
Ted Kremenek29b72842010-01-07 22:49:05 +00001050#ifdef USE_CRASHTRACER
1051 ArgsCrashTracerInfo ACTI(Args);
Ted Kremenek8a8da7d2010-01-06 03:42:32 +00001052#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001053
Daniel Dunbar94220972009-12-05 02:17:18 +00001054 llvm::OwningPtr<ASTUnit> Unit(
1055 ASTUnit::LoadFromCommandLine(Args.data(), Args.data() + Args.size(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001056 *Diags,
Daniel Dunbar869824e2009-12-13 03:46:13 +00001057 CXXIdx->getClangResourcesPath(),
Daniel Dunbar94220972009-12-05 02:17:18 +00001058 CXXIdx->getOnlyLocalDecls(),
Douglas Gregor4db64a42010-01-23 00:14:00 +00001059 RemappedFiles.data(),
Douglas Gregora88084b2010-02-18 18:08:43 +00001060 RemappedFiles.size(),
Douglas Gregor94dc8f62010-03-19 16:15:56 +00001061 /*CaptureDiagnostics=*/true));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001062
Daniel Dunbar94220972009-12-05 02:17:18 +00001063 // FIXME: Until we have broader testing, just drop the entire AST if we
1064 // encountered an error.
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001065 if (NumErrors != Diags->getNumErrors()) {
Ted Kremenek34f6a322010-03-05 22:43:29 +00001066 // Make sure to check that 'Unit' is non-NULL.
1067 if (CXXIdx->getDisplayDiagnostics() && Unit.get()) {
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001068 for (ASTUnit::diag_iterator D = Unit->diag_begin(),
1069 DEnd = Unit->diag_end();
1070 D != DEnd; ++D) {
1071 CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOptions());
Douglas Gregor274f1902010-02-22 23:17:23 +00001072 CXString Msg = clang_formatDiagnostic(&Diag,
1073 clang_defaultDiagnosticDisplayOptions());
1074 fprintf(stderr, "%s\n", clang_getCString(Msg));
1075 clang_disposeString(Msg);
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001076 }
Douglas Gregor274f1902010-02-22 23:17:23 +00001077#ifdef LLVM_ON_WIN32
1078 // On Windows, force a flush, since there may be multiple copies of
1079 // stderr and stdout in the file system, all with different buffers
1080 // but writing to the same device.
1081 fflush(stderr);
1082#endif
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001083 }
Daniel Dunbar94220972009-12-05 02:17:18 +00001084 return 0;
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001085 }
Daniel Dunbar94220972009-12-05 02:17:18 +00001086
1087 return Unit.take();
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001088 }
1089
Ted Kremenek139ba862009-10-22 00:03:57 +00001090 // Build up the arguments for invoking 'clang'.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001091 std::vector<const char *> argv;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001092
Ted Kremenek139ba862009-10-22 00:03:57 +00001093 // First add the complete path to the 'clang' executable.
1094 llvm::sys::Path ClangPath = static_cast<CIndexer *>(CIdx)->getClangPath();
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00001095 argv.push_back(ClangPath.c_str());
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001096
Ted Kremenek139ba862009-10-22 00:03:57 +00001097 // Add the '-emit-ast' option as our execution mode for 'clang'.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001098 argv.push_back("-emit-ast");
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001099
Ted Kremenek139ba862009-10-22 00:03:57 +00001100 // The 'source_filename' argument is optional. If the caller does not
1101 // specify it then it is assumed that the source file is specified
1102 // in the actual argument list.
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001103 if (source_filename)
1104 argv.push_back(source_filename);
Ted Kremenek139ba862009-10-22 00:03:57 +00001105
Steve Naroff37b5ac22009-10-15 20:50:09 +00001106 // Generate a temporary name for the AST file.
Ted Kremenek139ba862009-10-22 00:03:57 +00001107 argv.push_back("-o");
Benjamin Kramerc2a98162010-03-13 21:22:49 +00001108 char astTmpFile[L_tmpnam];
1109 argv.push_back(tmpnam(astTmpFile));
Ted Kremenek139ba862009-10-22 00:03:57 +00001110
Douglas Gregor4db64a42010-01-23 00:14:00 +00001111 // Remap any unsaved files to temporary files.
1112 std::vector<llvm::sys::Path> TemporaryFiles;
1113 std::vector<std::string> RemapArgs;
1114 if (RemapFiles(num_unsaved_files, unsaved_files, RemapArgs, TemporaryFiles))
1115 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001116
Douglas Gregor4db64a42010-01-23 00:14:00 +00001117 // The pointers into the elements of RemapArgs are stable because we
1118 // won't be adding anything to RemapArgs after this point.
1119 for (unsigned i = 0, e = RemapArgs.size(); i != e; ++i)
1120 argv.push_back(RemapArgs[i].c_str());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001121
Ted Kremenek139ba862009-10-22 00:03:57 +00001122 // Process the compiler options, stripping off '-o', '-c', '-fsyntax-only'.
1123 for (int i = 0; i < num_command_line_args; ++i)
1124 if (const char *arg = command_line_args[i]) {
1125 if (strcmp(arg, "-o") == 0) {
1126 ++i; // Also skip the matching argument.
1127 continue;
1128 }
1129 if (strcmp(arg, "-emit-ast") == 0 ||
1130 strcmp(arg, "-c") == 0 ||
1131 strcmp(arg, "-fsyntax-only") == 0) {
1132 continue;
1133 }
1134
1135 // Keep the argument.
1136 argv.push_back(arg);
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001137 }
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001138
Douglas Gregord93256e2010-01-28 06:00:51 +00001139 // Generate a temporary name for the diagnostics file.
Benjamin Kramerc2a98162010-03-13 21:22:49 +00001140 char tmpFileResults[L_tmpnam];
1141 char *tmpResultsFileName = tmpnam(tmpFileResults);
1142 llvm::sys::Path DiagnosticsFile(tmpResultsFileName);
Douglas Gregord93256e2010-01-28 06:00:51 +00001143 TemporaryFiles.push_back(DiagnosticsFile);
1144 argv.push_back("-fdiagnostics-binary");
1145
Douglas Gregor94dc8f62010-03-19 16:15:56 +00001146 argv.push_back("-Xclang");
1147 argv.push_back("-detailed-preprocessing-record");
1148
Ted Kremenek139ba862009-10-22 00:03:57 +00001149 // Add the null terminator.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001150 argv.push_back(NULL);
1151
Ted Kremenekfeb15e32009-10-26 22:14:08 +00001152 // Invoke 'clang'.
1153 llvm::sys::Path DevNull; // leave empty, causes redirection to /dev/null
1154 // on Unix or NUL (Windows).
Ted Kremenek379afec2009-10-22 03:24:01 +00001155 std::string ErrMsg;
Douglas Gregord93256e2010-01-28 06:00:51 +00001156 const llvm::sys::Path *Redirects[] = { &DevNull, &DevNull, &DiagnosticsFile,
1157 NULL };
Ted Kremenek379afec2009-10-22 03:24:01 +00001158 llvm::sys::Program::ExecuteAndWait(ClangPath, &argv[0], /* env */ NULL,
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001159 /* redirects */ &Redirects[0],
Ted Kremenek379afec2009-10-22 03:24:01 +00001160 /* secondsToWait */ 0, /* memoryLimits */ 0, &ErrMsg);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001161
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001162 if (!ErrMsg.empty()) {
1163 std::string AllArgs;
Ted Kremenek379afec2009-10-22 03:24:01 +00001164 for (std::vector<const char*>::iterator I = argv.begin(), E = argv.end();
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001165 I != E; ++I) {
1166 AllArgs += ' ';
Ted Kremenek779e5f42009-10-26 22:08:39 +00001167 if (*I)
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001168 AllArgs += *I;
Ted Kremenek779e5f42009-10-26 22:08:39 +00001169 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001170
Daniel Dunbar32141c82010-02-23 20:23:45 +00001171 Diags->Report(diag::err_fe_invoking) << AllArgs << ErrMsg;
Ted Kremenek379afec2009-10-22 03:24:01 +00001172 }
Benjamin Kramer0829a832009-10-18 11:19:36 +00001173
Benjamin Kramerc2a98162010-03-13 21:22:49 +00001174 ASTUnit *ATU = ASTUnit::LoadFromPCHFile(astTmpFile, *Diags,
Douglas Gregor4db64a42010-01-23 00:14:00 +00001175 CXXIdx->getOnlyLocalDecls(),
Douglas Gregor4db64a42010-01-23 00:14:00 +00001176 RemappedFiles.data(),
Douglas Gregora88084b2010-02-18 18:08:43 +00001177 RemappedFiles.size(),
1178 /*CaptureDiagnostics=*/true);
Douglas Gregora88084b2010-02-18 18:08:43 +00001179 if (ATU) {
1180 LoadSerializedDiagnostics(DiagnosticsFile,
1181 num_unsaved_files, unsaved_files,
1182 ATU->getFileManager(),
1183 ATU->getSourceManager(),
1184 ATU->getDiagnostics());
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001185 } else if (CXXIdx->getDisplayDiagnostics()) {
1186 // We failed to load the ASTUnit, but we can still deserialize the
1187 // diagnostics and emit them.
1188 FileManager FileMgr;
Douglas Gregorf715ca12010-03-16 00:06:06 +00001189 Diagnostic Diag;
1190 SourceManager SourceMgr(Diag);
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001191 // FIXME: Faked LangOpts!
1192 LangOptions LangOpts;
1193 llvm::SmallVector<StoredDiagnostic, 4> Diags;
1194 LoadSerializedDiagnostics(DiagnosticsFile,
1195 num_unsaved_files, unsaved_files,
1196 FileMgr, SourceMgr, Diags);
1197 for (llvm::SmallVector<StoredDiagnostic, 4>::iterator D = Diags.begin(),
1198 DEnd = Diags.end();
1199 D != DEnd; ++D) {
1200 CXStoredDiagnostic Diag(*D, LangOpts);
Douglas Gregor274f1902010-02-22 23:17:23 +00001201 CXString Msg = clang_formatDiagnostic(&Diag,
1202 clang_defaultDiagnosticDisplayOptions());
1203 fprintf(stderr, "%s\n", clang_getCString(Msg));
1204 clang_disposeString(Msg);
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001205 }
Douglas Gregor274f1902010-02-22 23:17:23 +00001206
1207#ifdef LLVM_ON_WIN32
1208 // On Windows, force a flush, since there may be multiple copies of
1209 // stderr and stdout in the file system, all with different buffers
1210 // but writing to the same device.
1211 fflush(stderr);
1212#endif
Douglas Gregora88084b2010-02-18 18:08:43 +00001213 }
Douglas Gregord93256e2010-01-28 06:00:51 +00001214
Douglas Gregor313e26c2010-02-18 23:35:40 +00001215 if (ATU) {
1216 // Make the translation unit responsible for destroying all temporary files.
1217 for (unsigned i = 0, e = TemporaryFiles.size(); i != e; ++i)
1218 ATU->addTemporaryFile(TemporaryFiles[i]);
1219 ATU->addTemporaryFile(llvm::sys::Path(ATU->getPCHFileName()));
1220 } else {
1221 // Destroy all of the temporary files now; they can't be referenced any
1222 // longer.
1223 llvm::sys::Path(astTmpFile).eraseFromDisk();
1224 for (unsigned i = 0, e = TemporaryFiles.size(); i != e; ++i)
1225 TemporaryFiles[i].eraseFromDisk();
1226 }
1227
Steve Naroffe19944c2009-10-15 22:23:48 +00001228 return ATU;
Steve Naroff5b7d8e22009-10-15 20:04:39 +00001229}
1230
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001231void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001232 if (CTUnit)
1233 delete static_cast<ASTUnit *>(CTUnit);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00001234}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001235
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001236CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001237 if (!CTUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001238 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001239
Steve Naroff77accc12009-09-03 18:19:54 +00001240 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001241 return createCXString(CXXUnit->getOriginalSourceFileName(), true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +00001242}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +00001243
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001244CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001245 CXCursor Result = { CXCursor_TranslationUnit, { 0, 0, TU } };
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001246 return Result;
1247}
1248
Ted Kremenekfb480492010-01-13 21:46:36 +00001249} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +00001250
Ted Kremenekfb480492010-01-13 21:46:36 +00001251//===----------------------------------------------------------------------===//
Douglas Gregor1db19de2010-01-19 21:36:55 +00001252// CXSourceLocation and CXSourceRange Operations.
1253//===----------------------------------------------------------------------===//
1254
Douglas Gregorb9790342010-01-22 21:44:22 +00001255extern "C" {
1256CXSourceLocation clang_getNullLocation() {
Douglas Gregor5352ac02010-01-28 00:27:43 +00001257 CXSourceLocation Result = { { 0, 0 }, 0 };
Douglas Gregorb9790342010-01-22 21:44:22 +00001258 return Result;
1259}
1260
1261unsigned clang_equalLocations(CXSourceLocation loc1, CXSourceLocation loc2) {
Daniel Dunbar90a6b9e2010-01-30 23:58:27 +00001262 return (loc1.ptr_data[0] == loc2.ptr_data[0] &&
1263 loc1.ptr_data[1] == loc2.ptr_data[1] &&
1264 loc1.int_data == loc2.int_data);
Douglas Gregorb9790342010-01-22 21:44:22 +00001265}
1266
1267CXSourceLocation clang_getLocation(CXTranslationUnit tu,
1268 CXFile file,
1269 unsigned line,
1270 unsigned column) {
1271 if (!tu)
1272 return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001273
Douglas Gregorb9790342010-01-22 21:44:22 +00001274 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
1275 SourceLocation SLoc
1276 = CXXUnit->getSourceManager().getLocation(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001277 static_cast<const FileEntry *>(file),
Douglas Gregorb9790342010-01-22 21:44:22 +00001278 line, column);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001279
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00001280 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
Douglas Gregorb9790342010-01-22 21:44:22 +00001281}
1282
Douglas Gregor5352ac02010-01-28 00:27:43 +00001283CXSourceRange clang_getNullRange() {
1284 CXSourceRange Result = { { 0, 0 }, 0, 0 };
1285 return Result;
1286}
Daniel Dunbard52864b2010-02-14 10:02:57 +00001287
Douglas Gregor5352ac02010-01-28 00:27:43 +00001288CXSourceRange clang_getRange(CXSourceLocation begin, CXSourceLocation end) {
1289 if (begin.ptr_data[0] != end.ptr_data[0] ||
1290 begin.ptr_data[1] != end.ptr_data[1])
1291 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001292
1293 CXSourceRange Result = { { begin.ptr_data[0], begin.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00001294 begin.int_data, end.int_data };
Douglas Gregorb9790342010-01-22 21:44:22 +00001295 return Result;
1296}
1297
Douglas Gregor46766dc2010-01-26 19:19:08 +00001298void clang_getInstantiationLocation(CXSourceLocation location,
1299 CXFile *file,
1300 unsigned *line,
1301 unsigned *column,
1302 unsigned *offset) {
Douglas Gregor1db19de2010-01-19 21:36:55 +00001303 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
1304
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00001305 if (!location.ptr_data[0] || Loc.isInvalid()) {
Douglas Gregor46766dc2010-01-26 19:19:08 +00001306 if (file)
1307 *file = 0;
1308 if (line)
1309 *line = 0;
1310 if (column)
1311 *column = 0;
1312 if (offset)
1313 *offset = 0;
1314 return;
1315 }
1316
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00001317 const SourceManager &SM =
1318 *static_cast<const SourceManager*>(location.ptr_data[0]);
Douglas Gregor1db19de2010-01-19 21:36:55 +00001319 SourceLocation InstLoc = SM.getInstantiationLoc(Loc);
Douglas Gregor1db19de2010-01-19 21:36:55 +00001320
1321 if (file)
1322 *file = (void *)SM.getFileEntryForID(SM.getFileID(InstLoc));
1323 if (line)
1324 *line = SM.getInstantiationLineNumber(InstLoc);
1325 if (column)
1326 *column = SM.getInstantiationColumnNumber(InstLoc);
Douglas Gregore69517c2010-01-26 03:07:15 +00001327 if (offset)
Douglas Gregor46766dc2010-01-26 19:19:08 +00001328 *offset = SM.getDecomposedLoc(InstLoc).second;
Douglas Gregore69517c2010-01-26 03:07:15 +00001329}
1330
Douglas Gregor1db19de2010-01-19 21:36:55 +00001331CXSourceLocation clang_getRangeStart(CXSourceRange range) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001332 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00001333 range.begin_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00001334 return Result;
1335}
1336
1337CXSourceLocation clang_getRangeEnd(CXSourceRange range) {
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00001338 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00001339 range.end_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00001340 return Result;
1341}
1342
Douglas Gregorb9790342010-01-22 21:44:22 +00001343} // end: extern "C"
1344
Douglas Gregor1db19de2010-01-19 21:36:55 +00001345//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00001346// CXFile Operations.
1347//===----------------------------------------------------------------------===//
1348
1349extern "C" {
Ted Kremenek74844072010-02-17 00:41:20 +00001350CXString clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00001351 if (!SFile)
Ted Kremenek74844072010-02-17 00:41:20 +00001352 return createCXString(NULL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001353
Steve Naroff88145032009-10-27 14:35:18 +00001354 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Ted Kremenek74844072010-02-17 00:41:20 +00001355 return createCXString(FEnt->getName());
Steve Naroff88145032009-10-27 14:35:18 +00001356}
1357
1358time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00001359 if (!SFile)
1360 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001361
Steve Naroff88145032009-10-27 14:35:18 +00001362 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
1363 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +00001364}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001365
Douglas Gregorb9790342010-01-22 21:44:22 +00001366CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
1367 if (!tu)
1368 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001369
Douglas Gregorb9790342010-01-22 21:44:22 +00001370 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001371
Douglas Gregorb9790342010-01-22 21:44:22 +00001372 FileManager &FMgr = CXXUnit->getFileManager();
1373 const FileEntry *File = FMgr.getFile(file_name, file_name+strlen(file_name));
1374 return const_cast<FileEntry *>(File);
1375}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001376
Ted Kremenekfb480492010-01-13 21:46:36 +00001377} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +00001378
Ted Kremenekfb480492010-01-13 21:46:36 +00001379//===----------------------------------------------------------------------===//
1380// CXCursor Operations.
1381//===----------------------------------------------------------------------===//
1382
Ted Kremenekfb480492010-01-13 21:46:36 +00001383static Decl *getDeclFromExpr(Stmt *E) {
1384 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
1385 return RefExpr->getDecl();
1386 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
1387 return ME->getMemberDecl();
1388 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
1389 return RE->getDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001390
Ted Kremenekfb480492010-01-13 21:46:36 +00001391 if (CallExpr *CE = dyn_cast<CallExpr>(E))
1392 return getDeclFromExpr(CE->getCallee());
1393 if (CastExpr *CE = dyn_cast<CastExpr>(E))
1394 return getDeclFromExpr(CE->getSubExpr());
1395 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
1396 return OME->getMethodDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001397
Ted Kremenekfb480492010-01-13 21:46:36 +00001398 return 0;
1399}
1400
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00001401static SourceLocation getLocationFromExpr(Expr *E) {
1402 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
1403 return /*FIXME:*/Msg->getLeftLoc();
1404 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
1405 return DRE->getLocation();
1406 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
1407 return Member->getMemberLoc();
1408 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
1409 return Ivar->getLocation();
1410 return E->getLocStart();
1411}
1412
Ted Kremenekfb480492010-01-13 21:46:36 +00001413extern "C" {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001414
1415unsigned clang_visitChildren(CXCursor parent,
Douglas Gregorb1373d02010-01-20 20:59:29 +00001416 CXCursorVisitor visitor,
1417 CXClientData client_data) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001418 ASTUnit *CXXUnit = getCursorASTUnit(parent);
Douglas Gregorb1373d02010-01-20 20:59:29 +00001419
1420 unsigned PCHLevel = Decl::MaxPCHLevel;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001421
Douglas Gregorb1373d02010-01-20 20:59:29 +00001422 // Set the PCHLevel to filter out unwanted decls if requested.
1423 if (CXXUnit->getOnlyLocalDecls()) {
1424 PCHLevel = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001425
Douglas Gregorb1373d02010-01-20 20:59:29 +00001426 // If the main input was an AST, bump the level.
1427 if (CXXUnit->isMainFileAST())
1428 ++PCHLevel;
1429 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001430
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001431 CursorVisitor CursorVis(CXXUnit, visitor, client_data, PCHLevel);
Douglas Gregorb1373d02010-01-20 20:59:29 +00001432 return CursorVis.VisitChildren(parent);
1433}
1434
Douglas Gregor78205d42010-01-20 21:45:58 +00001435static CXString getDeclSpelling(Decl *D) {
1436 NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
1437 if (!ND)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001438 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001439
Douglas Gregor78205d42010-01-20 21:45:58 +00001440 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001441 return createCXString(OMD->getSelector().getAsString());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001442
Douglas Gregor78205d42010-01-20 21:45:58 +00001443 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
1444 // No, this isn't the same as the code below. getIdentifier() is non-virtual
1445 // and returns different names. NamedDecl returns the class name and
1446 // ObjCCategoryImplDecl returns the category name.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001447 return createCXString(CIMP->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001448
Douglas Gregor78205d42010-01-20 21:45:58 +00001449 if (ND->getIdentifier())
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001450 return createCXString(ND->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001451
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001452 return createCXString("");
Douglas Gregor78205d42010-01-20 21:45:58 +00001453}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001454
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001455CXString clang_getCursorSpelling(CXCursor C) {
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001456 if (clang_isTranslationUnit(C.kind))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001457 return clang_getTranslationUnitSpelling(C.data[2]);
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001458
Steve Narofff334b4e2009-09-02 18:26:48 +00001459 if (clang_isReference(C.kind)) {
1460 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00001461 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +00001462 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001463 return createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00001464 }
1465 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +00001466 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001467 return createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00001468 }
1469 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +00001470 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +00001471 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001472 return createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00001473 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001474 case CXCursor_TypeRef: {
1475 TypeDecl *Type = getCursorTypeRef(C).first;
1476 assert(Type && "Missing type decl");
1477
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001478 return createCXString(getCursorContext(C).getTypeDeclType(Type).
1479 getAsString());
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001480 }
1481
Daniel Dunbaracca7252009-11-30 20:42:49 +00001482 default:
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001483 return createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +00001484 }
1485 }
Douglas Gregor97b98722010-01-19 23:20:36 +00001486
1487 if (clang_isExpression(C.kind)) {
1488 Decl *D = getDeclFromExpr(getCursorExpr(C));
1489 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +00001490 return getDeclSpelling(D);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001491 return createCXString("");
Douglas Gregor97b98722010-01-19 23:20:36 +00001492 }
1493
Douglas Gregor4ae8f292010-03-18 17:52:52 +00001494 if (C.kind == CXCursor_MacroInstantiation)
1495 return createCXString(getCursorMacroInstantiation(C)->getName()
1496 ->getNameStart());
1497
Douglas Gregor572feb22010-03-18 18:04:21 +00001498 if (C.kind == CXCursor_MacroDefinition)
1499 return createCXString(getCursorMacroDefinition(C)->getName()
1500 ->getNameStart());
1501
Douglas Gregor60cbfac2010-01-25 16:56:17 +00001502 if (clang_isDeclaration(C.kind))
1503 return getDeclSpelling(getCursorDecl(C));
Ted Kremeneke68fff62010-02-17 00:41:32 +00001504
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001505 return createCXString("");
Steve Narofff334b4e2009-09-02 18:26:48 +00001506}
1507
Ted Kremeneke68fff62010-02-17 00:41:32 +00001508CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00001509 switch (Kind) {
Ted Kremeneke68fff62010-02-17 00:41:32 +00001510 case CXCursor_FunctionDecl:
1511 return createCXString("FunctionDecl");
1512 case CXCursor_TypedefDecl:
1513 return createCXString("TypedefDecl");
1514 case CXCursor_EnumDecl:
1515 return createCXString("EnumDecl");
1516 case CXCursor_EnumConstantDecl:
1517 return createCXString("EnumConstantDecl");
1518 case CXCursor_StructDecl:
1519 return createCXString("StructDecl");
1520 case CXCursor_UnionDecl:
1521 return createCXString("UnionDecl");
1522 case CXCursor_ClassDecl:
1523 return createCXString("ClassDecl");
1524 case CXCursor_FieldDecl:
1525 return createCXString("FieldDecl");
1526 case CXCursor_VarDecl:
1527 return createCXString("VarDecl");
1528 case CXCursor_ParmDecl:
1529 return createCXString("ParmDecl");
1530 case CXCursor_ObjCInterfaceDecl:
1531 return createCXString("ObjCInterfaceDecl");
1532 case CXCursor_ObjCCategoryDecl:
1533 return createCXString("ObjCCategoryDecl");
1534 case CXCursor_ObjCProtocolDecl:
1535 return createCXString("ObjCProtocolDecl");
1536 case CXCursor_ObjCPropertyDecl:
1537 return createCXString("ObjCPropertyDecl");
1538 case CXCursor_ObjCIvarDecl:
1539 return createCXString("ObjCIvarDecl");
1540 case CXCursor_ObjCInstanceMethodDecl:
1541 return createCXString("ObjCInstanceMethodDecl");
1542 case CXCursor_ObjCClassMethodDecl:
1543 return createCXString("ObjCClassMethodDecl");
1544 case CXCursor_ObjCImplementationDecl:
1545 return createCXString("ObjCImplementationDecl");
1546 case CXCursor_ObjCCategoryImplDecl:
1547 return createCXString("ObjCCategoryImplDecl");
1548 case CXCursor_UnexposedDecl:
1549 return createCXString("UnexposedDecl");
1550 case CXCursor_ObjCSuperClassRef:
1551 return createCXString("ObjCSuperClassRef");
1552 case CXCursor_ObjCProtocolRef:
1553 return createCXString("ObjCProtocolRef");
1554 case CXCursor_ObjCClassRef:
1555 return createCXString("ObjCClassRef");
1556 case CXCursor_TypeRef:
1557 return createCXString("TypeRef");
1558 case CXCursor_UnexposedExpr:
1559 return createCXString("UnexposedExpr");
1560 case CXCursor_DeclRefExpr:
1561 return createCXString("DeclRefExpr");
1562 case CXCursor_MemberRefExpr:
1563 return createCXString("MemberRefExpr");
1564 case CXCursor_CallExpr:
1565 return createCXString("CallExpr");
1566 case CXCursor_ObjCMessageExpr:
1567 return createCXString("ObjCMessageExpr");
1568 case CXCursor_UnexposedStmt:
1569 return createCXString("UnexposedStmt");
1570 case CXCursor_InvalidFile:
1571 return createCXString("InvalidFile");
Ted Kremenek292db642010-03-19 20:39:05 +00001572 case CXCursor_InvalidCode:
1573 return createCXString("InvalidCode");
Ted Kremeneke68fff62010-02-17 00:41:32 +00001574 case CXCursor_NoDeclFound:
1575 return createCXString("NoDeclFound");
1576 case CXCursor_NotImplemented:
1577 return createCXString("NotImplemented");
1578 case CXCursor_TranslationUnit:
1579 return createCXString("TranslationUnit");
Ted Kremeneke77f4432010-02-18 03:09:07 +00001580 case CXCursor_UnexposedAttr:
1581 return createCXString("UnexposedAttr");
1582 case CXCursor_IBActionAttr:
1583 return createCXString("attribute(ibaction)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00001584 case CXCursor_IBOutletAttr:
1585 return createCXString("attribute(iboutlet)");
1586 case CXCursor_PreprocessingDirective:
1587 return createCXString("preprocessing directive");
Douglas Gregor572feb22010-03-18 18:04:21 +00001588 case CXCursor_MacroDefinition:
1589 return createCXString("macro definition");
Douglas Gregor48072312010-03-18 15:23:44 +00001590 case CXCursor_MacroInstantiation:
1591 return createCXString("macro instantiation");
Steve Naroff89922f82009-08-31 00:59:03 +00001592 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00001593
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00001594 llvm_unreachable("Unhandled CXCursorKind");
Ted Kremeneke68fff62010-02-17 00:41:32 +00001595 return createCXString(NULL);
Steve Naroff600866c2009-08-27 19:51:58 +00001596}
Steve Naroff89922f82009-08-31 00:59:03 +00001597
Ted Kremeneke68fff62010-02-17 00:41:32 +00001598enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
1599 CXCursor parent,
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001600 CXClientData client_data) {
1601 CXCursor *BestCursor = static_cast<CXCursor *>(client_data);
1602 *BestCursor = cursor;
1603 return CXChildVisit_Recurse;
1604}
Ted Kremeneke68fff62010-02-17 00:41:32 +00001605
Douglas Gregorb9790342010-01-22 21:44:22 +00001606CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
1607 if (!TU)
Ted Kremenekf4629892010-01-14 01:51:23 +00001608 return clang_getNullCursor();
Ted Kremeneke68fff62010-02-17 00:41:32 +00001609
Douglas Gregorb9790342010-01-22 21:44:22 +00001610 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
1611
Douglas Gregorbdf60622010-03-05 21:16:25 +00001612 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
1613
Ted Kremeneka297de22010-01-25 22:34:44 +00001614 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001615 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
1616 if (SLoc.isValid()) {
Daniel Dunbard52864b2010-02-14 10:02:57 +00001617 SourceRange RegionOfInterest(SLoc, SLoc.getFileLocWithOffset(1));
Ted Kremeneke68fff62010-02-17 00:41:32 +00001618
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001619 // FIXME: Would be great to have a "hint" cursor, then walk from that
1620 // hint cursor upward until we find a cursor whose source range encloses
1621 // the region of interest, rather than starting from the translation unit.
1622 CXCursor Parent = clang_getTranslationUnitCursor(CXXUnit);
Ted Kremeneke68fff62010-02-17 00:41:32 +00001623 CursorVisitor CursorVis(CXXUnit, GetCursorVisitor, &Result,
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001624 Decl::MaxPCHLevel, RegionOfInterest);
1625 CursorVis.VisitChildren(Parent);
Steve Naroff77128dd2009-09-15 20:25:34 +00001626 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00001627 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00001628}
1629
Ted Kremenek73885552009-11-17 19:28:59 +00001630CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00001631 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00001632}
1633
1634unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00001635 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00001636}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001637
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001638unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00001639 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
1640}
1641
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001642unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +00001643 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
1644}
Steve Naroff2d4d6292009-08-31 14:26:51 +00001645
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001646unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00001647 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
1648}
1649
Douglas Gregor97b98722010-01-19 23:20:36 +00001650unsigned clang_isExpression(enum CXCursorKind K) {
1651 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
1652}
1653
1654unsigned clang_isStatement(enum CXCursorKind K) {
1655 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
1656}
1657
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001658unsigned clang_isTranslationUnit(enum CXCursorKind K) {
1659 return K == CXCursor_TranslationUnit;
1660}
1661
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00001662unsigned clang_isPreprocessing(enum CXCursorKind K) {
1663 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
1664}
1665
Ted Kremenekad6eff62010-03-08 21:17:29 +00001666unsigned clang_isUnexposed(enum CXCursorKind K) {
1667 switch (K) {
1668 case CXCursor_UnexposedDecl:
1669 case CXCursor_UnexposedExpr:
1670 case CXCursor_UnexposedStmt:
1671 case CXCursor_UnexposedAttr:
1672 return true;
1673 default:
1674 return false;
1675 }
1676}
1677
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001678CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00001679 return C.kind;
1680}
1681
Douglas Gregor98258af2010-01-18 22:46:11 +00001682CXSourceLocation clang_getCursorLocation(CXCursor C) {
1683 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00001684 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001685 case CXCursor_ObjCSuperClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00001686 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1687 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001688 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001689 }
1690
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001691 case CXCursor_ObjCProtocolRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00001692 std::pair<ObjCProtocolDecl *, SourceLocation> P
1693 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001694 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001695 }
1696
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001697 case CXCursor_ObjCClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00001698 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1699 = getCursorObjCClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001700 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001701 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001702
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001703 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001704 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001705 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001706 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001707
Douglas Gregorf46034a2010-01-18 23:41:10 +00001708 default:
1709 // FIXME: Need a way to enumerate all non-reference cases.
1710 llvm_unreachable("Missed a reference kind");
1711 }
Douglas Gregor98258af2010-01-18 22:46:11 +00001712 }
Douglas Gregor97b98722010-01-19 23:20:36 +00001713
1714 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001715 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00001716 getLocationFromExpr(getCursorExpr(C)));
1717
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00001718 if (C.kind == CXCursor_PreprocessingDirective) {
1719 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
1720 return cxloc::translateSourceLocation(getCursorContext(C), L);
1721 }
Douglas Gregor48072312010-03-18 15:23:44 +00001722
1723 if (C.kind == CXCursor_MacroInstantiation) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00001724 SourceLocation L
1725 = cxcursor::getCursorMacroInstantiation(C)->getSourceRange().getBegin();
Douglas Gregor48072312010-03-18 15:23:44 +00001726 return cxloc::translateSourceLocation(getCursorContext(C), L);
1727 }
Douglas Gregor572feb22010-03-18 18:04:21 +00001728
1729 if (C.kind == CXCursor_MacroDefinition) {
1730 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
1731 return cxloc::translateSourceLocation(getCursorContext(C), L);
1732 }
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00001733
Douglas Gregor5352ac02010-01-28 00:27:43 +00001734 if (!getCursorDecl(C))
1735 return clang_getNullLocation();
Douglas Gregor98258af2010-01-18 22:46:11 +00001736
Douglas Gregorf46034a2010-01-18 23:41:10 +00001737 Decl *D = getCursorDecl(C);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001738 SourceLocation Loc = D->getLocation();
1739 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
1740 Loc = Class->getClassLoc();
Ted Kremeneka297de22010-01-25 22:34:44 +00001741 return cxloc::translateSourceLocation(D->getASTContext(), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00001742}
Douglas Gregora7bde202010-01-19 00:34:46 +00001743
1744CXSourceRange clang_getCursorExtent(CXCursor C) {
1745 if (clang_isReference(C.kind)) {
1746 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001747 case CXCursor_ObjCSuperClassRef: {
Douglas Gregora7bde202010-01-19 00:34:46 +00001748 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1749 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001750 return cxloc::translateSourceRange(P.first->getASTContext(), P.second);
Douglas Gregora7bde202010-01-19 00:34:46 +00001751 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001752
1753 case CXCursor_ObjCProtocolRef: {
Douglas Gregora7bde202010-01-19 00:34:46 +00001754 std::pair<ObjCProtocolDecl *, SourceLocation> P
1755 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001756 return cxloc::translateSourceRange(P.first->getASTContext(), P.second);
Douglas Gregora7bde202010-01-19 00:34:46 +00001757 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001758
1759 case CXCursor_ObjCClassRef: {
Douglas Gregora7bde202010-01-19 00:34:46 +00001760 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1761 = getCursorObjCClassRef(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001762
Ted Kremeneka297de22010-01-25 22:34:44 +00001763 return cxloc::translateSourceRange(P.first->getASTContext(), P.second);
Douglas Gregora7bde202010-01-19 00:34:46 +00001764 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001765
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001766 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001767 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001768 return cxloc::translateSourceRange(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001769 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001770
Douglas Gregora7bde202010-01-19 00:34:46 +00001771 default:
1772 // FIXME: Need a way to enumerate all non-reference cases.
1773 llvm_unreachable("Missed a reference kind");
1774 }
1775 }
Douglas Gregor97b98722010-01-19 23:20:36 +00001776
1777 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001778 return cxloc::translateSourceRange(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00001779 getCursorExpr(C)->getSourceRange());
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001780
1781 if (clang_isStatement(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001782 return cxloc::translateSourceRange(getCursorContext(C),
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001783 getCursorStmt(C)->getSourceRange());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001784
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00001785 if (C.kind == CXCursor_PreprocessingDirective) {
1786 SourceRange R = cxcursor::getCursorPreprocessingDirective(C);
1787 return cxloc::translateSourceRange(getCursorContext(C), R);
1788 }
Douglas Gregor48072312010-03-18 15:23:44 +00001789
1790 if (C.kind == CXCursor_MacroInstantiation) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00001791 SourceRange R = cxcursor::getCursorMacroInstantiation(C)->getSourceRange();
Douglas Gregor48072312010-03-18 15:23:44 +00001792 return cxloc::translateSourceRange(getCursorContext(C), R);
1793 }
Douglas Gregor572feb22010-03-18 18:04:21 +00001794
1795 if (C.kind == CXCursor_MacroDefinition) {
1796 SourceRange R = cxcursor::getCursorMacroDefinition(C)->getSourceRange();
1797 return cxloc::translateSourceRange(getCursorContext(C), R);
1798 }
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00001799
Douglas Gregor5352ac02010-01-28 00:27:43 +00001800 if (!getCursorDecl(C))
1801 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001802
Douglas Gregora7bde202010-01-19 00:34:46 +00001803 Decl *D = getCursorDecl(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001804 return cxloc::translateSourceRange(D->getASTContext(), D->getSourceRange());
Douglas Gregora7bde202010-01-19 00:34:46 +00001805}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001806
1807CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001808 if (clang_isInvalid(C.kind))
1809 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001810
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001811 ASTUnit *CXXUnit = getCursorASTUnit(C);
Douglas Gregorb6998662010-01-19 19:34:47 +00001812 if (clang_isDeclaration(C.kind))
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001813 return C;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001814
Douglas Gregor97b98722010-01-19 23:20:36 +00001815 if (clang_isExpression(C.kind)) {
1816 Decl *D = getDeclFromExpr(getCursorExpr(C));
1817 if (D)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001818 return MakeCXCursor(D, CXXUnit);
Douglas Gregor97b98722010-01-19 23:20:36 +00001819 return clang_getNullCursor();
1820 }
1821
Douglas Gregorbf7efa22010-03-18 18:23:03 +00001822 if (C.kind == CXCursor_MacroInstantiation) {
1823 if (MacroDefinition *Def = getCursorMacroInstantiation(C)->getDefinition())
1824 return MakeMacroDefinitionCursor(Def, CXXUnit);
1825 }
1826
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001827 if (!clang_isReference(C.kind))
1828 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001829
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001830 switch (C.kind) {
1831 case CXCursor_ObjCSuperClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001832 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001833
1834 case CXCursor_ObjCProtocolRef: {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001835 return MakeCXCursor(getCursorObjCProtocolRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001836
1837 case CXCursor_ObjCClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001838 return MakeCXCursor(getCursorObjCClassRef(C).first, CXXUnit);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001839
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001840 case CXCursor_TypeRef:
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001841 return MakeCXCursor(getCursorTypeRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001842
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001843 default:
1844 // We would prefer to enumerate all non-reference cursor kinds here.
1845 llvm_unreachable("Unhandled reference cursor kind");
1846 break;
1847 }
1848 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001849
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001850 return clang_getNullCursor();
1851}
1852
Douglas Gregorb6998662010-01-19 19:34:47 +00001853CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001854 if (clang_isInvalid(C.kind))
1855 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001856
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001857 ASTUnit *CXXUnit = getCursorASTUnit(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001858
Douglas Gregorb6998662010-01-19 19:34:47 +00001859 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00001860 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00001861 C = clang_getCursorReferenced(C);
1862 WasReference = true;
1863 }
1864
Douglas Gregorbf7efa22010-03-18 18:23:03 +00001865 if (C.kind == CXCursor_MacroInstantiation)
1866 return clang_getCursorReferenced(C);
1867
Douglas Gregorb6998662010-01-19 19:34:47 +00001868 if (!clang_isDeclaration(C.kind))
1869 return clang_getNullCursor();
1870
1871 Decl *D = getCursorDecl(C);
1872 if (!D)
1873 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001874
Douglas Gregorb6998662010-01-19 19:34:47 +00001875 switch (D->getKind()) {
1876 // Declaration kinds that don't really separate the notions of
1877 // declaration and definition.
1878 case Decl::Namespace:
1879 case Decl::Typedef:
1880 case Decl::TemplateTypeParm:
1881 case Decl::EnumConstant:
1882 case Decl::Field:
1883 case Decl::ObjCIvar:
1884 case Decl::ObjCAtDefsField:
1885 case Decl::ImplicitParam:
1886 case Decl::ParmVar:
1887 case Decl::NonTypeTemplateParm:
1888 case Decl::TemplateTemplateParm:
1889 case Decl::ObjCCategoryImpl:
1890 case Decl::ObjCImplementation:
1891 case Decl::LinkageSpec:
1892 case Decl::ObjCPropertyImpl:
1893 case Decl::FileScopeAsm:
1894 case Decl::StaticAssert:
1895 case Decl::Block:
1896 return C;
1897
1898 // Declaration kinds that don't make any sense here, but are
1899 // nonetheless harmless.
1900 case Decl::TranslationUnit:
1901 case Decl::Template:
1902 case Decl::ObjCContainer:
1903 break;
1904
1905 // Declaration kinds for which the definition is not resolvable.
1906 case Decl::UnresolvedUsingTypename:
1907 case Decl::UnresolvedUsingValue:
1908 break;
1909
1910 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001911 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
1912 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001913
1914 case Decl::NamespaceAlias:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001915 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001916
1917 case Decl::Enum:
1918 case Decl::Record:
1919 case Decl::CXXRecord:
1920 case Decl::ClassTemplateSpecialization:
1921 case Decl::ClassTemplatePartialSpecialization:
Douglas Gregor952b0172010-02-11 01:04:33 +00001922 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001923 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001924 return clang_getNullCursor();
1925
1926 case Decl::Function:
1927 case Decl::CXXMethod:
1928 case Decl::CXXConstructor:
1929 case Decl::CXXDestructor:
1930 case Decl::CXXConversion: {
1931 const FunctionDecl *Def = 0;
1932 if (cast<FunctionDecl>(D)->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001933 return MakeCXCursor(const_cast<FunctionDecl *>(Def), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001934 return clang_getNullCursor();
1935 }
1936
1937 case Decl::Var: {
Sebastian Redl31310a22010-02-01 20:16:42 +00001938 // Ask the variable if it has a definition.
1939 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
1940 return MakeCXCursor(Def, CXXUnit);
1941 return clang_getNullCursor();
Douglas Gregorb6998662010-01-19 19:34:47 +00001942 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001943
Douglas Gregorb6998662010-01-19 19:34:47 +00001944 case Decl::FunctionTemplate: {
1945 const FunctionDecl *Def = 0;
1946 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001947 return MakeCXCursor(Def->getDescribedFunctionTemplate(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001948 return clang_getNullCursor();
1949 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001950
Douglas Gregorb6998662010-01-19 19:34:47 +00001951 case Decl::ClassTemplate: {
1952 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
Douglas Gregor952b0172010-02-11 01:04:33 +00001953 ->getDefinition())
Douglas Gregorb6998662010-01-19 19:34:47 +00001954 return MakeCXCursor(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001955 cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001956 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001957 return clang_getNullCursor();
1958 }
1959
1960 case Decl::Using: {
1961 UsingDecl *Using = cast<UsingDecl>(D);
1962 CXCursor Def = clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001963 for (UsingDecl::shadow_iterator S = Using->shadow_begin(),
1964 SEnd = Using->shadow_end();
Douglas Gregorb6998662010-01-19 19:34:47 +00001965 S != SEnd; ++S) {
1966 if (Def != clang_getNullCursor()) {
1967 // FIXME: We have no way to return multiple results.
1968 return clang_getNullCursor();
1969 }
1970
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001971 Def = clang_getCursorDefinition(MakeCXCursor((*S)->getTargetDecl(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001972 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00001973 }
1974
1975 return Def;
1976 }
1977
1978 case Decl::UsingShadow:
1979 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001980 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001981 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00001982
1983 case Decl::ObjCMethod: {
1984 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
1985 if (Method->isThisDeclarationADefinition())
1986 return C;
1987
1988 // Dig out the method definition in the associated
1989 // @implementation, if we have it.
1990 // FIXME: The ASTs should make finding the definition easier.
1991 if (ObjCInterfaceDecl *Class
1992 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
1993 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
1994 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
1995 Method->isInstanceMethod()))
1996 if (Def->isThisDeclarationADefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001997 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001998
1999 return clang_getNullCursor();
2000 }
2001
2002 case Decl::ObjCCategory:
2003 if (ObjCCategoryImplDecl *Impl
2004 = cast<ObjCCategoryDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002005 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002006 return clang_getNullCursor();
2007
2008 case Decl::ObjCProtocol:
2009 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
2010 return C;
2011 return clang_getNullCursor();
2012
2013 case Decl::ObjCInterface:
2014 // There are two notions of a "definition" for an Objective-C
2015 // class: the interface and its implementation. When we resolved a
2016 // reference to an Objective-C class, produce the @interface as
2017 // the definition; when we were provided with the interface,
2018 // produce the @implementation as the definition.
2019 if (WasReference) {
2020 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
2021 return C;
2022 } else if (ObjCImplementationDecl *Impl
2023 = cast<ObjCInterfaceDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002024 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002025 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002026
Douglas Gregorb6998662010-01-19 19:34:47 +00002027 case Decl::ObjCProperty:
2028 // FIXME: We don't really know where to find the
2029 // ObjCPropertyImplDecls that implement this property.
2030 return clang_getNullCursor();
2031
2032 case Decl::ObjCCompatibleAlias:
2033 if (ObjCInterfaceDecl *Class
2034 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
2035 if (!Class->isForwardDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002036 return MakeCXCursor(Class, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002037
Douglas Gregorb6998662010-01-19 19:34:47 +00002038 return clang_getNullCursor();
2039
2040 case Decl::ObjCForwardProtocol: {
2041 ObjCForwardProtocolDecl *Forward = cast<ObjCForwardProtocolDecl>(D);
2042 if (Forward->protocol_size() == 1)
2043 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002044 MakeCXCursor(*Forward->protocol_begin(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002045 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002046
2047 // FIXME: Cannot return multiple definitions.
2048 return clang_getNullCursor();
2049 }
2050
2051 case Decl::ObjCClass: {
2052 ObjCClassDecl *Class = cast<ObjCClassDecl>(D);
2053 if (Class->size() == 1) {
2054 ObjCInterfaceDecl *IFace = Class->begin()->getInterface();
2055 if (!IFace->isForwardDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002056 return MakeCXCursor(IFace, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002057 return clang_getNullCursor();
2058 }
2059
2060 // FIXME: Cannot return multiple definitions.
2061 return clang_getNullCursor();
2062 }
2063
2064 case Decl::Friend:
2065 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002066 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002067 return clang_getNullCursor();
2068
2069 case Decl::FriendTemplate:
2070 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002071 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002072 return clang_getNullCursor();
2073 }
2074
2075 return clang_getNullCursor();
2076}
2077
2078unsigned clang_isCursorDefinition(CXCursor C) {
2079 if (!clang_isDeclaration(C.kind))
2080 return 0;
2081
2082 return clang_getCursorDefinition(C) == C;
2083}
2084
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002085void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00002086 const char **startBuf,
2087 const char **endBuf,
2088 unsigned *startLine,
2089 unsigned *startColumn,
2090 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002091 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00002092 assert(getCursorDecl(C) && "CXCursor has null decl");
2093 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00002094 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
2095 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002096
Steve Naroff4ade6d62009-09-23 17:52:52 +00002097 SourceManager &SM = FD->getASTContext().getSourceManager();
2098 *startBuf = SM.getCharacterData(Body->getLBracLoc());
2099 *endBuf = SM.getCharacterData(Body->getRBracLoc());
2100 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
2101 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
2102 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
2103 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
2104}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002105
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002106void clang_enableStackTraces(void) {
2107 llvm::sys::PrintStackTraceOnErrorSignal();
2108}
2109
Ted Kremenekfb480492010-01-13 21:46:36 +00002110} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00002111
Ted Kremenekfb480492010-01-13 21:46:36 +00002112//===----------------------------------------------------------------------===//
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002113// Token-based Operations.
2114//===----------------------------------------------------------------------===//
2115
2116/* CXToken layout:
2117 * int_data[0]: a CXTokenKind
2118 * int_data[1]: starting token location
2119 * int_data[2]: token length
2120 * int_data[3]: reserved
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002121 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002122 * otherwise unused.
2123 */
2124extern "C" {
2125
2126CXTokenKind clang_getTokenKind(CXToken CXTok) {
2127 return static_cast<CXTokenKind>(CXTok.int_data[0]);
2128}
2129
2130CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
2131 switch (clang_getTokenKind(CXTok)) {
2132 case CXToken_Identifier:
2133 case CXToken_Keyword:
2134 // We know we have an IdentifierInfo*, so use that.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002135 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
2136 ->getNameStart());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002137
2138 case CXToken_Literal: {
2139 // We have stashed the starting pointer in the ptr_data field. Use it.
2140 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002141 return createCXString(llvm::StringRef(Text, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002142 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002143
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002144 case CXToken_Punctuation:
2145 case CXToken_Comment:
2146 break;
2147 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002148
2149 // We have to find the starting buffer pointer the hard way, by
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002150 // deconstructing the source location.
2151 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2152 if (!CXXUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002153 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002154
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002155 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
2156 std::pair<FileID, unsigned> LocInfo
2157 = CXXUnit->getSourceManager().getDecomposedLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +00002158 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002159 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00002160 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
2161 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00002162 return createCXString("");
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002163
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002164 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002165}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002166
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002167CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
2168 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2169 if (!CXXUnit)
2170 return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002171
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002172 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
2173 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
2174}
2175
2176CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
2177 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregor5352ac02010-01-28 00:27:43 +00002178 if (!CXXUnit)
2179 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002180
2181 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002182 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
2183}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002184
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002185void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
2186 CXToken **Tokens, unsigned *NumTokens) {
2187 if (Tokens)
2188 *Tokens = 0;
2189 if (NumTokens)
2190 *NumTokens = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002191
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002192 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2193 if (!CXXUnit || !Tokens || !NumTokens)
2194 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002195
Douglas Gregorbdf60622010-03-05 21:16:25 +00002196 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
2197
Daniel Dunbar85b988f2010-02-14 08:31:57 +00002198 SourceRange R = cxloc::translateCXSourceRange(Range);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002199 if (R.isInvalid())
2200 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002201
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002202 SourceManager &SourceMgr = CXXUnit->getSourceManager();
2203 std::pair<FileID, unsigned> BeginLocInfo
2204 = SourceMgr.getDecomposedLoc(R.getBegin());
2205 std::pair<FileID, unsigned> EndLocInfo
2206 = SourceMgr.getDecomposedLoc(R.getEnd());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002207
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002208 // Cannot tokenize across files.
2209 if (BeginLocInfo.first != EndLocInfo.first)
2210 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002211
2212 // Create a lexer
Douglas Gregorf715ca12010-03-16 00:06:06 +00002213 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002214 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00002215 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
Douglas Gregor47a3fcd2010-03-16 20:26:15 +00002216 if (Invalid)
2217 return;
Douglas Gregoraea67db2010-03-15 22:54:52 +00002218
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002219 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
2220 CXXUnit->getASTContext().getLangOptions(),
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002221 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002222 Lex.SetCommentRetentionState(true);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002223
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002224 // Lex tokens until we hit the end of the range.
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002225 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002226 llvm::SmallVector<CXToken, 32> CXTokens;
2227 Token Tok;
2228 do {
2229 // Lex the next token
2230 Lex.LexFromRawLexer(Tok);
2231 if (Tok.is(tok::eof))
2232 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002233
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002234 // Initialize the CXToken.
2235 CXToken CXTok;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002236
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002237 // - Common fields
2238 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
2239 CXTok.int_data[2] = Tok.getLength();
2240 CXTok.int_data[3] = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002241
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002242 // - Kind-specific fields
2243 if (Tok.isLiteral()) {
2244 CXTok.int_data[0] = CXToken_Literal;
2245 CXTok.ptr_data = (void *)Tok.getLiteralData();
2246 } else if (Tok.is(tok::identifier)) {
Douglas Gregoraea67db2010-03-15 22:54:52 +00002247 // Lookup the identifier to determine whether we have a keyword.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002248 std::pair<FileID, unsigned> LocInfo
2249 = SourceMgr.getDecomposedLoc(Tok.getLocation());
Douglas Gregorf715ca12010-03-16 00:06:06 +00002250 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002251 llvm::StringRef Buf
Douglas Gregorf715ca12010-03-16 00:06:06 +00002252 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
2253 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00002254 return;
2255
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002256 const char *StartPos = Buf.data() + LocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002257 IdentifierInfo *II
2258 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok, StartPos);
2259 CXTok.int_data[0] = II->getTokenID() == tok::identifier?
2260 CXToken_Identifier
2261 : CXToken_Keyword;
2262 CXTok.ptr_data = II;
2263 } else if (Tok.is(tok::comment)) {
2264 CXTok.int_data[0] = CXToken_Comment;
2265 CXTok.ptr_data = 0;
2266 } else {
2267 CXTok.int_data[0] = CXToken_Punctuation;
2268 CXTok.ptr_data = 0;
2269 }
2270 CXTokens.push_back(CXTok);
2271 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002272
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002273 if (CXTokens.empty())
2274 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002275
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002276 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
2277 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
2278 *NumTokens = CXTokens.size();
2279}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002280
2281typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
2282
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002283enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
2284 CXCursor parent,
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002285 CXClientData client_data) {
2286 AnnotateTokensData *Data = static_cast<AnnotateTokensData *>(client_data);
2287
2288 // We only annotate the locations of declarations, simple
2289 // references, and expressions which directly reference something.
2290 CXCursorKind Kind = clang_getCursorKind(cursor);
2291 if (clang_isDeclaration(Kind) || clang_isReference(Kind)) {
2292 // Okay: We can annotate the location of this declaration with the
2293 // declaration or reference
2294 } else if (clang_isExpression(cursor.kind)) {
2295 if (Kind != CXCursor_DeclRefExpr &&
2296 Kind != CXCursor_MemberRefExpr &&
2297 Kind != CXCursor_ObjCMessageExpr)
2298 return CXChildVisit_Recurse;
2299
2300 CXCursor Referenced = clang_getCursorReferenced(cursor);
2301 if (Referenced == cursor || Referenced == clang_getNullCursor())
2302 return CXChildVisit_Recurse;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002303
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002304 // Okay: we can annotate the location of this expression
Douglas Gregor0396f462010-03-19 05:22:59 +00002305 } else if (clang_isPreprocessing(cursor.kind)) {
2306 // We can always annotate a preprocessing directive/macro instantiation.
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002307 } else {
2308 // Nothing to annotate
2309 return CXChildVisit_Recurse;
2310 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002311
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002312 CXSourceLocation Loc = clang_getCursorLocation(cursor);
2313 (*Data)[Loc.int_data] = cursor;
2314 return CXChildVisit_Recurse;
2315}
2316
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002317void clang_annotateTokens(CXTranslationUnit TU,
2318 CXToken *Tokens, unsigned NumTokens,
2319 CXCursor *Cursors) {
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002320 if (NumTokens == 0)
2321 return;
2322
2323 // Any token we don't specifically annotate will have a NULL cursor.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002324 for (unsigned I = 0; I != NumTokens; ++I)
2325 Cursors[I] = clang_getNullCursor();
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002326
2327 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2328 if (!CXXUnit || !Tokens)
2329 return;
2330
Douglas Gregorbdf60622010-03-05 21:16:25 +00002331 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
2332
Douglas Gregor0396f462010-03-19 05:22:59 +00002333 // Determine the region of interest, which contains all of the tokens.
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002334 SourceRange RegionOfInterest;
2335 RegionOfInterest.setBegin(
2336 cxloc::translateSourceLocation(clang_getTokenLocation(TU, Tokens[0])));
2337 SourceLocation End
Douglas Gregor0396f462010-03-19 05:22:59 +00002338 = cxloc::translateSourceLocation(clang_getTokenLocation(TU,
2339 Tokens[NumTokens - 1]));
Daniel Dunbard52864b2010-02-14 10:02:57 +00002340 RegionOfInterest.setEnd(CXXUnit->getPreprocessor().getLocForEndOfToken(End));
Douglas Gregor2507fa82010-03-19 00:18:31 +00002341
Douglas Gregor0396f462010-03-19 05:22:59 +00002342 // A mapping from the source locations found when re-lexing or traversing the
2343 // region of interest to the corresponding cursors.
2344 AnnotateTokensData Annotated;
2345
2346 // Relex the tokens within the source range to look for preprocessing
2347 // directives.
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002348 SourceManager &SourceMgr = CXXUnit->getSourceManager();
2349 std::pair<FileID, unsigned> BeginLocInfo
2350 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
2351 std::pair<FileID, unsigned> EndLocInfo
2352 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
2353
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002354 llvm::StringRef Buffer;
Douglas Gregor0396f462010-03-19 05:22:59 +00002355 bool Invalid = false;
2356 if (BeginLocInfo.first == EndLocInfo.first &&
2357 ((Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid)),true) &&
2358 !Invalid) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002359 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
2360 CXXUnit->getASTContext().getLangOptions(),
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002361 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
2362 Buffer.end());
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002363 Lex.SetCommentRetentionState(true);
2364
2365 // Lex tokens in raw mode until we hit the end of the range, to avoid
2366 // entering #includes or expanding macros.
Douglas Gregor48072312010-03-18 15:23:44 +00002367 while (true) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002368 Token Tok;
2369 Lex.LexFromRawLexer(Tok);
2370
2371 reprocess:
2372 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
2373 // We have found a preprocessing directive. Gobble it up so that we
2374 // don't see it while preprocessing these tokens later, but keep track of
2375 // all of the token locations inside this preprocessing directive so that
2376 // we can annotate them appropriately.
2377 //
2378 // FIXME: Some simple tests here could identify macro definitions and
2379 // #undefs, to provide specific cursor kinds for those.
2380 std::vector<SourceLocation> Locations;
2381 do {
2382 Locations.push_back(Tok.getLocation());
2383 Lex.LexFromRawLexer(Tok);
2384 } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
2385
2386 using namespace cxcursor;
2387 CXCursor Cursor
2388 = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
2389 Locations.back()),
2390 CXXUnit);
2391 for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
2392 Annotated[Locations[I].getRawEncoding()] = Cursor;
2393 }
2394
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002395 if (Tok.isAtStartOfLine())
2396 goto reprocess;
2397
2398 continue;
2399 }
2400
Douglas Gregor48072312010-03-18 15:23:44 +00002401 if (Tok.is(tok::eof))
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002402 break;
2403 }
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002404 }
Douglas Gregor0396f462010-03-19 05:22:59 +00002405
2406 // Annotate all of the source locations in the region of interest that map to
2407 // a specific cursor.
2408 CXCursor Parent = clang_getTranslationUnitCursor(CXXUnit);
2409 CursorVisitor AnnotateVis(CXXUnit, AnnotateTokensVisitor, &Annotated,
2410 Decl::MaxPCHLevel, RegionOfInterest);
2411 AnnotateVis.VisitChildren(Parent);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002412
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002413 for (unsigned I = 0; I != NumTokens; ++I) {
2414 // Determine whether we saw a cursor at this token's location.
2415 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
2416 if (Pos == Annotated.end())
2417 continue;
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002418
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002419 Cursors[I] = Pos->second;
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002420 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002421}
2422
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002423void clang_disposeTokens(CXTranslationUnit TU,
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002424 CXToken *Tokens, unsigned NumTokens) {
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002425 free(Tokens);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002426}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002427
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002428} // end: extern "C"
2429
2430//===----------------------------------------------------------------------===//
Ted Kremenek16b42592010-03-03 06:36:57 +00002431// Operations for querying linkage of a cursor.
2432//===----------------------------------------------------------------------===//
2433
2434extern "C" {
2435CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
Douglas Gregor0396f462010-03-19 05:22:59 +00002436 if (!clang_isDeclaration(cursor.kind))
2437 return CXLinkage_Invalid;
2438
Ted Kremenek16b42592010-03-03 06:36:57 +00002439 Decl *D = cxcursor::getCursorDecl(cursor);
2440 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
2441 switch (ND->getLinkage()) {
2442 case NoLinkage: return CXLinkage_NoLinkage;
2443 case InternalLinkage: return CXLinkage_Internal;
2444 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
2445 case ExternalLinkage: return CXLinkage_External;
2446 };
2447
2448 return CXLinkage_Invalid;
2449}
2450} // end: extern "C"
2451
2452//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00002453// CXString Operations.
2454//===----------------------------------------------------------------------===//
2455
2456extern "C" {
2457const char *clang_getCString(CXString string) {
2458 return string.Spelling;
2459}
2460
2461void clang_disposeString(CXString string) {
2462 if (string.MustFreeString && string.Spelling)
2463 free((void*)string.Spelling);
2464}
Ted Kremenek04bb7162010-01-22 22:44:15 +00002465
Ted Kremenekfb480492010-01-13 21:46:36 +00002466} // end: extern "C"
Ted Kremenek04bb7162010-01-22 22:44:15 +00002467
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002468namespace clang { namespace cxstring {
2469CXString createCXString(const char *String, bool DupString){
2470 CXString Str;
2471 if (DupString) {
2472 Str.Spelling = strdup(String);
2473 Str.MustFreeString = 1;
2474 } else {
2475 Str.Spelling = String;
2476 Str.MustFreeString = 0;
2477 }
2478 return Str;
2479}
2480
2481CXString createCXString(llvm::StringRef String, bool DupString) {
2482 CXString Result;
2483 if (DupString || (!String.empty() && String.data()[String.size()] != 0)) {
2484 char *Spelling = (char *)malloc(String.size() + 1);
2485 memmove(Spelling, String.data(), String.size());
2486 Spelling[String.size()] = 0;
2487 Result.Spelling = Spelling;
2488 Result.MustFreeString = 1;
2489 } else {
2490 Result.Spelling = String.data();
2491 Result.MustFreeString = 0;
2492 }
2493 return Result;
2494}
2495}}
2496
Ted Kremenek04bb7162010-01-22 22:44:15 +00002497//===----------------------------------------------------------------------===//
2498// Misc. utility functions.
2499//===----------------------------------------------------------------------===//
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002500
Ted Kremenek04bb7162010-01-22 22:44:15 +00002501extern "C" {
2502
Ted Kremeneka2a9d6e2010-02-12 22:54:40 +00002503CXString clang_getClangVersion() {
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002504 return createCXString(getClangFullVersion());
Ted Kremenek04bb7162010-01-22 22:44:15 +00002505}
2506
2507} // end: extern "C"