blob: 7a8c78eceae40beae9ee3af15b48ccb37a936650 [file] [log] [blame]
Ted Kremenekd2fa5662009-08-26 22:36:44 +00001//===- CIndex.cpp - Clang-C Source Indexing Library -----------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00007//
Ted Kremenekd2fa5662009-08-26 22:36:44 +00008//===----------------------------------------------------------------------===//
9//
Ted Kremenekab188932010-01-05 19:32:54 +000010// This file implements the main API hooks in the Clang-C Source Indexing
11// library.
Ted Kremenekd2fa5662009-08-26 22:36:44 +000012//
13//===----------------------------------------------------------------------===//
14
Ted Kremenekab188932010-01-05 19:32:54 +000015#include "CIndexer.h"
Ted Kremenek16c440a2010-01-15 20:35:54 +000016#include "CXCursor.h"
Ted Kremeneka297de22010-01-25 22:34:44 +000017#include "CXSourceLocation.h"
Douglas Gregor5352ac02010-01-28 00:27:43 +000018#include "CIndexDiagnostic.h"
Ted Kremenekab188932010-01-05 19:32:54 +000019
Ted Kremenek04bb7162010-01-22 22:44:15 +000020#include "clang/Basic/Version.h"
Douglas Gregor936ea3b2010-01-28 00:56:43 +000021
Steve Naroff50398192009-08-28 15:28:48 +000022#include "clang/AST/DeclVisitor.h"
Steve Narofffb570422009-09-22 19:25:29 +000023#include "clang/AST/StmtVisitor.h"
Douglas Gregor7d0d40e2010-01-21 16:28:34 +000024#include "clang/AST/TypeLocVisitor.h"
Douglas Gregor936ea3b2010-01-28 00:56:43 +000025#include "clang/Frontend/FrontendDiagnostic.h"
Ted Kremenekd8210652010-01-06 23:43:31 +000026#include "clang/Lex/Lexer.h"
Douglas Gregor33e9abd2010-01-22 19:49:59 +000027#include "clang/Lex/Preprocessor.h"
Douglas Gregor02465752009-10-16 21:24:31 +000028#include "llvm/Support/MemoryBuffer.h"
Benjamin Kramer0829a832009-10-18 11:19:36 +000029#include "llvm/System/Program.h"
Douglas Gregor0a812cf2010-02-18 23:07:20 +000030#include "llvm/System/Signals.h"
Ted Kremenekfc062212009-10-19 21:44:57 +000031
Benjamin Kramerc2a98162010-03-13 21:22:49 +000032// Needed to define L_TMPNAM on some systems.
33#include <cstdio>
34
Steve Naroff50398192009-08-28 15:28:48 +000035using namespace clang;
Ted Kremenek16c440a2010-01-15 20:35:54 +000036using namespace clang::cxcursor;
Ted Kremenekee4db4f2010-02-17 00:41:08 +000037using namespace clang::cxstring;
Steve Naroff50398192009-08-28 15:28:48 +000038using namespace idx;
39
Ted Kremenek8a8da7d2010-01-06 03:42:32 +000040//===----------------------------------------------------------------------===//
41// Crash Reporting.
42//===----------------------------------------------------------------------===//
43
44#ifdef __APPLE__
Ted Kremenek29b72842010-01-07 22:49:05 +000045#define USE_CRASHTRACER
Ted Kremenek8a8da7d2010-01-06 03:42:32 +000046#include "clang/Analysis/Support/SaveAndRestore.h"
47// Integrate with crash reporter.
48extern "C" const char *__crashreporter_info__;
Ted Kremenek6b569992010-02-17 21:12:23 +000049#define NUM_CRASH_STRINGS 32
Ted Kremenek29b72842010-01-07 22:49:05 +000050static unsigned crashtracer_counter = 0;
Ted Kremenek254ba7c2010-01-07 23:13:53 +000051static unsigned crashtracer_counter_id[NUM_CRASH_STRINGS] = { 0 };
Ted Kremenek29b72842010-01-07 22:49:05 +000052static const char *crashtracer_strings[NUM_CRASH_STRINGS] = { 0 };
53static const char *agg_crashtracer_strings[NUM_CRASH_STRINGS] = { 0 };
54
55static unsigned SetCrashTracerInfo(const char *str,
56 llvm::SmallString<1024> &AggStr) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +000057
Ted Kremenek254ba7c2010-01-07 23:13:53 +000058 unsigned slot = 0;
Ted Kremenek29b72842010-01-07 22:49:05 +000059 while (crashtracer_strings[slot]) {
60 if (++slot == NUM_CRASH_STRINGS)
61 slot = 0;
62 }
63 crashtracer_strings[slot] = str;
Ted Kremenek254ba7c2010-01-07 23:13:53 +000064 crashtracer_counter_id[slot] = ++crashtracer_counter;
Ted Kremenek29b72842010-01-07 22:49:05 +000065
66 // We need to create an aggregate string because multiple threads
67 // may be in this method at one time. The crash reporter string
68 // will attempt to overapproximate the set of in-flight invocations
69 // of this function. Race conditions can still cause this goal
70 // to not be achieved.
71 {
Ted Kremenekf0e23e82010-02-17 00:41:40 +000072 llvm::raw_svector_ostream Out(AggStr);
Ted Kremenek29b72842010-01-07 22:49:05 +000073 for (unsigned i = 0; i < NUM_CRASH_STRINGS; ++i)
74 if (crashtracer_strings[i]) Out << crashtracer_strings[i] << '\n';
75 }
76 __crashreporter_info__ = agg_crashtracer_strings[slot] = AggStr.c_str();
77 return slot;
78}
79
80static void ResetCrashTracerInfo(unsigned slot) {
Ted Kremenek254ba7c2010-01-07 23:13:53 +000081 unsigned max_slot = 0;
82 unsigned max_value = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +000083
Ted Kremenek254ba7c2010-01-07 23:13:53 +000084 crashtracer_strings[slot] = agg_crashtracer_strings[slot] = 0;
85
86 for (unsigned i = 0 ; i < NUM_CRASH_STRINGS; ++i)
87 if (agg_crashtracer_strings[i] &&
88 crashtracer_counter_id[i] > max_value) {
89 max_slot = i;
90 max_value = crashtracer_counter_id[i];
Ted Kremenek29b72842010-01-07 22:49:05 +000091 }
Ted Kremenek254ba7c2010-01-07 23:13:53 +000092
93 __crashreporter_info__ = agg_crashtracer_strings[max_slot];
Ted Kremenek29b72842010-01-07 22:49:05 +000094}
95
96namespace {
97class ArgsCrashTracerInfo {
98 llvm::SmallString<1024> CrashString;
99 llvm::SmallString<1024> AggregateString;
100 unsigned crashtracerSlot;
101public:
102 ArgsCrashTracerInfo(llvm::SmallVectorImpl<const char*> &Args)
103 : crashtracerSlot(0)
104 {
105 {
106 llvm::raw_svector_ostream Out(CrashString);
Ted Kremenek0baa9522010-03-05 22:43:25 +0000107 Out << "ClangCIndex [" << getClangFullVersion() << "]"
108 << "[createTranslationUnitFromSourceFile]: clang";
Ted Kremenek29b72842010-01-07 22:49:05 +0000109 for (llvm::SmallVectorImpl<const char*>::iterator I=Args.begin(),
110 E=Args.end(); I!=E; ++I)
111 Out << ' ' << *I;
112 }
113 crashtracerSlot = SetCrashTracerInfo(CrashString.c_str(),
114 AggregateString);
115 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000116
Ted Kremenek29b72842010-01-07 22:49:05 +0000117 ~ArgsCrashTracerInfo() {
118 ResetCrashTracerInfo(crashtracerSlot);
119 }
120};
121}
122#endif
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000123
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000124/// \brief The result of comparing two source ranges.
125enum RangeComparisonResult {
126 /// \brief Either the ranges overlap or one of the ranges is invalid.
127 RangeOverlap,
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000128
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000129 /// \brief The first range ends before the second range starts.
130 RangeBefore,
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000131
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000132 /// \brief The first range starts after the second range ends.
133 RangeAfter
134};
135
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000136/// \brief Compare two source ranges to determine their relative position in
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000137/// the translation unit.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000138static RangeComparisonResult RangeCompare(SourceManager &SM,
139 SourceRange R1,
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000140 SourceRange R2) {
141 assert(R1.isValid() && "First range is invalid?");
142 assert(R2.isValid() && "Second range is invalid?");
Daniel Dunbard52864b2010-02-14 10:02:57 +0000143 if (R1.getEnd() == R2.getBegin() ||
144 SM.isBeforeInTranslationUnit(R1.getEnd(), R2.getBegin()))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000145 return RangeBefore;
Daniel Dunbard52864b2010-02-14 10:02:57 +0000146 if (R2.getEnd() == R1.getBegin() ||
147 SM.isBeforeInTranslationUnit(R2.getEnd(), R1.getBegin()))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000148 return RangeAfter;
149 return RangeOverlap;
150}
151
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000152/// \brief Translate a Clang source range into a CIndex source range.
153///
154/// Clang internally represents ranges where the end location points to the
155/// start of the token at the end. However, for external clients it is more
156/// useful to have a CXSourceRange be a proper half-open interval. This routine
157/// does the appropriate translation.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000158CXSourceRange cxloc::translateSourceRange(const SourceManager &SM,
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000159 const LangOptions &LangOpts,
160 SourceRange R) {
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000161 // We want the last character in this location, so we will adjust the
Douglas Gregor6a5a23f2010-03-19 21:51:54 +0000162 // location accordingly.
163 // FIXME: How do do this with a macro instantiation location?
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000164 SourceLocation EndLoc = R.getEnd();
Douglas Gregor6a5a23f2010-03-19 21:51:54 +0000165 if (!EndLoc.isInvalid() && EndLoc.isFileID()) {
166 unsigned Length = Lexer::MeasureTokenLength(EndLoc, SM, LangOpts);
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000167 EndLoc = EndLoc.getFileLocWithOffset(Length);
168 }
169
170 CXSourceRange Result = { { (void *)&SM, (void *)&LangOpts },
171 R.getBegin().getRawEncoding(),
172 EndLoc.getRawEncoding() };
173 return Result;
174}
Douglas Gregor1db19de2010-01-19 21:36:55 +0000175
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000176//===----------------------------------------------------------------------===//
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000177// Cursor visitor.
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000178//===----------------------------------------------------------------------===//
179
Steve Naroff89922f82009-08-31 00:59:03 +0000180namespace {
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000181
Douglas Gregorb1373d02010-01-20 20:59:29 +0000182// Cursor visitor.
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000183class CursorVisitor : public DeclVisitor<CursorVisitor, bool>,
Douglas Gregora59e3902010-01-21 23:27:09 +0000184 public TypeLocVisitor<CursorVisitor, bool>,
185 public StmtVisitor<CursorVisitor, bool>
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000186{
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000187 /// \brief The translation unit we are traversing.
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000188 ASTUnit *TU;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000189
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000190 /// \brief The parent cursor whose children we are traversing.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000191 CXCursor Parent;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000192
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000193 /// \brief The declaration that serves at the parent of any statement or
194 /// expression nodes.
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000195 Decl *StmtParent;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000196
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000197 /// \brief The visitor function.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000198 CXCursorVisitor Visitor;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000199
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000200 /// \brief The opaque client data, to be passed along to the visitor.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000201 CXClientData ClientData;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000202
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000203 // MaxPCHLevel - the maximum PCH level of declarations that we will pass on
204 // to the visitor. Declarations with a PCH level greater than this value will
205 // be suppressed.
206 unsigned MaxPCHLevel;
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000207
208 /// \brief When valid, a source range to which the cursor should restrict
209 /// its search.
210 SourceRange RegionOfInterest;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000211
Douglas Gregorb1373d02010-01-20 20:59:29 +0000212 using DeclVisitor<CursorVisitor, bool>::Visit;
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000213 using TypeLocVisitor<CursorVisitor, bool>::Visit;
Douglas Gregora59e3902010-01-21 23:27:09 +0000214 using StmtVisitor<CursorVisitor, bool>::Visit;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000215
216 /// \brief Determine whether this particular source range comes before, comes
217 /// after, or overlaps the region of interest.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000218 ///
Daniel Dunbard52864b2010-02-14 10:02:57 +0000219 /// \param R a half-open source range retrieved from the abstract syntax tree.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000220 RangeComparisonResult CompareRegionOfInterest(SourceRange R);
221
Steve Naroff89922f82009-08-31 00:59:03 +0000222public:
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000223 CursorVisitor(ASTUnit *TU, CXCursorVisitor Visitor, CXClientData ClientData,
224 unsigned MaxPCHLevel,
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000225 SourceRange RegionOfInterest = SourceRange())
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000226 : TU(TU), Visitor(Visitor), ClientData(ClientData),
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000227 MaxPCHLevel(MaxPCHLevel), RegionOfInterest(RegionOfInterest)
Douglas Gregorb1373d02010-01-20 20:59:29 +0000228 {
229 Parent.kind = CXCursor_NoDeclFound;
230 Parent.data[0] = 0;
231 Parent.data[1] = 0;
232 Parent.data[2] = 0;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000233 StmtParent = 0;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000234 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000235
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000236 bool Visit(CXCursor Cursor, bool CheckedRegionOfInterest = false);
Douglas Gregor788f5a12010-03-20 00:41:21 +0000237
238 std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
239 getPreprocessedEntities();
240
Douglas Gregorb1373d02010-01-20 20:59:29 +0000241 bool VisitChildren(CXCursor Parent);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000242
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000243 // Declaration visitors
Ted Kremenek09dfa372010-02-18 05:46:33 +0000244 bool VisitAttributes(Decl *D);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000245 bool VisitDeclContext(DeclContext *DC);
Ted Kremenek4540c9c2010-02-18 18:47:08 +0000246 bool VisitTranslationUnitDecl(TranslationUnitDecl *D);
247 bool VisitTypedefDecl(TypedefDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000248 bool VisitTagDecl(TagDecl *D);
249 bool VisitEnumConstantDecl(EnumConstantDecl *D);
250 bool VisitDeclaratorDecl(DeclaratorDecl *DD);
251 bool VisitFunctionDecl(FunctionDecl *ND);
252 bool VisitFieldDecl(FieldDecl *D);
Ted Kremenek4540c9c2010-02-18 18:47:08 +0000253 bool VisitVarDecl(VarDecl *);
Ted Kremenek79758f62010-02-18 22:36:18 +0000254 bool VisitObjCMethodDecl(ObjCMethodDecl *ND);
255 bool VisitObjCContainerDecl(ObjCContainerDecl *D);
256 bool VisitObjCCategoryDecl(ObjCCategoryDecl *ND);
257 bool VisitObjCProtocolDecl(ObjCProtocolDecl *PID);
258 bool VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
259 bool VisitObjCImplDecl(ObjCImplDecl *D);
260 bool VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
261 bool VisitObjCImplementationDecl(ObjCImplementationDecl *D);
262 // FIXME: ObjCPropertyDecl requires TypeSourceInfo, getter/setter locations,
263 // etc.
264 // FIXME: ObjCCompatibleAliasDecl requires aliased-class locations.
265 bool VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D);
266 bool VisitObjCClassDecl(ObjCClassDecl *D);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000267
268 // Type visitors
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000269 // FIXME: QualifiedTypeLoc doesn't provide any location information
270 bool VisitBuiltinTypeLoc(BuiltinTypeLoc TL);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000271 bool VisitTypedefTypeLoc(TypedefTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000272 bool VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL);
273 bool VisitTagTypeLoc(TagTypeLoc TL);
274 // FIXME: TemplateTypeParmTypeLoc doesn't provide any location information
275 bool VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL);
276 bool VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL);
277 bool VisitPointerTypeLoc(PointerTypeLoc TL);
278 bool VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL);
279 bool VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL);
280 bool VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL);
281 bool VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL);
282 bool VisitFunctionTypeLoc(FunctionTypeLoc TL);
283 bool VisitArrayTypeLoc(ArrayTypeLoc TL);
Douglas Gregor2332c112010-01-21 20:48:56 +0000284 // FIXME: Implement for TemplateSpecializationTypeLoc
285 // FIXME: Implement visitors here when the unimplemented TypeLocs get
286 // implemented
287 bool VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL);
288 bool VisitTypeOfTypeLoc(TypeOfTypeLoc TL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000289
Douglas Gregora59e3902010-01-21 23:27:09 +0000290 // Statement visitors
291 bool VisitStmt(Stmt *S);
292 bool VisitDeclStmt(DeclStmt *S);
Douglas Gregorf5bab412010-01-22 01:00:11 +0000293 // FIXME: LabelStmt label?
294 bool VisitIfStmt(IfStmt *S);
295 bool VisitSwitchStmt(SwitchStmt *S);
Douglas Gregor263b47b2010-01-25 16:12:32 +0000296 bool VisitWhileStmt(WhileStmt *S);
297 bool VisitForStmt(ForStmt *S);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000298
Douglas Gregor336fd812010-01-23 00:40:08 +0000299 // Expression visitors
300 bool VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E);
301 bool VisitExplicitCastExpr(ExplicitCastExpr *E);
302 bool VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
Douglas Gregorc2350e52010-03-08 16:40:19 +0000303 bool VisitObjCMessageExpr(ObjCMessageExpr *E);
Steve Naroff89922f82009-08-31 00:59:03 +0000304};
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000305
Ted Kremenekab188932010-01-05 19:32:54 +0000306} // end anonymous namespace
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000307
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000308RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000309 return RangeCompare(TU->getSourceManager(), R, RegionOfInterest);
310}
311
Douglas Gregorb1373d02010-01-20 20:59:29 +0000312/// \brief Visit the given cursor and, if requested by the visitor,
313/// its children.
314///
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000315/// \param Cursor the cursor to visit.
316///
317/// \param CheckRegionOfInterest if true, then the caller already checked that
318/// this cursor is within the region of interest.
319///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000320/// \returns true if the visitation should be aborted, false if it
321/// should continue.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000322bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
Douglas Gregorb1373d02010-01-20 20:59:29 +0000323 if (clang_isInvalid(Cursor.kind))
324 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000325
Douglas Gregorb1373d02010-01-20 20:59:29 +0000326 if (clang_isDeclaration(Cursor.kind)) {
327 Decl *D = getCursorDecl(Cursor);
328 assert(D && "Invalid declaration cursor");
329 if (D->getPCHLevel() > MaxPCHLevel)
330 return false;
331
332 if (D->isImplicit())
333 return false;
334 }
335
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000336 // If we have a range of interest, and this cursor doesn't intersect with it,
337 // we're done.
338 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
Daniel Dunbarf408f322010-02-14 08:32:05 +0000339 SourceRange Range =
340 cxloc::translateCXSourceRange(clang_getCursorExtent(Cursor));
341 if (Range.isInvalid() || CompareRegionOfInterest(Range))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000342 return false;
343 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000344
Douglas Gregorb1373d02010-01-20 20:59:29 +0000345 switch (Visitor(Cursor, Parent, ClientData)) {
346 case CXChildVisit_Break:
347 return true;
348
349 case CXChildVisit_Continue:
350 return false;
351
352 case CXChildVisit_Recurse:
353 return VisitChildren(Cursor);
354 }
355
Douglas Gregorfd643772010-01-25 16:45:46 +0000356 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000357}
358
Douglas Gregor788f5a12010-03-20 00:41:21 +0000359std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
360CursorVisitor::getPreprocessedEntities() {
361 PreprocessingRecord &PPRec
362 = *TU->getPreprocessor().getPreprocessingRecord();
363
364 bool OnlyLocalDecls
365 = !TU->isMainFileAST() && TU->getOnlyLocalDecls();
366
367 // There is no region of interest; we have to walk everything.
368 if (RegionOfInterest.isInvalid())
369 return std::make_pair(PPRec.begin(OnlyLocalDecls),
370 PPRec.end(OnlyLocalDecls));
371
372 // Find the file in which the region of interest lands.
373 SourceManager &SM = TU->getSourceManager();
374 std::pair<FileID, unsigned> Begin
375 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getBegin());
376 std::pair<FileID, unsigned> End
377 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getEnd());
378
379 // The region of interest spans files; we have to walk everything.
380 if (Begin.first != End.first)
381 return std::make_pair(PPRec.begin(OnlyLocalDecls),
382 PPRec.end(OnlyLocalDecls));
383
384 ASTUnit::PreprocessedEntitiesByFileMap &ByFileMap
385 = TU->getPreprocessedEntitiesByFile();
386 if (ByFileMap.empty()) {
387 // Build the mapping from files to sets of preprocessed entities.
388 for (PreprocessingRecord::iterator E = PPRec.begin(OnlyLocalDecls),
389 EEnd = PPRec.end(OnlyLocalDecls);
390 E != EEnd; ++E) {
391 std::pair<FileID, unsigned> P
392 = SM.getDecomposedInstantiationLoc((*E)->getSourceRange().getBegin());
393 ByFileMap[P.first].push_back(*E);
394 }
395 }
396
397 return std::make_pair(ByFileMap[Begin.first].begin(),
398 ByFileMap[Begin.first].end());
399}
400
Douglas Gregorb1373d02010-01-20 20:59:29 +0000401/// \brief Visit the children of the given cursor.
402///
403/// \returns true if the visitation should be aborted, false if it
404/// should continue.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000405bool CursorVisitor::VisitChildren(CXCursor Cursor) {
Douglas Gregora59e3902010-01-21 23:27:09 +0000406 if (clang_isReference(Cursor.kind)) {
407 // By definition, references have no children.
408 return false;
409 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000410
411 // Set the Parent field to Cursor, then back to its old value once we're
Douglas Gregorb1373d02010-01-20 20:59:29 +0000412 // done.
413 class SetParentRAII {
414 CXCursor &Parent;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000415 Decl *&StmtParent;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000416 CXCursor OldParent;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000417
Douglas Gregorb1373d02010-01-20 20:59:29 +0000418 public:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000419 SetParentRAII(CXCursor &Parent, Decl *&StmtParent, CXCursor NewParent)
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000420 : Parent(Parent), StmtParent(StmtParent), OldParent(Parent)
Douglas Gregorb1373d02010-01-20 20:59:29 +0000421 {
422 Parent = NewParent;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000423 if (clang_isDeclaration(Parent.kind))
424 StmtParent = getCursorDecl(Parent);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000425 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000426
Douglas Gregorb1373d02010-01-20 20:59:29 +0000427 ~SetParentRAII() {
428 Parent = OldParent;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000429 if (clang_isDeclaration(Parent.kind))
430 StmtParent = getCursorDecl(Parent);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000431 }
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000432 } SetParent(Parent, StmtParent, Cursor);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000433
Douglas Gregorb1373d02010-01-20 20:59:29 +0000434 if (clang_isDeclaration(Cursor.kind)) {
435 Decl *D = getCursorDecl(Cursor);
436 assert(D && "Invalid declaration cursor");
Ted Kremenek539311e2010-02-18 18:47:01 +0000437 return VisitAttributes(D) || Visit(D);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000438 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000439
Douglas Gregora59e3902010-01-21 23:27:09 +0000440 if (clang_isStatement(Cursor.kind))
441 return Visit(getCursorStmt(Cursor));
442 if (clang_isExpression(Cursor.kind))
443 return Visit(getCursorExpr(Cursor));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000444
Douglas Gregorb1373d02010-01-20 20:59:29 +0000445 if (clang_isTranslationUnit(Cursor.kind)) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000446 ASTUnit *CXXUnit = getCursorASTUnit(Cursor);
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000447 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
448 RegionOfInterest.isInvalid()) {
Douglas Gregor7b691f332010-01-20 21:13:59 +0000449 const std::vector<Decl*> &TLDs = CXXUnit->getTopLevelDecls();
450 for (std::vector<Decl*>::const_iterator it = TLDs.begin(),
451 ie = TLDs.end(); it != ie; ++it) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000452 if (Visit(MakeCXCursor(*it, CXXUnit), true))
Douglas Gregor7b691f332010-01-20 21:13:59 +0000453 return true;
454 }
Douglas Gregor0396f462010-03-19 05:22:59 +0000455 } else if (VisitDeclContext(
456 CXXUnit->getASTContext().getTranslationUnitDecl()))
457 return true;
Bob Wilson3178cb62010-03-19 03:57:57 +0000458
Douglas Gregor0396f462010-03-19 05:22:59 +0000459 // Walk the preprocessing record.
Daniel Dunbar8de30ff2010-03-20 01:11:56 +0000460 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000461 // FIXME: Once we have the ability to deserialize a preprocessing record,
462 // do so.
Douglas Gregor788f5a12010-03-20 00:41:21 +0000463 PreprocessingRecord::iterator E, EEnd;
464 for (llvm::tie(E, EEnd) = getPreprocessedEntities(); E != EEnd; ++E) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000465 if (MacroInstantiation *MI = dyn_cast<MacroInstantiation>(*E)) {
466 if (Visit(MakeMacroInstantiationCursor(MI, CXXUnit)))
467 return true;
Douglas Gregor788f5a12010-03-20 00:41:21 +0000468
Douglas Gregor0396f462010-03-19 05:22:59 +0000469 continue;
470 }
471
472 if (MacroDefinition *MD = dyn_cast<MacroDefinition>(*E)) {
473 if (Visit(MakeMacroDefinitionCursor(MD, CXXUnit)))
474 return true;
475
476 continue;
477 }
478 }
479 }
Douglas Gregor7b691f332010-01-20 21:13:59 +0000480 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000481 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000482
Douglas Gregorb1373d02010-01-20 20:59:29 +0000483 // Nothing to visit at the moment.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000484 return false;
485}
486
Douglas Gregorb1373d02010-01-20 20:59:29 +0000487bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000488 for (DeclContext::decl_iterator
Douglas Gregorb1373d02010-01-20 20:59:29 +0000489 I = DC->decls_begin(), E = DC->decls_end(); I != E; ++I) {
Ted Kremenek09dfa372010-02-18 05:46:33 +0000490
Daniel Dunbard52864b2010-02-14 10:02:57 +0000491 CXCursor Cursor = MakeCXCursor(*I, TU);
492
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000493 if (RegionOfInterest.isValid()) {
Daniel Dunbard52864b2010-02-14 10:02:57 +0000494 SourceRange Range =
495 cxloc::translateCXSourceRange(clang_getCursorExtent(Cursor));
496 if (Range.isInvalid())
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000497 continue;
Daniel Dunbard52864b2010-02-14 10:02:57 +0000498
499 switch (CompareRegionOfInterest(Range)) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000500 case RangeBefore:
501 // This declaration comes before the region of interest; skip it.
502 continue;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000503
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000504 case RangeAfter:
505 // This declaration comes after the region of interest; we're done.
506 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000507
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000508 case RangeOverlap:
509 // This declaration overlaps the region of interest; visit it.
510 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000511 }
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000512 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000513
Daniel Dunbard52864b2010-02-14 10:02:57 +0000514 if (Visit(Cursor, true))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000515 return true;
516 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000517
Douglas Gregorb1373d02010-01-20 20:59:29 +0000518 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000519}
520
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000521bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
522 llvm_unreachable("Translation units are visited directly by Visit()");
523 return false;
524}
525
526bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
527 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
528 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000529
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000530 return false;
531}
532
533bool CursorVisitor::VisitTagDecl(TagDecl *D) {
534 return VisitDeclContext(D);
535}
536
537bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
538 if (Expr *Init = D->getInitExpr())
539 return Visit(MakeCXCursor(Init, StmtParent, TU));
540 return false;
541}
542
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000543bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
544 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
545 if (Visit(TSInfo->getTypeLoc()))
546 return true;
547
548 return false;
549}
550
Douglas Gregorb1373d02010-01-20 20:59:29 +0000551bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000552 if (VisitDeclaratorDecl(ND))
553 return true;
554
Douglas Gregora59e3902010-01-21 23:27:09 +0000555 if (ND->isThisDeclarationADefinition() &&
556 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
557 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000558
Douglas Gregorb1373d02010-01-20 20:59:29 +0000559 return false;
560}
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000561
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000562bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
563 if (VisitDeclaratorDecl(D))
564 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000565
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000566 if (Expr *BitWidth = D->getBitWidth())
567 return Visit(MakeCXCursor(BitWidth, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000568
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000569 return false;
570}
571
572bool CursorVisitor::VisitVarDecl(VarDecl *D) {
573 if (VisitDeclaratorDecl(D))
574 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000575
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000576 if (Expr *Init = D->getInit())
577 return Visit(MakeCXCursor(Init, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000578
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000579 return false;
580}
581
582bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
Douglas Gregor4bc1cb62010-03-08 14:59:44 +0000583 if (TypeSourceInfo *TSInfo = ND->getResultTypeSourceInfo())
584 if (Visit(TSInfo->getTypeLoc()))
585 return true;
586
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000587 for (ObjCMethodDecl::param_iterator P = ND->param_begin(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000588 PEnd = ND->param_end();
589 P != PEnd; ++P) {
590 if (Visit(MakeCXCursor(*P, TU)))
591 return true;
592 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000593
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000594 if (ND->isThisDeclarationADefinition() &&
595 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
596 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000597
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000598 return false;
599}
600
Douglas Gregora59e3902010-01-21 23:27:09 +0000601bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
602 return VisitDeclContext(D);
603}
604
Douglas Gregorb1373d02010-01-20 20:59:29 +0000605bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000606 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
607 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000608 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000609
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000610 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
611 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
612 E = ND->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000613 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000614 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000615
Douglas Gregora59e3902010-01-21 23:27:09 +0000616 return VisitObjCContainerDecl(ND);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000617}
618
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000619bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
620 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
621 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
622 E = PID->protocol_end(); I != E; ++I, ++PL)
623 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
624 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000625
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000626 return VisitObjCContainerDecl(PID);
627}
628
Douglas Gregorb1373d02010-01-20 20:59:29 +0000629bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000630 // Issue callbacks for super class.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000631 if (D->getSuperClass() &&
632 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000633 D->getSuperClassLoc(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000634 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000635 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000636
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000637 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
638 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
639 E = D->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000640 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000641 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000642
Douglas Gregora59e3902010-01-21 23:27:09 +0000643 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000644}
645
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000646bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
647 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000648}
649
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000650bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
Ted Kremenekebfa3392010-03-19 20:39:03 +0000651 // 'ID' could be null when dealing with invalid code.
652 if (ObjCInterfaceDecl *ID = D->getClassInterface())
653 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
654 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000655
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000656 return VisitObjCImplDecl(D);
657}
658
659bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
660#if 0
661 // Issue callbacks for super class.
662 // FIXME: No source location information!
663 if (D->getSuperClass() &&
664 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000665 D->getSuperClassLoc(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000666 TU)))
667 return true;
668#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000669
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000670 return VisitObjCImplDecl(D);
671}
672
673bool CursorVisitor::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D) {
674 ObjCForwardProtocolDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
675 for (ObjCForwardProtocolDecl::protocol_iterator I = D->protocol_begin(),
676 E = D->protocol_end();
677 I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000678 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000679 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000680
681 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000682}
683
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000684bool CursorVisitor::VisitObjCClassDecl(ObjCClassDecl *D) {
685 for (ObjCClassDecl::iterator C = D->begin(), CEnd = D->end(); C != CEnd; ++C)
686 if (Visit(MakeCursorObjCClassRef(C->getInterface(), C->getLocation(), TU)))
687 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000688
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000689 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000690}
691
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000692bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
693 ASTContext &Context = TU->getASTContext();
694
695 // Some builtin types (such as Objective-C's "id", "sel", and
696 // "Class") have associated declarations. Create cursors for those.
697 QualType VisitType;
698 switch (TL.getType()->getAs<BuiltinType>()->getKind()) {
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000699 case BuiltinType::Void:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000700 case BuiltinType::Bool:
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000701 case BuiltinType::Char_U:
702 case BuiltinType::UChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000703 case BuiltinType::Char16:
704 case BuiltinType::Char32:
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000705 case BuiltinType::UShort:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000706 case BuiltinType::UInt:
707 case BuiltinType::ULong:
708 case BuiltinType::ULongLong:
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000709 case BuiltinType::UInt128:
710 case BuiltinType::Char_S:
711 case BuiltinType::SChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000712 case BuiltinType::WChar:
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000713 case BuiltinType::Short:
714 case BuiltinType::Int:
715 case BuiltinType::Long:
716 case BuiltinType::LongLong:
717 case BuiltinType::Int128:
718 case BuiltinType::Float:
719 case BuiltinType::Double:
720 case BuiltinType::LongDouble:
721 case BuiltinType::NullPtr:
722 case BuiltinType::Overload:
723 case BuiltinType::Dependent:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000724 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000725
726 case BuiltinType::UndeducedAuto: // FIXME: Deserves a cursor?
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000727 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000728
Ted Kremenekc4174cc2010-02-18 18:52:18 +0000729 case BuiltinType::ObjCId:
730 VisitType = Context.getObjCIdType();
731 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000732
733 case BuiltinType::ObjCClass:
734 VisitType = Context.getObjCClassType();
735 break;
736
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000737 case BuiltinType::ObjCSel:
738 VisitType = Context.getObjCSelType();
739 break;
740 }
741
742 if (!VisitType.isNull()) {
743 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000744 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000745 TU));
746 }
747
748 return false;
749}
750
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000751bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
752 return Visit(MakeCursorTypeRef(TL.getTypedefDecl(), TL.getNameLoc(), TU));
753}
754
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000755bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
756 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
757}
758
759bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
760 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
761}
762
763bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
764 if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
765 return true;
766
767 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
768 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
769 TU)))
770 return true;
771 }
772
773 return false;
774}
775
776bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
777 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseTypeLoc()))
778 return true;
779
780 if (TL.hasProtocolsAsWritten()) {
781 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000782 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I),
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000783 TL.getProtocolLoc(I),
784 TU)))
785 return true;
786 }
787 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000788
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000789 return false;
790}
791
792bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
793 return Visit(TL.getPointeeLoc());
794}
795
796bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
797 return Visit(TL.getPointeeLoc());
798}
799
800bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
801 return Visit(TL.getPointeeLoc());
802}
803
804bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000805 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000806}
807
808bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000809 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000810}
811
812bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
813 if (Visit(TL.getResultLoc()))
814 return true;
815
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000816 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
Ted Kremenek5dbacb42010-04-07 00:27:13 +0000817 if (Decl *D = TL.getArg(I))
818 if (Visit(MakeCXCursor(D, TU)))
819 return true;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000820
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 Gregor28019772010-04-05 23:52:57 +00001000 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
1001 return ASTUnit::LoadFromPCHFile(ast_filename, Diags,
Douglas Gregora88084b2010-02-18 18:08:43 +00001002 CXXIdx->getOnlyLocalDecls(),
1003 0, 0, true);
Steve Naroff600866c2009-08-27 19:51:58 +00001004}
1005
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001006CXTranslationUnit
1007clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
1008 const char *source_filename,
1009 int num_command_line_args,
Douglas Gregor4db64a42010-01-23 00:14:00 +00001010 const char **command_line_args,
1011 unsigned num_unsaved_files,
Douglas Gregora88084b2010-02-18 18:08:43 +00001012 struct CXUnsavedFile *unsaved_files) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001013 if (!CIdx)
1014 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001015
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001016 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
1017
Douglas Gregor5352ac02010-01-28 00:27:43 +00001018 // Configure the diagnostics.
1019 DiagnosticOptions DiagOpts;
Douglas Gregor28019772010-04-05 23:52:57 +00001020 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
1021 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001022
Douglas Gregor4db64a42010-01-23 00:14:00 +00001023 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
1024 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattnera0a270c2010-04-05 22:42:27 +00001025 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001026 const llvm::MemoryBuffer *Buffer
Chris Lattnera0a270c2010-04-05 22:42:27 +00001027 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregor4db64a42010-01-23 00:14:00 +00001028 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
1029 Buffer));
1030 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001031
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001032 if (!CXXIdx->getUseExternalASTGeneration()) {
1033 llvm::SmallVector<const char *, 16> Args;
1034
1035 // The 'source_filename' argument is optional. If the caller does not
1036 // specify it then it is assumed that the source file is specified
1037 // in the actual argument list.
1038 if (source_filename)
1039 Args.push_back(source_filename);
1040 Args.insert(Args.end(), command_line_args,
1041 command_line_args + num_command_line_args);
Douglas Gregor94dc8f62010-03-19 16:15:56 +00001042 Args.push_back("-Xclang");
1043 Args.push_back("-detailed-preprocessing-record");
Douglas Gregor5352ac02010-01-28 00:27:43 +00001044 unsigned NumErrors = Diags->getNumErrors();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001045
Ted Kremenek29b72842010-01-07 22:49:05 +00001046#ifdef USE_CRASHTRACER
1047 ArgsCrashTracerInfo ACTI(Args);
Ted Kremenek8a8da7d2010-01-06 03:42:32 +00001048#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001049
Daniel Dunbar94220972009-12-05 02:17:18 +00001050 llvm::OwningPtr<ASTUnit> Unit(
1051 ASTUnit::LoadFromCommandLine(Args.data(), Args.data() + Args.size(),
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001052 Diags,
Daniel Dunbar869824e2009-12-13 03:46:13 +00001053 CXXIdx->getClangResourcesPath(),
Daniel Dunbar94220972009-12-05 02:17:18 +00001054 CXXIdx->getOnlyLocalDecls(),
Douglas Gregor4db64a42010-01-23 00:14:00 +00001055 RemappedFiles.data(),
Douglas Gregora88084b2010-02-18 18:08:43 +00001056 RemappedFiles.size(),
Douglas Gregor94dc8f62010-03-19 16:15:56 +00001057 /*CaptureDiagnostics=*/true));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001058
Daniel Dunbar94220972009-12-05 02:17:18 +00001059 // FIXME: Until we have broader testing, just drop the entire AST if we
1060 // encountered an error.
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001061 if (NumErrors != Diags->getNumErrors()) {
Ted Kremenek34f6a322010-03-05 22:43:29 +00001062 // Make sure to check that 'Unit' is non-NULL.
1063 if (CXXIdx->getDisplayDiagnostics() && Unit.get()) {
Douglas Gregor405634b2010-04-05 18:10:21 +00001064 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
1065 DEnd = Unit->stored_diag_end();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001066 D != DEnd; ++D) {
1067 CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOptions());
Douglas Gregor274f1902010-02-22 23:17:23 +00001068 CXString Msg = clang_formatDiagnostic(&Diag,
1069 clang_defaultDiagnosticDisplayOptions());
1070 fprintf(stderr, "%s\n", clang_getCString(Msg));
1071 clang_disposeString(Msg);
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001072 }
Douglas Gregor274f1902010-02-22 23:17:23 +00001073#ifdef LLVM_ON_WIN32
1074 // On Windows, force a flush, since there may be multiple copies of
1075 // stderr and stdout in the file system, all with different buffers
1076 // but writing to the same device.
1077 fflush(stderr);
Ted Kremenek83c51842010-03-26 01:34:51 +00001078#endif
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001079 }
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001080 }
Daniel Dunbar94220972009-12-05 02:17:18 +00001081
1082 return Unit.take();
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001083 }
1084
Ted Kremenek139ba862009-10-22 00:03:57 +00001085 // Build up the arguments for invoking 'clang'.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001086 std::vector<const char *> argv;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001087
Ted Kremenek139ba862009-10-22 00:03:57 +00001088 // First add the complete path to the 'clang' executable.
1089 llvm::sys::Path ClangPath = static_cast<CIndexer *>(CIdx)->getClangPath();
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00001090 argv.push_back(ClangPath.c_str());
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001091
Ted Kremenek139ba862009-10-22 00:03:57 +00001092 // Add the '-emit-ast' option as our execution mode for 'clang'.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001093 argv.push_back("-emit-ast");
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001094
Ted Kremenek139ba862009-10-22 00:03:57 +00001095 // The 'source_filename' argument is optional. If the caller does not
1096 // specify it then it is assumed that the source file is specified
1097 // in the actual argument list.
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001098 if (source_filename)
1099 argv.push_back(source_filename);
Ted Kremenek139ba862009-10-22 00:03:57 +00001100
Steve Naroff37b5ac22009-10-15 20:50:09 +00001101 // Generate a temporary name for the AST file.
Ted Kremenek139ba862009-10-22 00:03:57 +00001102 argv.push_back("-o");
Benjamin Kramerc2a98162010-03-13 21:22:49 +00001103 char astTmpFile[L_tmpnam];
1104 argv.push_back(tmpnam(astTmpFile));
Ted Kremenek139ba862009-10-22 00:03:57 +00001105
Douglas Gregor4db64a42010-01-23 00:14:00 +00001106 // Remap any unsaved files to temporary files.
1107 std::vector<llvm::sys::Path> TemporaryFiles;
1108 std::vector<std::string> RemapArgs;
1109 if (RemapFiles(num_unsaved_files, unsaved_files, RemapArgs, TemporaryFiles))
1110 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001111
Douglas Gregor4db64a42010-01-23 00:14:00 +00001112 // The pointers into the elements of RemapArgs are stable because we
1113 // won't be adding anything to RemapArgs after this point.
1114 for (unsigned i = 0, e = RemapArgs.size(); i != e; ++i)
1115 argv.push_back(RemapArgs[i].c_str());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001116
Ted Kremenek139ba862009-10-22 00:03:57 +00001117 // Process the compiler options, stripping off '-o', '-c', '-fsyntax-only'.
1118 for (int i = 0; i < num_command_line_args; ++i)
1119 if (const char *arg = command_line_args[i]) {
1120 if (strcmp(arg, "-o") == 0) {
1121 ++i; // Also skip the matching argument.
1122 continue;
1123 }
1124 if (strcmp(arg, "-emit-ast") == 0 ||
1125 strcmp(arg, "-c") == 0 ||
1126 strcmp(arg, "-fsyntax-only") == 0) {
1127 continue;
1128 }
1129
1130 // Keep the argument.
1131 argv.push_back(arg);
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001132 }
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001133
Douglas Gregord93256e2010-01-28 06:00:51 +00001134 // Generate a temporary name for the diagnostics file.
Benjamin Kramerc2a98162010-03-13 21:22:49 +00001135 char tmpFileResults[L_tmpnam];
1136 char *tmpResultsFileName = tmpnam(tmpFileResults);
1137 llvm::sys::Path DiagnosticsFile(tmpResultsFileName);
Douglas Gregord93256e2010-01-28 06:00:51 +00001138 TemporaryFiles.push_back(DiagnosticsFile);
1139 argv.push_back("-fdiagnostics-binary");
1140
Douglas Gregor94dc8f62010-03-19 16:15:56 +00001141 argv.push_back("-Xclang");
1142 argv.push_back("-detailed-preprocessing-record");
1143
Ted Kremenek139ba862009-10-22 00:03:57 +00001144 // Add the null terminator.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001145 argv.push_back(NULL);
1146
Ted Kremenekfeb15e32009-10-26 22:14:08 +00001147 // Invoke 'clang'.
1148 llvm::sys::Path DevNull; // leave empty, causes redirection to /dev/null
1149 // on Unix or NUL (Windows).
Ted Kremenek379afec2009-10-22 03:24:01 +00001150 std::string ErrMsg;
Douglas Gregord93256e2010-01-28 06:00:51 +00001151 const llvm::sys::Path *Redirects[] = { &DevNull, &DevNull, &DiagnosticsFile,
1152 NULL };
Ted Kremenek379afec2009-10-22 03:24:01 +00001153 llvm::sys::Program::ExecuteAndWait(ClangPath, &argv[0], /* env */ NULL,
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001154 /* redirects */ &Redirects[0],
Ted Kremenek379afec2009-10-22 03:24:01 +00001155 /* secondsToWait */ 0, /* memoryLimits */ 0, &ErrMsg);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001156
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001157 if (!ErrMsg.empty()) {
1158 std::string AllArgs;
Ted Kremenek379afec2009-10-22 03:24:01 +00001159 for (std::vector<const char*>::iterator I = argv.begin(), E = argv.end();
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001160 I != E; ++I) {
1161 AllArgs += ' ';
Ted Kremenek779e5f42009-10-26 22:08:39 +00001162 if (*I)
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001163 AllArgs += *I;
Ted Kremenek779e5f42009-10-26 22:08:39 +00001164 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001165
Daniel Dunbar32141c82010-02-23 20:23:45 +00001166 Diags->Report(diag::err_fe_invoking) << AllArgs << ErrMsg;
Ted Kremenek379afec2009-10-22 03:24:01 +00001167 }
Benjamin Kramer0829a832009-10-18 11:19:36 +00001168
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001169 ASTUnit *ATU = ASTUnit::LoadFromPCHFile(astTmpFile, Diags,
Douglas Gregor4db64a42010-01-23 00:14:00 +00001170 CXXIdx->getOnlyLocalDecls(),
Douglas Gregor4db64a42010-01-23 00:14:00 +00001171 RemappedFiles.data(),
Douglas Gregora88084b2010-02-18 18:08:43 +00001172 RemappedFiles.size(),
1173 /*CaptureDiagnostics=*/true);
Douglas Gregora88084b2010-02-18 18:08:43 +00001174 if (ATU) {
1175 LoadSerializedDiagnostics(DiagnosticsFile,
1176 num_unsaved_files, unsaved_files,
1177 ATU->getFileManager(),
1178 ATU->getSourceManager(),
Douglas Gregor405634b2010-04-05 18:10:21 +00001179 ATU->getStoredDiagnostics());
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001180 } else if (CXXIdx->getDisplayDiagnostics()) {
1181 // We failed to load the ASTUnit, but we can still deserialize the
1182 // diagnostics and emit them.
1183 FileManager FileMgr;
Douglas Gregorf715ca12010-03-16 00:06:06 +00001184 Diagnostic Diag;
1185 SourceManager SourceMgr(Diag);
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001186 // FIXME: Faked LangOpts!
1187 LangOptions LangOpts;
1188 llvm::SmallVector<StoredDiagnostic, 4> Diags;
1189 LoadSerializedDiagnostics(DiagnosticsFile,
1190 num_unsaved_files, unsaved_files,
1191 FileMgr, SourceMgr, Diags);
1192 for (llvm::SmallVector<StoredDiagnostic, 4>::iterator D = Diags.begin(),
1193 DEnd = Diags.end();
1194 D != DEnd; ++D) {
1195 CXStoredDiagnostic Diag(*D, LangOpts);
Douglas Gregor274f1902010-02-22 23:17:23 +00001196 CXString Msg = clang_formatDiagnostic(&Diag,
1197 clang_defaultDiagnosticDisplayOptions());
1198 fprintf(stderr, "%s\n", clang_getCString(Msg));
1199 clang_disposeString(Msg);
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001200 }
Douglas Gregor274f1902010-02-22 23:17:23 +00001201
1202#ifdef LLVM_ON_WIN32
1203 // On Windows, force a flush, since there may be multiple copies of
1204 // stderr and stdout in the file system, all with different buffers
1205 // but writing to the same device.
1206 fflush(stderr);
1207#endif
Douglas Gregora88084b2010-02-18 18:08:43 +00001208 }
Douglas Gregord93256e2010-01-28 06:00:51 +00001209
Douglas Gregor313e26c2010-02-18 23:35:40 +00001210 if (ATU) {
1211 // Make the translation unit responsible for destroying all temporary files.
1212 for (unsigned i = 0, e = TemporaryFiles.size(); i != e; ++i)
1213 ATU->addTemporaryFile(TemporaryFiles[i]);
1214 ATU->addTemporaryFile(llvm::sys::Path(ATU->getPCHFileName()));
1215 } else {
1216 // Destroy all of the temporary files now; they can't be referenced any
1217 // longer.
1218 llvm::sys::Path(astTmpFile).eraseFromDisk();
1219 for (unsigned i = 0, e = TemporaryFiles.size(); i != e; ++i)
1220 TemporaryFiles[i].eraseFromDisk();
1221 }
1222
Steve Naroffe19944c2009-10-15 22:23:48 +00001223 return ATU;
Steve Naroff5b7d8e22009-10-15 20:04:39 +00001224}
1225
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001226void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001227 if (CTUnit)
1228 delete static_cast<ASTUnit *>(CTUnit);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00001229}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001230
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001231CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001232 if (!CTUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001233 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001234
Steve Naroff77accc12009-09-03 18:19:54 +00001235 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001236 return createCXString(CXXUnit->getOriginalSourceFileName(), true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +00001237}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +00001238
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001239CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001240 CXCursor Result = { CXCursor_TranslationUnit, { 0, 0, TU } };
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001241 return Result;
1242}
1243
Ted Kremenekfb480492010-01-13 21:46:36 +00001244} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +00001245
Ted Kremenekfb480492010-01-13 21:46:36 +00001246//===----------------------------------------------------------------------===//
Douglas Gregor1db19de2010-01-19 21:36:55 +00001247// CXSourceLocation and CXSourceRange Operations.
1248//===----------------------------------------------------------------------===//
1249
Douglas Gregorb9790342010-01-22 21:44:22 +00001250extern "C" {
1251CXSourceLocation clang_getNullLocation() {
Douglas Gregor5352ac02010-01-28 00:27:43 +00001252 CXSourceLocation Result = { { 0, 0 }, 0 };
Douglas Gregorb9790342010-01-22 21:44:22 +00001253 return Result;
1254}
1255
1256unsigned clang_equalLocations(CXSourceLocation loc1, CXSourceLocation loc2) {
Daniel Dunbar90a6b9e2010-01-30 23:58:27 +00001257 return (loc1.ptr_data[0] == loc2.ptr_data[0] &&
1258 loc1.ptr_data[1] == loc2.ptr_data[1] &&
1259 loc1.int_data == loc2.int_data);
Douglas Gregorb9790342010-01-22 21:44:22 +00001260}
1261
1262CXSourceLocation clang_getLocation(CXTranslationUnit tu,
1263 CXFile file,
1264 unsigned line,
1265 unsigned column) {
1266 if (!tu)
1267 return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001268
Douglas Gregorb9790342010-01-22 21:44:22 +00001269 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
1270 SourceLocation SLoc
1271 = CXXUnit->getSourceManager().getLocation(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001272 static_cast<const FileEntry *>(file),
Douglas Gregorb9790342010-01-22 21:44:22 +00001273 line, column);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001274
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00001275 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
Douglas Gregorb9790342010-01-22 21:44:22 +00001276}
1277
Douglas Gregor5352ac02010-01-28 00:27:43 +00001278CXSourceRange clang_getNullRange() {
1279 CXSourceRange Result = { { 0, 0 }, 0, 0 };
1280 return Result;
1281}
Daniel Dunbard52864b2010-02-14 10:02:57 +00001282
Douglas Gregor5352ac02010-01-28 00:27:43 +00001283CXSourceRange clang_getRange(CXSourceLocation begin, CXSourceLocation end) {
1284 if (begin.ptr_data[0] != end.ptr_data[0] ||
1285 begin.ptr_data[1] != end.ptr_data[1])
1286 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001287
1288 CXSourceRange Result = { { begin.ptr_data[0], begin.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00001289 begin.int_data, end.int_data };
Douglas Gregorb9790342010-01-22 21:44:22 +00001290 return Result;
1291}
1292
Douglas Gregor46766dc2010-01-26 19:19:08 +00001293void clang_getInstantiationLocation(CXSourceLocation location,
1294 CXFile *file,
1295 unsigned *line,
1296 unsigned *column,
1297 unsigned *offset) {
Douglas Gregor1db19de2010-01-19 21:36:55 +00001298 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
1299
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00001300 if (!location.ptr_data[0] || Loc.isInvalid()) {
Douglas Gregor46766dc2010-01-26 19:19:08 +00001301 if (file)
1302 *file = 0;
1303 if (line)
1304 *line = 0;
1305 if (column)
1306 *column = 0;
1307 if (offset)
1308 *offset = 0;
1309 return;
1310 }
1311
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00001312 const SourceManager &SM =
1313 *static_cast<const SourceManager*>(location.ptr_data[0]);
Douglas Gregor1db19de2010-01-19 21:36:55 +00001314 SourceLocation InstLoc = SM.getInstantiationLoc(Loc);
Douglas Gregor1db19de2010-01-19 21:36:55 +00001315
1316 if (file)
1317 *file = (void *)SM.getFileEntryForID(SM.getFileID(InstLoc));
1318 if (line)
1319 *line = SM.getInstantiationLineNumber(InstLoc);
1320 if (column)
1321 *column = SM.getInstantiationColumnNumber(InstLoc);
Douglas Gregore69517c2010-01-26 03:07:15 +00001322 if (offset)
Douglas Gregor46766dc2010-01-26 19:19:08 +00001323 *offset = SM.getDecomposedLoc(InstLoc).second;
Douglas Gregore69517c2010-01-26 03:07:15 +00001324}
1325
Douglas Gregor1db19de2010-01-19 21:36:55 +00001326CXSourceLocation clang_getRangeStart(CXSourceRange range) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001327 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00001328 range.begin_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00001329 return Result;
1330}
1331
1332CXSourceLocation clang_getRangeEnd(CXSourceRange range) {
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00001333 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00001334 range.end_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00001335 return Result;
1336}
1337
Douglas Gregorb9790342010-01-22 21:44:22 +00001338} // end: extern "C"
1339
Douglas Gregor1db19de2010-01-19 21:36:55 +00001340//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00001341// CXFile Operations.
1342//===----------------------------------------------------------------------===//
1343
1344extern "C" {
Ted Kremenek74844072010-02-17 00:41:20 +00001345CXString clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00001346 if (!SFile)
Ted Kremenek74844072010-02-17 00:41:20 +00001347 return createCXString(NULL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001348
Steve Naroff88145032009-10-27 14:35:18 +00001349 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Ted Kremenek74844072010-02-17 00:41:20 +00001350 return createCXString(FEnt->getName());
Steve Naroff88145032009-10-27 14:35:18 +00001351}
1352
1353time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00001354 if (!SFile)
1355 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001356
Steve Naroff88145032009-10-27 14:35:18 +00001357 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
1358 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +00001359}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001360
Douglas Gregorb9790342010-01-22 21:44:22 +00001361CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
1362 if (!tu)
1363 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001364
Douglas Gregorb9790342010-01-22 21:44:22 +00001365 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001366
Douglas Gregorb9790342010-01-22 21:44:22 +00001367 FileManager &FMgr = CXXUnit->getFileManager();
1368 const FileEntry *File = FMgr.getFile(file_name, file_name+strlen(file_name));
1369 return const_cast<FileEntry *>(File);
1370}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001371
Ted Kremenekfb480492010-01-13 21:46:36 +00001372} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +00001373
Ted Kremenekfb480492010-01-13 21:46:36 +00001374//===----------------------------------------------------------------------===//
1375// CXCursor Operations.
1376//===----------------------------------------------------------------------===//
1377
Ted Kremenekfb480492010-01-13 21:46:36 +00001378static Decl *getDeclFromExpr(Stmt *E) {
1379 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
1380 return RefExpr->getDecl();
1381 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
1382 return ME->getMemberDecl();
1383 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
1384 return RE->getDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001385
Ted Kremenekfb480492010-01-13 21:46:36 +00001386 if (CallExpr *CE = dyn_cast<CallExpr>(E))
1387 return getDeclFromExpr(CE->getCallee());
1388 if (CastExpr *CE = dyn_cast<CastExpr>(E))
1389 return getDeclFromExpr(CE->getSubExpr());
1390 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
1391 return OME->getMethodDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001392
Ted Kremenekfb480492010-01-13 21:46:36 +00001393 return 0;
1394}
1395
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00001396static SourceLocation getLocationFromExpr(Expr *E) {
1397 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
1398 return /*FIXME:*/Msg->getLeftLoc();
1399 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
1400 return DRE->getLocation();
1401 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
1402 return Member->getMemberLoc();
1403 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
1404 return Ivar->getLocation();
1405 return E->getLocStart();
1406}
1407
Ted Kremenekfb480492010-01-13 21:46:36 +00001408extern "C" {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001409
1410unsigned clang_visitChildren(CXCursor parent,
Douglas Gregorb1373d02010-01-20 20:59:29 +00001411 CXCursorVisitor visitor,
1412 CXClientData client_data) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001413 ASTUnit *CXXUnit = getCursorASTUnit(parent);
Douglas Gregorb1373d02010-01-20 20:59:29 +00001414
1415 unsigned PCHLevel = Decl::MaxPCHLevel;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001416
Douglas Gregorb1373d02010-01-20 20:59:29 +00001417 // Set the PCHLevel to filter out unwanted decls if requested.
1418 if (CXXUnit->getOnlyLocalDecls()) {
1419 PCHLevel = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001420
Douglas Gregorb1373d02010-01-20 20:59:29 +00001421 // If the main input was an AST, bump the level.
1422 if (CXXUnit->isMainFileAST())
1423 ++PCHLevel;
1424 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001425
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001426 CursorVisitor CursorVis(CXXUnit, visitor, client_data, PCHLevel);
Douglas Gregorb1373d02010-01-20 20:59:29 +00001427 return CursorVis.VisitChildren(parent);
1428}
1429
Douglas Gregor78205d42010-01-20 21:45:58 +00001430static CXString getDeclSpelling(Decl *D) {
1431 NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
1432 if (!ND)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001433 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001434
Douglas Gregor78205d42010-01-20 21:45:58 +00001435 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001436 return createCXString(OMD->getSelector().getAsString());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001437
Douglas Gregor78205d42010-01-20 21:45:58 +00001438 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
1439 // No, this isn't the same as the code below. getIdentifier() is non-virtual
1440 // and returns different names. NamedDecl returns the class name and
1441 // ObjCCategoryImplDecl returns the category name.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001442 return createCXString(CIMP->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001443
Douglas Gregor78205d42010-01-20 21:45:58 +00001444 if (ND->getIdentifier())
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001445 return createCXString(ND->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001446
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001447 return createCXString("");
Douglas Gregor78205d42010-01-20 21:45:58 +00001448}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001449
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001450CXString clang_getCursorSpelling(CXCursor C) {
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001451 if (clang_isTranslationUnit(C.kind))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001452 return clang_getTranslationUnitSpelling(C.data[2]);
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001453
Steve Narofff334b4e2009-09-02 18:26:48 +00001454 if (clang_isReference(C.kind)) {
1455 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00001456 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +00001457 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001458 return createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00001459 }
1460 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +00001461 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001462 return createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00001463 }
1464 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +00001465 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +00001466 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001467 return createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00001468 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001469 case CXCursor_TypeRef: {
1470 TypeDecl *Type = getCursorTypeRef(C).first;
1471 assert(Type && "Missing type decl");
1472
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001473 return createCXString(getCursorContext(C).getTypeDeclType(Type).
1474 getAsString());
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001475 }
1476
Daniel Dunbaracca7252009-11-30 20:42:49 +00001477 default:
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001478 return createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +00001479 }
1480 }
Douglas Gregor97b98722010-01-19 23:20:36 +00001481
1482 if (clang_isExpression(C.kind)) {
1483 Decl *D = getDeclFromExpr(getCursorExpr(C));
1484 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +00001485 return getDeclSpelling(D);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001486 return createCXString("");
Douglas Gregor97b98722010-01-19 23:20:36 +00001487 }
1488
Douglas Gregor4ae8f292010-03-18 17:52:52 +00001489 if (C.kind == CXCursor_MacroInstantiation)
1490 return createCXString(getCursorMacroInstantiation(C)->getName()
1491 ->getNameStart());
1492
Douglas Gregor572feb22010-03-18 18:04:21 +00001493 if (C.kind == CXCursor_MacroDefinition)
1494 return createCXString(getCursorMacroDefinition(C)->getName()
1495 ->getNameStart());
1496
Douglas Gregor60cbfac2010-01-25 16:56:17 +00001497 if (clang_isDeclaration(C.kind))
1498 return getDeclSpelling(getCursorDecl(C));
Ted Kremeneke68fff62010-02-17 00:41:32 +00001499
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001500 return createCXString("");
Steve Narofff334b4e2009-09-02 18:26:48 +00001501}
1502
Ted Kremeneke68fff62010-02-17 00:41:32 +00001503CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00001504 switch (Kind) {
Ted Kremeneke68fff62010-02-17 00:41:32 +00001505 case CXCursor_FunctionDecl:
1506 return createCXString("FunctionDecl");
1507 case CXCursor_TypedefDecl:
1508 return createCXString("TypedefDecl");
1509 case CXCursor_EnumDecl:
1510 return createCXString("EnumDecl");
1511 case CXCursor_EnumConstantDecl:
1512 return createCXString("EnumConstantDecl");
1513 case CXCursor_StructDecl:
1514 return createCXString("StructDecl");
1515 case CXCursor_UnionDecl:
1516 return createCXString("UnionDecl");
1517 case CXCursor_ClassDecl:
1518 return createCXString("ClassDecl");
1519 case CXCursor_FieldDecl:
1520 return createCXString("FieldDecl");
1521 case CXCursor_VarDecl:
1522 return createCXString("VarDecl");
1523 case CXCursor_ParmDecl:
1524 return createCXString("ParmDecl");
1525 case CXCursor_ObjCInterfaceDecl:
1526 return createCXString("ObjCInterfaceDecl");
1527 case CXCursor_ObjCCategoryDecl:
1528 return createCXString("ObjCCategoryDecl");
1529 case CXCursor_ObjCProtocolDecl:
1530 return createCXString("ObjCProtocolDecl");
1531 case CXCursor_ObjCPropertyDecl:
1532 return createCXString("ObjCPropertyDecl");
1533 case CXCursor_ObjCIvarDecl:
1534 return createCXString("ObjCIvarDecl");
1535 case CXCursor_ObjCInstanceMethodDecl:
1536 return createCXString("ObjCInstanceMethodDecl");
1537 case CXCursor_ObjCClassMethodDecl:
1538 return createCXString("ObjCClassMethodDecl");
1539 case CXCursor_ObjCImplementationDecl:
1540 return createCXString("ObjCImplementationDecl");
1541 case CXCursor_ObjCCategoryImplDecl:
1542 return createCXString("ObjCCategoryImplDecl");
1543 case CXCursor_UnexposedDecl:
1544 return createCXString("UnexposedDecl");
1545 case CXCursor_ObjCSuperClassRef:
1546 return createCXString("ObjCSuperClassRef");
1547 case CXCursor_ObjCProtocolRef:
1548 return createCXString("ObjCProtocolRef");
1549 case CXCursor_ObjCClassRef:
1550 return createCXString("ObjCClassRef");
1551 case CXCursor_TypeRef:
1552 return createCXString("TypeRef");
1553 case CXCursor_UnexposedExpr:
1554 return createCXString("UnexposedExpr");
1555 case CXCursor_DeclRefExpr:
1556 return createCXString("DeclRefExpr");
1557 case CXCursor_MemberRefExpr:
1558 return createCXString("MemberRefExpr");
1559 case CXCursor_CallExpr:
1560 return createCXString("CallExpr");
1561 case CXCursor_ObjCMessageExpr:
1562 return createCXString("ObjCMessageExpr");
1563 case CXCursor_UnexposedStmt:
1564 return createCXString("UnexposedStmt");
1565 case CXCursor_InvalidFile:
1566 return createCXString("InvalidFile");
Ted Kremenek292db642010-03-19 20:39:05 +00001567 case CXCursor_InvalidCode:
1568 return createCXString("InvalidCode");
Ted Kremeneke68fff62010-02-17 00:41:32 +00001569 case CXCursor_NoDeclFound:
1570 return createCXString("NoDeclFound");
1571 case CXCursor_NotImplemented:
1572 return createCXString("NotImplemented");
1573 case CXCursor_TranslationUnit:
1574 return createCXString("TranslationUnit");
Ted Kremeneke77f4432010-02-18 03:09:07 +00001575 case CXCursor_UnexposedAttr:
1576 return createCXString("UnexposedAttr");
1577 case CXCursor_IBActionAttr:
1578 return createCXString("attribute(ibaction)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00001579 case CXCursor_IBOutletAttr:
1580 return createCXString("attribute(iboutlet)");
1581 case CXCursor_PreprocessingDirective:
1582 return createCXString("preprocessing directive");
Douglas Gregor572feb22010-03-18 18:04:21 +00001583 case CXCursor_MacroDefinition:
1584 return createCXString("macro definition");
Douglas Gregor48072312010-03-18 15:23:44 +00001585 case CXCursor_MacroInstantiation:
1586 return createCXString("macro instantiation");
Steve Naroff89922f82009-08-31 00:59:03 +00001587 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00001588
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00001589 llvm_unreachable("Unhandled CXCursorKind");
Ted Kremeneke68fff62010-02-17 00:41:32 +00001590 return createCXString(NULL);
Steve Naroff600866c2009-08-27 19:51:58 +00001591}
Steve Naroff89922f82009-08-31 00:59:03 +00001592
Ted Kremeneke68fff62010-02-17 00:41:32 +00001593enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
1594 CXCursor parent,
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001595 CXClientData client_data) {
1596 CXCursor *BestCursor = static_cast<CXCursor *>(client_data);
1597 *BestCursor = cursor;
1598 return CXChildVisit_Recurse;
1599}
Ted Kremeneke68fff62010-02-17 00:41:32 +00001600
Douglas Gregorb9790342010-01-22 21:44:22 +00001601CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
1602 if (!TU)
Ted Kremenekf4629892010-01-14 01:51:23 +00001603 return clang_getNullCursor();
Ted Kremeneke68fff62010-02-17 00:41:32 +00001604
Douglas Gregorb9790342010-01-22 21:44:22 +00001605 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
1606
Douglas Gregorbdf60622010-03-05 21:16:25 +00001607 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
1608
Ted Kremeneka297de22010-01-25 22:34:44 +00001609 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001610 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
1611 if (SLoc.isValid()) {
Daniel Dunbard52864b2010-02-14 10:02:57 +00001612 SourceRange RegionOfInterest(SLoc, SLoc.getFileLocWithOffset(1));
Ted Kremeneke68fff62010-02-17 00:41:32 +00001613
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001614 // FIXME: Would be great to have a "hint" cursor, then walk from that
1615 // hint cursor upward until we find a cursor whose source range encloses
1616 // the region of interest, rather than starting from the translation unit.
1617 CXCursor Parent = clang_getTranslationUnitCursor(CXXUnit);
Ted Kremeneke68fff62010-02-17 00:41:32 +00001618 CursorVisitor CursorVis(CXXUnit, GetCursorVisitor, &Result,
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001619 Decl::MaxPCHLevel, RegionOfInterest);
1620 CursorVis.VisitChildren(Parent);
Steve Naroff77128dd2009-09-15 20:25:34 +00001621 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00001622 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00001623}
1624
Ted Kremenek73885552009-11-17 19:28:59 +00001625CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00001626 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00001627}
1628
1629unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00001630 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00001631}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001632
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001633unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00001634 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
1635}
1636
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001637unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +00001638 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
1639}
Steve Naroff2d4d6292009-08-31 14:26:51 +00001640
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001641unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00001642 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
1643}
1644
Douglas Gregor97b98722010-01-19 23:20:36 +00001645unsigned clang_isExpression(enum CXCursorKind K) {
1646 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
1647}
1648
1649unsigned clang_isStatement(enum CXCursorKind K) {
1650 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
1651}
1652
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001653unsigned clang_isTranslationUnit(enum CXCursorKind K) {
1654 return K == CXCursor_TranslationUnit;
1655}
1656
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00001657unsigned clang_isPreprocessing(enum CXCursorKind K) {
1658 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
1659}
1660
Ted Kremenekad6eff62010-03-08 21:17:29 +00001661unsigned clang_isUnexposed(enum CXCursorKind K) {
1662 switch (K) {
1663 case CXCursor_UnexposedDecl:
1664 case CXCursor_UnexposedExpr:
1665 case CXCursor_UnexposedStmt:
1666 case CXCursor_UnexposedAttr:
1667 return true;
1668 default:
1669 return false;
1670 }
1671}
1672
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001673CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00001674 return C.kind;
1675}
1676
Douglas Gregor98258af2010-01-18 22:46:11 +00001677CXSourceLocation clang_getCursorLocation(CXCursor C) {
1678 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00001679 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001680 case CXCursor_ObjCSuperClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00001681 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1682 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001683 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001684 }
1685
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001686 case CXCursor_ObjCProtocolRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00001687 std::pair<ObjCProtocolDecl *, SourceLocation> P
1688 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001689 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001690 }
1691
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001692 case CXCursor_ObjCClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00001693 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1694 = getCursorObjCClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001695 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001696 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001697
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001698 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001699 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001700 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001701 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001702
Douglas Gregorf46034a2010-01-18 23:41:10 +00001703 default:
1704 // FIXME: Need a way to enumerate all non-reference cases.
1705 llvm_unreachable("Missed a reference kind");
1706 }
Douglas Gregor98258af2010-01-18 22:46:11 +00001707 }
Douglas Gregor97b98722010-01-19 23:20:36 +00001708
1709 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001710 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00001711 getLocationFromExpr(getCursorExpr(C)));
1712
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00001713 if (C.kind == CXCursor_PreprocessingDirective) {
1714 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
1715 return cxloc::translateSourceLocation(getCursorContext(C), L);
1716 }
Douglas Gregor48072312010-03-18 15:23:44 +00001717
1718 if (C.kind == CXCursor_MacroInstantiation) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00001719 SourceLocation L
1720 = cxcursor::getCursorMacroInstantiation(C)->getSourceRange().getBegin();
Douglas Gregor48072312010-03-18 15:23:44 +00001721 return cxloc::translateSourceLocation(getCursorContext(C), L);
1722 }
Douglas Gregor572feb22010-03-18 18:04:21 +00001723
1724 if (C.kind == CXCursor_MacroDefinition) {
1725 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
1726 return cxloc::translateSourceLocation(getCursorContext(C), L);
1727 }
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00001728
Douglas Gregor5352ac02010-01-28 00:27:43 +00001729 if (!getCursorDecl(C))
1730 return clang_getNullLocation();
Douglas Gregor98258af2010-01-18 22:46:11 +00001731
Douglas Gregorf46034a2010-01-18 23:41:10 +00001732 Decl *D = getCursorDecl(C);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001733 SourceLocation Loc = D->getLocation();
1734 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
1735 Loc = Class->getClassLoc();
Douglas Gregor2ca54fe2010-03-22 15:53:50 +00001736 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00001737}
Douglas Gregora7bde202010-01-19 00:34:46 +00001738
1739CXSourceRange clang_getCursorExtent(CXCursor C) {
1740 if (clang_isReference(C.kind)) {
1741 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001742 case CXCursor_ObjCSuperClassRef: {
Douglas Gregora7bde202010-01-19 00:34:46 +00001743 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1744 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001745 return cxloc::translateSourceRange(P.first->getASTContext(), P.second);
Douglas Gregora7bde202010-01-19 00:34:46 +00001746 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001747
1748 case CXCursor_ObjCProtocolRef: {
Douglas Gregora7bde202010-01-19 00:34:46 +00001749 std::pair<ObjCProtocolDecl *, SourceLocation> P
1750 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001751 return cxloc::translateSourceRange(P.first->getASTContext(), P.second);
Douglas Gregora7bde202010-01-19 00:34:46 +00001752 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001753
1754 case CXCursor_ObjCClassRef: {
Douglas Gregora7bde202010-01-19 00:34:46 +00001755 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1756 = getCursorObjCClassRef(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001757
Ted Kremeneka297de22010-01-25 22:34:44 +00001758 return cxloc::translateSourceRange(P.first->getASTContext(), P.second);
Douglas Gregora7bde202010-01-19 00:34:46 +00001759 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001760
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001761 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001762 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001763 return cxloc::translateSourceRange(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001764 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001765
Douglas Gregora7bde202010-01-19 00:34:46 +00001766 default:
1767 // FIXME: Need a way to enumerate all non-reference cases.
1768 llvm_unreachable("Missed a reference kind");
1769 }
1770 }
Douglas Gregor97b98722010-01-19 23:20:36 +00001771
1772 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001773 return cxloc::translateSourceRange(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00001774 getCursorExpr(C)->getSourceRange());
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001775
1776 if (clang_isStatement(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001777 return cxloc::translateSourceRange(getCursorContext(C),
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001778 getCursorStmt(C)->getSourceRange());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001779
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00001780 if (C.kind == CXCursor_PreprocessingDirective) {
1781 SourceRange R = cxcursor::getCursorPreprocessingDirective(C);
1782 return cxloc::translateSourceRange(getCursorContext(C), R);
1783 }
Douglas Gregor48072312010-03-18 15:23:44 +00001784
1785 if (C.kind == CXCursor_MacroInstantiation) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00001786 SourceRange R = cxcursor::getCursorMacroInstantiation(C)->getSourceRange();
Douglas Gregor48072312010-03-18 15:23:44 +00001787 return cxloc::translateSourceRange(getCursorContext(C), R);
1788 }
Douglas Gregor572feb22010-03-18 18:04:21 +00001789
1790 if (C.kind == CXCursor_MacroDefinition) {
1791 SourceRange R = cxcursor::getCursorMacroDefinition(C)->getSourceRange();
1792 return cxloc::translateSourceRange(getCursorContext(C), R);
1793 }
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00001794
Douglas Gregor5352ac02010-01-28 00:27:43 +00001795 if (!getCursorDecl(C))
1796 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001797
Douglas Gregora7bde202010-01-19 00:34:46 +00001798 Decl *D = getCursorDecl(C);
Douglas Gregor2ca54fe2010-03-22 15:53:50 +00001799 return cxloc::translateSourceRange(getCursorContext(C), D->getSourceRange());
Douglas Gregora7bde202010-01-19 00:34:46 +00001800}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001801
1802CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001803 if (clang_isInvalid(C.kind))
1804 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001805
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001806 ASTUnit *CXXUnit = getCursorASTUnit(C);
Douglas Gregorb6998662010-01-19 19:34:47 +00001807 if (clang_isDeclaration(C.kind))
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001808 return C;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001809
Douglas Gregor97b98722010-01-19 23:20:36 +00001810 if (clang_isExpression(C.kind)) {
1811 Decl *D = getDeclFromExpr(getCursorExpr(C));
1812 if (D)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001813 return MakeCXCursor(D, CXXUnit);
Douglas Gregor97b98722010-01-19 23:20:36 +00001814 return clang_getNullCursor();
1815 }
1816
Douglas Gregorbf7efa22010-03-18 18:23:03 +00001817 if (C.kind == CXCursor_MacroInstantiation) {
1818 if (MacroDefinition *Def = getCursorMacroInstantiation(C)->getDefinition())
1819 return MakeMacroDefinitionCursor(Def, CXXUnit);
1820 }
1821
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001822 if (!clang_isReference(C.kind))
1823 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001824
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001825 switch (C.kind) {
1826 case CXCursor_ObjCSuperClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001827 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001828
1829 case CXCursor_ObjCProtocolRef: {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001830 return MakeCXCursor(getCursorObjCProtocolRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001831
1832 case CXCursor_ObjCClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001833 return MakeCXCursor(getCursorObjCClassRef(C).first, CXXUnit);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001834
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001835 case CXCursor_TypeRef:
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001836 return MakeCXCursor(getCursorTypeRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001837
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001838 default:
1839 // We would prefer to enumerate all non-reference cursor kinds here.
1840 llvm_unreachable("Unhandled reference cursor kind");
1841 break;
1842 }
1843 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001844
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001845 return clang_getNullCursor();
1846}
1847
Douglas Gregorb6998662010-01-19 19:34:47 +00001848CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001849 if (clang_isInvalid(C.kind))
1850 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001851
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001852 ASTUnit *CXXUnit = getCursorASTUnit(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001853
Douglas Gregorb6998662010-01-19 19:34:47 +00001854 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00001855 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00001856 C = clang_getCursorReferenced(C);
1857 WasReference = true;
1858 }
1859
Douglas Gregorbf7efa22010-03-18 18:23:03 +00001860 if (C.kind == CXCursor_MacroInstantiation)
1861 return clang_getCursorReferenced(C);
1862
Douglas Gregorb6998662010-01-19 19:34:47 +00001863 if (!clang_isDeclaration(C.kind))
1864 return clang_getNullCursor();
1865
1866 Decl *D = getCursorDecl(C);
1867 if (!D)
1868 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001869
Douglas Gregorb6998662010-01-19 19:34:47 +00001870 switch (D->getKind()) {
1871 // Declaration kinds that don't really separate the notions of
1872 // declaration and definition.
1873 case Decl::Namespace:
1874 case Decl::Typedef:
1875 case Decl::TemplateTypeParm:
1876 case Decl::EnumConstant:
1877 case Decl::Field:
1878 case Decl::ObjCIvar:
1879 case Decl::ObjCAtDefsField:
1880 case Decl::ImplicitParam:
1881 case Decl::ParmVar:
1882 case Decl::NonTypeTemplateParm:
1883 case Decl::TemplateTemplateParm:
1884 case Decl::ObjCCategoryImpl:
1885 case Decl::ObjCImplementation:
1886 case Decl::LinkageSpec:
1887 case Decl::ObjCPropertyImpl:
1888 case Decl::FileScopeAsm:
1889 case Decl::StaticAssert:
1890 case Decl::Block:
1891 return C;
1892
1893 // Declaration kinds that don't make any sense here, but are
1894 // nonetheless harmless.
1895 case Decl::TranslationUnit:
1896 case Decl::Template:
1897 case Decl::ObjCContainer:
1898 break;
1899
1900 // Declaration kinds for which the definition is not resolvable.
1901 case Decl::UnresolvedUsingTypename:
1902 case Decl::UnresolvedUsingValue:
1903 break;
1904
1905 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001906 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
1907 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001908
1909 case Decl::NamespaceAlias:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001910 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001911
1912 case Decl::Enum:
1913 case Decl::Record:
1914 case Decl::CXXRecord:
1915 case Decl::ClassTemplateSpecialization:
1916 case Decl::ClassTemplatePartialSpecialization:
Douglas Gregor952b0172010-02-11 01:04:33 +00001917 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001918 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001919 return clang_getNullCursor();
1920
1921 case Decl::Function:
1922 case Decl::CXXMethod:
1923 case Decl::CXXConstructor:
1924 case Decl::CXXDestructor:
1925 case Decl::CXXConversion: {
1926 const FunctionDecl *Def = 0;
1927 if (cast<FunctionDecl>(D)->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001928 return MakeCXCursor(const_cast<FunctionDecl *>(Def), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001929 return clang_getNullCursor();
1930 }
1931
1932 case Decl::Var: {
Sebastian Redl31310a22010-02-01 20:16:42 +00001933 // Ask the variable if it has a definition.
1934 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
1935 return MakeCXCursor(Def, CXXUnit);
1936 return clang_getNullCursor();
Douglas Gregorb6998662010-01-19 19:34:47 +00001937 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001938
Douglas Gregorb6998662010-01-19 19:34:47 +00001939 case Decl::FunctionTemplate: {
1940 const FunctionDecl *Def = 0;
1941 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001942 return MakeCXCursor(Def->getDescribedFunctionTemplate(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001943 return clang_getNullCursor();
1944 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001945
Douglas Gregorb6998662010-01-19 19:34:47 +00001946 case Decl::ClassTemplate: {
1947 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
Douglas Gregor952b0172010-02-11 01:04:33 +00001948 ->getDefinition())
Douglas Gregorb6998662010-01-19 19:34:47 +00001949 return MakeCXCursor(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001950 cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001951 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001952 return clang_getNullCursor();
1953 }
1954
1955 case Decl::Using: {
1956 UsingDecl *Using = cast<UsingDecl>(D);
1957 CXCursor Def = clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001958 for (UsingDecl::shadow_iterator S = Using->shadow_begin(),
1959 SEnd = Using->shadow_end();
Douglas Gregorb6998662010-01-19 19:34:47 +00001960 S != SEnd; ++S) {
1961 if (Def != clang_getNullCursor()) {
1962 // FIXME: We have no way to return multiple results.
1963 return clang_getNullCursor();
1964 }
1965
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001966 Def = clang_getCursorDefinition(MakeCXCursor((*S)->getTargetDecl(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001967 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00001968 }
1969
1970 return Def;
1971 }
1972
1973 case Decl::UsingShadow:
1974 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001975 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001976 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00001977
1978 case Decl::ObjCMethod: {
1979 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
1980 if (Method->isThisDeclarationADefinition())
1981 return C;
1982
1983 // Dig out the method definition in the associated
1984 // @implementation, if we have it.
1985 // FIXME: The ASTs should make finding the definition easier.
1986 if (ObjCInterfaceDecl *Class
1987 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
1988 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
1989 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
1990 Method->isInstanceMethod()))
1991 if (Def->isThisDeclarationADefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001992 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001993
1994 return clang_getNullCursor();
1995 }
1996
1997 case Decl::ObjCCategory:
1998 if (ObjCCategoryImplDecl *Impl
1999 = cast<ObjCCategoryDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002000 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002001 return clang_getNullCursor();
2002
2003 case Decl::ObjCProtocol:
2004 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
2005 return C;
2006 return clang_getNullCursor();
2007
2008 case Decl::ObjCInterface:
2009 // There are two notions of a "definition" for an Objective-C
2010 // class: the interface and its implementation. When we resolved a
2011 // reference to an Objective-C class, produce the @interface as
2012 // the definition; when we were provided with the interface,
2013 // produce the @implementation as the definition.
2014 if (WasReference) {
2015 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
2016 return C;
2017 } else if (ObjCImplementationDecl *Impl
2018 = cast<ObjCInterfaceDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002019 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002020 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002021
Douglas Gregorb6998662010-01-19 19:34:47 +00002022 case Decl::ObjCProperty:
2023 // FIXME: We don't really know where to find the
2024 // ObjCPropertyImplDecls that implement this property.
2025 return clang_getNullCursor();
2026
2027 case Decl::ObjCCompatibleAlias:
2028 if (ObjCInterfaceDecl *Class
2029 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
2030 if (!Class->isForwardDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002031 return MakeCXCursor(Class, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002032
Douglas Gregorb6998662010-01-19 19:34:47 +00002033 return clang_getNullCursor();
2034
2035 case Decl::ObjCForwardProtocol: {
2036 ObjCForwardProtocolDecl *Forward = cast<ObjCForwardProtocolDecl>(D);
2037 if (Forward->protocol_size() == 1)
2038 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002039 MakeCXCursor(*Forward->protocol_begin(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002040 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002041
2042 // FIXME: Cannot return multiple definitions.
2043 return clang_getNullCursor();
2044 }
2045
2046 case Decl::ObjCClass: {
2047 ObjCClassDecl *Class = cast<ObjCClassDecl>(D);
2048 if (Class->size() == 1) {
2049 ObjCInterfaceDecl *IFace = Class->begin()->getInterface();
2050 if (!IFace->isForwardDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002051 return MakeCXCursor(IFace, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002052 return clang_getNullCursor();
2053 }
2054
2055 // FIXME: Cannot return multiple definitions.
2056 return clang_getNullCursor();
2057 }
2058
2059 case Decl::Friend:
2060 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002061 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002062 return clang_getNullCursor();
2063
2064 case Decl::FriendTemplate:
2065 if (NamedDecl *Friend = cast<FriendTemplateDecl>(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
2070 return clang_getNullCursor();
2071}
2072
2073unsigned clang_isCursorDefinition(CXCursor C) {
2074 if (!clang_isDeclaration(C.kind))
2075 return 0;
2076
2077 return clang_getCursorDefinition(C) == C;
2078}
2079
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002080void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00002081 const char **startBuf,
2082 const char **endBuf,
2083 unsigned *startLine,
2084 unsigned *startColumn,
2085 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002086 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00002087 assert(getCursorDecl(C) && "CXCursor has null decl");
2088 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00002089 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
2090 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002091
Steve Naroff4ade6d62009-09-23 17:52:52 +00002092 SourceManager &SM = FD->getASTContext().getSourceManager();
2093 *startBuf = SM.getCharacterData(Body->getLBracLoc());
2094 *endBuf = SM.getCharacterData(Body->getRBracLoc());
2095 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
2096 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
2097 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
2098 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
2099}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002100
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002101void clang_enableStackTraces(void) {
2102 llvm::sys::PrintStackTraceOnErrorSignal();
2103}
2104
Ted Kremenekfb480492010-01-13 21:46:36 +00002105} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00002106
Ted Kremenekfb480492010-01-13 21:46:36 +00002107//===----------------------------------------------------------------------===//
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002108// Token-based Operations.
2109//===----------------------------------------------------------------------===//
2110
2111/* CXToken layout:
2112 * int_data[0]: a CXTokenKind
2113 * int_data[1]: starting token location
2114 * int_data[2]: token length
2115 * int_data[3]: reserved
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002116 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002117 * otherwise unused.
2118 */
2119extern "C" {
2120
2121CXTokenKind clang_getTokenKind(CXToken CXTok) {
2122 return static_cast<CXTokenKind>(CXTok.int_data[0]);
2123}
2124
2125CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
2126 switch (clang_getTokenKind(CXTok)) {
2127 case CXToken_Identifier:
2128 case CXToken_Keyword:
2129 // We know we have an IdentifierInfo*, so use that.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002130 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
2131 ->getNameStart());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002132
2133 case CXToken_Literal: {
2134 // We have stashed the starting pointer in the ptr_data field. Use it.
2135 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002136 return createCXString(llvm::StringRef(Text, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002137 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002138
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002139 case CXToken_Punctuation:
2140 case CXToken_Comment:
2141 break;
2142 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002143
2144 // We have to find the starting buffer pointer the hard way, by
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002145 // deconstructing the source location.
2146 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2147 if (!CXXUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002148 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002149
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002150 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
2151 std::pair<FileID, unsigned> LocInfo
2152 = CXXUnit->getSourceManager().getDecomposedLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +00002153 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002154 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00002155 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
2156 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00002157 return createCXString("");
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002158
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002159 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002160}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002161
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002162CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
2163 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2164 if (!CXXUnit)
2165 return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002166
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002167 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
2168 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
2169}
2170
2171CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
2172 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregor5352ac02010-01-28 00:27:43 +00002173 if (!CXXUnit)
2174 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002175
2176 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002177 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
2178}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002179
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002180void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
2181 CXToken **Tokens, unsigned *NumTokens) {
2182 if (Tokens)
2183 *Tokens = 0;
2184 if (NumTokens)
2185 *NumTokens = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002186
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002187 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2188 if (!CXXUnit || !Tokens || !NumTokens)
2189 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002190
Douglas Gregorbdf60622010-03-05 21:16:25 +00002191 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
2192
Daniel Dunbar85b988f2010-02-14 08:31:57 +00002193 SourceRange R = cxloc::translateCXSourceRange(Range);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002194 if (R.isInvalid())
2195 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002196
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002197 SourceManager &SourceMgr = CXXUnit->getSourceManager();
2198 std::pair<FileID, unsigned> BeginLocInfo
2199 = SourceMgr.getDecomposedLoc(R.getBegin());
2200 std::pair<FileID, unsigned> EndLocInfo
2201 = SourceMgr.getDecomposedLoc(R.getEnd());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002202
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002203 // Cannot tokenize across files.
2204 if (BeginLocInfo.first != EndLocInfo.first)
2205 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002206
2207 // Create a lexer
Douglas Gregorf715ca12010-03-16 00:06:06 +00002208 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002209 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00002210 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
Douglas Gregor47a3fcd2010-03-16 20:26:15 +00002211 if (Invalid)
2212 return;
Douglas Gregoraea67db2010-03-15 22:54:52 +00002213
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002214 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
2215 CXXUnit->getASTContext().getLangOptions(),
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002216 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002217 Lex.SetCommentRetentionState(true);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002218
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002219 // Lex tokens until we hit the end of the range.
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002220 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002221 llvm::SmallVector<CXToken, 32> CXTokens;
2222 Token Tok;
2223 do {
2224 // Lex the next token
2225 Lex.LexFromRawLexer(Tok);
2226 if (Tok.is(tok::eof))
2227 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002228
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002229 // Initialize the CXToken.
2230 CXToken CXTok;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002231
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002232 // - Common fields
2233 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
2234 CXTok.int_data[2] = Tok.getLength();
2235 CXTok.int_data[3] = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002236
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002237 // - Kind-specific fields
2238 if (Tok.isLiteral()) {
2239 CXTok.int_data[0] = CXToken_Literal;
2240 CXTok.ptr_data = (void *)Tok.getLiteralData();
2241 } else if (Tok.is(tok::identifier)) {
Douglas Gregoraea67db2010-03-15 22:54:52 +00002242 // Lookup the identifier to determine whether we have a keyword.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002243 std::pair<FileID, unsigned> LocInfo
2244 = SourceMgr.getDecomposedLoc(Tok.getLocation());
Douglas Gregorf715ca12010-03-16 00:06:06 +00002245 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002246 llvm::StringRef Buf
Douglas Gregorf715ca12010-03-16 00:06:06 +00002247 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
2248 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00002249 return;
2250
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002251 const char *StartPos = Buf.data() + LocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002252 IdentifierInfo *II
2253 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok, StartPos);
2254 CXTok.int_data[0] = II->getTokenID() == tok::identifier?
2255 CXToken_Identifier
2256 : CXToken_Keyword;
2257 CXTok.ptr_data = II;
2258 } else if (Tok.is(tok::comment)) {
2259 CXTok.int_data[0] = CXToken_Comment;
2260 CXTok.ptr_data = 0;
2261 } else {
2262 CXTok.int_data[0] = CXToken_Punctuation;
2263 CXTok.ptr_data = 0;
2264 }
2265 CXTokens.push_back(CXTok);
2266 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002267
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002268 if (CXTokens.empty())
2269 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002270
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002271 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
2272 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
2273 *NumTokens = CXTokens.size();
2274}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002275
2276typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
2277
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002278enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
2279 CXCursor parent,
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002280 CXClientData client_data) {
2281 AnnotateTokensData *Data = static_cast<AnnotateTokensData *>(client_data);
2282
2283 // We only annotate the locations of declarations, simple
2284 // references, and expressions which directly reference something.
2285 CXCursorKind Kind = clang_getCursorKind(cursor);
2286 if (clang_isDeclaration(Kind) || clang_isReference(Kind)) {
2287 // Okay: We can annotate the location of this declaration with the
2288 // declaration or reference
2289 } else if (clang_isExpression(cursor.kind)) {
2290 if (Kind != CXCursor_DeclRefExpr &&
2291 Kind != CXCursor_MemberRefExpr &&
2292 Kind != CXCursor_ObjCMessageExpr)
2293 return CXChildVisit_Recurse;
2294
2295 CXCursor Referenced = clang_getCursorReferenced(cursor);
2296 if (Referenced == cursor || Referenced == clang_getNullCursor())
2297 return CXChildVisit_Recurse;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002298
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002299 // Okay: we can annotate the location of this expression
Douglas Gregor0396f462010-03-19 05:22:59 +00002300 } else if (clang_isPreprocessing(cursor.kind)) {
2301 // We can always annotate a preprocessing directive/macro instantiation.
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002302 } else {
2303 // Nothing to annotate
2304 return CXChildVisit_Recurse;
2305 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002306
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002307 CXSourceLocation Loc = clang_getCursorLocation(cursor);
2308 (*Data)[Loc.int_data] = cursor;
2309 return CXChildVisit_Recurse;
2310}
2311
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002312void clang_annotateTokens(CXTranslationUnit TU,
2313 CXToken *Tokens, unsigned NumTokens,
2314 CXCursor *Cursors) {
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002315 if (NumTokens == 0)
2316 return;
2317
2318 // Any token we don't specifically annotate will have a NULL cursor.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002319 for (unsigned I = 0; I != NumTokens; ++I)
2320 Cursors[I] = clang_getNullCursor();
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002321
2322 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2323 if (!CXXUnit || !Tokens)
2324 return;
2325
Douglas Gregorbdf60622010-03-05 21:16:25 +00002326 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
2327
Douglas Gregor0396f462010-03-19 05:22:59 +00002328 // Determine the region of interest, which contains all of the tokens.
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002329 SourceRange RegionOfInterest;
2330 RegionOfInterest.setBegin(
2331 cxloc::translateSourceLocation(clang_getTokenLocation(TU, Tokens[0])));
2332 SourceLocation End
Douglas Gregor09d9fa12010-04-05 16:10:30 +00002333 = cxloc::translateSourceLocation(clang_getTokenLocation(TU,
Douglas Gregor0396f462010-03-19 05:22:59 +00002334 Tokens[NumTokens - 1]));
Daniel Dunbard52864b2010-02-14 10:02:57 +00002335 RegionOfInterest.setEnd(CXXUnit->getPreprocessor().getLocForEndOfToken(End));
Douglas Gregor2507fa82010-03-19 00:18:31 +00002336
Douglas Gregor0396f462010-03-19 05:22:59 +00002337 // A mapping from the source locations found when re-lexing or traversing the
2338 // region of interest to the corresponding cursors.
2339 AnnotateTokensData Annotated;
2340
2341 // Relex the tokens within the source range to look for preprocessing
2342 // directives.
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002343 SourceManager &SourceMgr = CXXUnit->getSourceManager();
2344 std::pair<FileID, unsigned> BeginLocInfo
2345 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
2346 std::pair<FileID, unsigned> EndLocInfo
2347 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
2348
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002349 llvm::StringRef Buffer;
Douglas Gregor0396f462010-03-19 05:22:59 +00002350 bool Invalid = false;
2351 if (BeginLocInfo.first == EndLocInfo.first &&
2352 ((Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid)),true) &&
2353 !Invalid) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002354 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
2355 CXXUnit->getASTContext().getLangOptions(),
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002356 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
2357 Buffer.end());
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002358 Lex.SetCommentRetentionState(true);
2359
2360 // Lex tokens in raw mode until we hit the end of the range, to avoid
2361 // entering #includes or expanding macros.
Douglas Gregor48072312010-03-18 15:23:44 +00002362 while (true) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002363 Token Tok;
2364 Lex.LexFromRawLexer(Tok);
2365
2366 reprocess:
2367 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
2368 // We have found a preprocessing directive. Gobble it up so that we
2369 // don't see it while preprocessing these tokens later, but keep track of
2370 // all of the token locations inside this preprocessing directive so that
2371 // we can annotate them appropriately.
2372 //
2373 // FIXME: Some simple tests here could identify macro definitions and
2374 // #undefs, to provide specific cursor kinds for those.
2375 std::vector<SourceLocation> Locations;
2376 do {
2377 Locations.push_back(Tok.getLocation());
2378 Lex.LexFromRawLexer(Tok);
2379 } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
2380
2381 using namespace cxcursor;
2382 CXCursor Cursor
2383 = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
2384 Locations.back()),
2385 CXXUnit);
2386 for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
2387 Annotated[Locations[I].getRawEncoding()] = Cursor;
2388 }
2389
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002390 if (Tok.isAtStartOfLine())
2391 goto reprocess;
2392
2393 continue;
2394 }
2395
Douglas Gregor48072312010-03-18 15:23:44 +00002396 if (Tok.is(tok::eof))
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002397 break;
2398 }
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002399 }
Douglas Gregor0396f462010-03-19 05:22:59 +00002400
2401 // Annotate all of the source locations in the region of interest that map to
2402 // a specific cursor.
2403 CXCursor Parent = clang_getTranslationUnitCursor(CXXUnit);
2404 CursorVisitor AnnotateVis(CXXUnit, AnnotateTokensVisitor, &Annotated,
2405 Decl::MaxPCHLevel, RegionOfInterest);
2406 AnnotateVis.VisitChildren(Parent);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002407
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002408 for (unsigned I = 0; I != NumTokens; ++I) {
2409 // Determine whether we saw a cursor at this token's location.
2410 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
2411 if (Pos == Annotated.end())
2412 continue;
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002413
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002414 Cursors[I] = Pos->second;
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002415 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002416}
2417
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002418void clang_disposeTokens(CXTranslationUnit TU,
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002419 CXToken *Tokens, unsigned NumTokens) {
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002420 free(Tokens);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002421}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002422
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002423} // end: extern "C"
2424
2425//===----------------------------------------------------------------------===//
Ted Kremenek16b42592010-03-03 06:36:57 +00002426// Operations for querying linkage of a cursor.
2427//===----------------------------------------------------------------------===//
2428
2429extern "C" {
2430CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
Douglas Gregor0396f462010-03-19 05:22:59 +00002431 if (!clang_isDeclaration(cursor.kind))
2432 return CXLinkage_Invalid;
2433
Ted Kremenek16b42592010-03-03 06:36:57 +00002434 Decl *D = cxcursor::getCursorDecl(cursor);
2435 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
2436 switch (ND->getLinkage()) {
2437 case NoLinkage: return CXLinkage_NoLinkage;
2438 case InternalLinkage: return CXLinkage_Internal;
2439 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
2440 case ExternalLinkage: return CXLinkage_External;
2441 };
2442
2443 return CXLinkage_Invalid;
2444}
2445} // end: extern "C"
2446
2447//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00002448// CXString Operations.
2449//===----------------------------------------------------------------------===//
2450
2451extern "C" {
2452const char *clang_getCString(CXString string) {
2453 return string.Spelling;
2454}
2455
2456void clang_disposeString(CXString string) {
2457 if (string.MustFreeString && string.Spelling)
2458 free((void*)string.Spelling);
2459}
Ted Kremenek04bb7162010-01-22 22:44:15 +00002460
Ted Kremenekfb480492010-01-13 21:46:36 +00002461} // end: extern "C"
Ted Kremenek04bb7162010-01-22 22:44:15 +00002462
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002463namespace clang { namespace cxstring {
2464CXString createCXString(const char *String, bool DupString){
2465 CXString Str;
2466 if (DupString) {
2467 Str.Spelling = strdup(String);
2468 Str.MustFreeString = 1;
2469 } else {
2470 Str.Spelling = String;
2471 Str.MustFreeString = 0;
2472 }
2473 return Str;
2474}
2475
2476CXString createCXString(llvm::StringRef String, bool DupString) {
2477 CXString Result;
2478 if (DupString || (!String.empty() && String.data()[String.size()] != 0)) {
2479 char *Spelling = (char *)malloc(String.size() + 1);
2480 memmove(Spelling, String.data(), String.size());
2481 Spelling[String.size()] = 0;
2482 Result.Spelling = Spelling;
2483 Result.MustFreeString = 1;
2484 } else {
2485 Result.Spelling = String.data();
2486 Result.MustFreeString = 0;
2487 }
2488 return Result;
2489}
2490}}
2491
Ted Kremenek04bb7162010-01-22 22:44:15 +00002492//===----------------------------------------------------------------------===//
2493// Misc. utility functions.
2494//===----------------------------------------------------------------------===//
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002495
Ted Kremenek04bb7162010-01-22 22:44:15 +00002496extern "C" {
2497
Ted Kremeneka2a9d6e2010-02-12 22:54:40 +00002498CXString clang_getClangVersion() {
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002499 return createCXString(getClangFullVersion());
Ted Kremenek04bb7162010-01-22 22:44:15 +00002500}
2501
2502} // end: extern "C"