blob: 5a64caa342d857ad16bba2eb9244edd9a59aef18 [file] [log] [blame]
Ted Kremenekd2fa5662009-08-26 22:36:44 +00001//===- CIndex.cpp - Clang-C Source Indexing Library -----------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00007//
Ted Kremenekd2fa5662009-08-26 22:36:44 +00008//===----------------------------------------------------------------------===//
9//
Ted Kremenekab188932010-01-05 19:32:54 +000010// This file implements the main API hooks in the Clang-C Source Indexing
11// library.
Ted Kremenekd2fa5662009-08-26 22:36:44 +000012//
13//===----------------------------------------------------------------------===//
14
Ted Kremenekab188932010-01-05 19:32:54 +000015#include "CIndexer.h"
Ted Kremenek16c440a2010-01-15 20:35:54 +000016#include "CXCursor.h"
Ted Kremeneka297de22010-01-25 22:34:44 +000017#include "CXSourceLocation.h"
Douglas Gregor5352ac02010-01-28 00:27:43 +000018#include "CIndexDiagnostic.h"
Ted Kremenekab188932010-01-05 19:32:54 +000019
Ted Kremenek04bb7162010-01-22 22:44:15 +000020#include "clang/Basic/Version.h"
Douglas Gregor936ea3b2010-01-28 00:56:43 +000021
Steve Naroff50398192009-08-28 15:28:48 +000022#include "clang/AST/DeclVisitor.h"
Steve Narofffb570422009-09-22 19:25:29 +000023#include "clang/AST/StmtVisitor.h"
Douglas Gregor7d0d40e2010-01-21 16:28:34 +000024#include "clang/AST/TypeLocVisitor.h"
Douglas Gregor936ea3b2010-01-28 00:56:43 +000025#include "clang/Frontend/FrontendDiagnostic.h"
Ted Kremenekd8210652010-01-06 23:43:31 +000026#include "clang/Lex/Lexer.h"
Douglas Gregor33e9abd2010-01-22 19:49:59 +000027#include "clang/Lex/Preprocessor.h"
Douglas Gregor02465752009-10-16 21:24:31 +000028#include "llvm/Support/MemoryBuffer.h"
Benjamin Kramer0829a832009-10-18 11:19:36 +000029#include "llvm/System/Program.h"
Douglas Gregor0a812cf2010-02-18 23:07:20 +000030#include "llvm/System/Signals.h"
Ted Kremenekfc062212009-10-19 21:44:57 +000031
Benjamin Kramerc2a98162010-03-13 21:22:49 +000032// Needed to define L_TMPNAM on some systems.
33#include <cstdio>
34
Steve Naroff50398192009-08-28 15:28:48 +000035using namespace clang;
Ted Kremenek16c440a2010-01-15 20:35:54 +000036using namespace clang::cxcursor;
Ted Kremenekee4db4f2010-02-17 00:41:08 +000037using namespace clang::cxstring;
Steve Naroff50398192009-08-28 15:28:48 +000038using namespace idx;
39
Ted Kremenek8a8da7d2010-01-06 03:42:32 +000040//===----------------------------------------------------------------------===//
41// Crash Reporting.
42//===----------------------------------------------------------------------===//
43
44#ifdef __APPLE__
Ted Kremenek29b72842010-01-07 22:49:05 +000045#define USE_CRASHTRACER
Ted Kremenek8a8da7d2010-01-06 03:42:32 +000046#include "clang/Analysis/Support/SaveAndRestore.h"
47// Integrate with crash reporter.
48extern "C" const char *__crashreporter_info__;
Ted Kremenek6b569992010-02-17 21:12:23 +000049#define NUM_CRASH_STRINGS 32
Ted Kremenek29b72842010-01-07 22:49:05 +000050static unsigned crashtracer_counter = 0;
Ted Kremenek254ba7c2010-01-07 23:13:53 +000051static unsigned crashtracer_counter_id[NUM_CRASH_STRINGS] = { 0 };
Ted Kremenek29b72842010-01-07 22:49:05 +000052static const char *crashtracer_strings[NUM_CRASH_STRINGS] = { 0 };
53static const char *agg_crashtracer_strings[NUM_CRASH_STRINGS] = { 0 };
54
55static unsigned SetCrashTracerInfo(const char *str,
56 llvm::SmallString<1024> &AggStr) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +000057
Ted Kremenek254ba7c2010-01-07 23:13:53 +000058 unsigned slot = 0;
Ted Kremenek29b72842010-01-07 22:49:05 +000059 while (crashtracer_strings[slot]) {
60 if (++slot == NUM_CRASH_STRINGS)
61 slot = 0;
62 }
63 crashtracer_strings[slot] = str;
Ted Kremenek254ba7c2010-01-07 23:13:53 +000064 crashtracer_counter_id[slot] = ++crashtracer_counter;
Ted Kremenek29b72842010-01-07 22:49:05 +000065
66 // We need to create an aggregate string because multiple threads
67 // may be in this method at one time. The crash reporter string
68 // will attempt to overapproximate the set of in-flight invocations
69 // of this function. Race conditions can still cause this goal
70 // to not be achieved.
71 {
Ted Kremenekf0e23e82010-02-17 00:41:40 +000072 llvm::raw_svector_ostream Out(AggStr);
Ted Kremenek29b72842010-01-07 22:49:05 +000073 for (unsigned i = 0; i < NUM_CRASH_STRINGS; ++i)
74 if (crashtracer_strings[i]) Out << crashtracer_strings[i] << '\n';
75 }
76 __crashreporter_info__ = agg_crashtracer_strings[slot] = AggStr.c_str();
77 return slot;
78}
79
80static void ResetCrashTracerInfo(unsigned slot) {
Ted Kremenek254ba7c2010-01-07 23:13:53 +000081 unsigned max_slot = 0;
82 unsigned max_value = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +000083
Ted Kremenek254ba7c2010-01-07 23:13:53 +000084 crashtracer_strings[slot] = agg_crashtracer_strings[slot] = 0;
85
86 for (unsigned i = 0 ; i < NUM_CRASH_STRINGS; ++i)
87 if (agg_crashtracer_strings[i] &&
88 crashtracer_counter_id[i] > max_value) {
89 max_slot = i;
90 max_value = crashtracer_counter_id[i];
Ted Kremenek29b72842010-01-07 22:49:05 +000091 }
Ted Kremenek254ba7c2010-01-07 23:13:53 +000092
93 __crashreporter_info__ = agg_crashtracer_strings[max_slot];
Ted Kremenek29b72842010-01-07 22:49:05 +000094}
95
96namespace {
97class ArgsCrashTracerInfo {
98 llvm::SmallString<1024> CrashString;
99 llvm::SmallString<1024> AggregateString;
100 unsigned crashtracerSlot;
101public:
102 ArgsCrashTracerInfo(llvm::SmallVectorImpl<const char*> &Args)
103 : crashtracerSlot(0)
104 {
105 {
106 llvm::raw_svector_ostream Out(CrashString);
Ted Kremenek0baa9522010-03-05 22:43:25 +0000107 Out << "ClangCIndex [" << getClangFullVersion() << "]"
108 << "[createTranslationUnitFromSourceFile]: clang";
Ted Kremenek29b72842010-01-07 22:49:05 +0000109 for (llvm::SmallVectorImpl<const char*>::iterator I=Args.begin(),
110 E=Args.end(); I!=E; ++I)
111 Out << ' ' << *I;
112 }
113 crashtracerSlot = SetCrashTracerInfo(CrashString.c_str(),
114 AggregateString);
115 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000116
Ted Kremenek29b72842010-01-07 22:49:05 +0000117 ~ArgsCrashTracerInfo() {
118 ResetCrashTracerInfo(crashtracerSlot);
119 }
120};
121}
122#endif
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000123
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000124/// \brief The result of comparing two source ranges.
125enum RangeComparisonResult {
126 /// \brief Either the ranges overlap or one of the ranges is invalid.
127 RangeOverlap,
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000128
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000129 /// \brief The first range ends before the second range starts.
130 RangeBefore,
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000131
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000132 /// \brief The first range starts after the second range ends.
133 RangeAfter
134};
135
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000136/// \brief Compare two source ranges to determine their relative position in
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000137/// the translation unit.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000138static RangeComparisonResult RangeCompare(SourceManager &SM,
139 SourceRange R1,
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000140 SourceRange R2) {
141 assert(R1.isValid() && "First range is invalid?");
142 assert(R2.isValid() && "Second range is invalid?");
Daniel Dunbard52864b2010-02-14 10:02:57 +0000143 if (R1.getEnd() == R2.getBegin() ||
144 SM.isBeforeInTranslationUnit(R1.getEnd(), R2.getBegin()))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000145 return RangeBefore;
Daniel Dunbard52864b2010-02-14 10:02:57 +0000146 if (R2.getEnd() == R1.getBegin() ||
147 SM.isBeforeInTranslationUnit(R2.getEnd(), R1.getBegin()))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000148 return RangeAfter;
149 return RangeOverlap;
150}
151
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000152/// \brief Translate a Clang source range into a CIndex source range.
153///
154/// Clang internally represents ranges where the end location points to the
155/// start of the token at the end. However, for external clients it is more
156/// useful to have a CXSourceRange be a proper half-open interval. This routine
157/// does the appropriate translation.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000158CXSourceRange cxloc::translateSourceRange(const SourceManager &SM,
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000159 const LangOptions &LangOpts,
160 SourceRange R) {
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000161 // We want the last character in this location, so we will adjust the
Douglas Gregor6a5a23f2010-03-19 21:51:54 +0000162 // location accordingly.
163 // FIXME: How do do this with a macro instantiation location?
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000164 SourceLocation EndLoc = R.getEnd();
Douglas Gregor6a5a23f2010-03-19 21:51:54 +0000165 if (!EndLoc.isInvalid() && EndLoc.isFileID()) {
166 unsigned Length = Lexer::MeasureTokenLength(EndLoc, SM, LangOpts);
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000167 EndLoc = EndLoc.getFileLocWithOffset(Length);
168 }
169
170 CXSourceRange Result = { { (void *)&SM, (void *)&LangOpts },
171 R.getBegin().getRawEncoding(),
172 EndLoc.getRawEncoding() };
173 return Result;
174}
Douglas Gregor1db19de2010-01-19 21:36:55 +0000175
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000176//===----------------------------------------------------------------------===//
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000177// Cursor visitor.
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000178//===----------------------------------------------------------------------===//
179
Steve Naroff89922f82009-08-31 00:59:03 +0000180namespace {
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000181
Douglas Gregorb1373d02010-01-20 20:59:29 +0000182// Cursor visitor.
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000183class CursorVisitor : public DeclVisitor<CursorVisitor, bool>,
Douglas Gregora59e3902010-01-21 23:27:09 +0000184 public TypeLocVisitor<CursorVisitor, bool>,
185 public StmtVisitor<CursorVisitor, bool>
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000186{
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000187 /// \brief The translation unit we are traversing.
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000188 ASTUnit *TU;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000189
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000190 /// \brief The parent cursor whose children we are traversing.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000191 CXCursor Parent;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000192
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000193 /// \brief The declaration that serves at the parent of any statement or
194 /// expression nodes.
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000195 Decl *StmtParent;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000196
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000197 /// \brief The visitor function.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000198 CXCursorVisitor Visitor;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000199
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000200 /// \brief The opaque client data, to be passed along to the visitor.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000201 CXClientData ClientData;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000202
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000203 // MaxPCHLevel - the maximum PCH level of declarations that we will pass on
204 // to the visitor. Declarations with a PCH level greater than this value will
205 // be suppressed.
206 unsigned MaxPCHLevel;
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000207
208 /// \brief When valid, a source range to which the cursor should restrict
209 /// its search.
210 SourceRange RegionOfInterest;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000211
Douglas Gregorb1373d02010-01-20 20:59:29 +0000212 using DeclVisitor<CursorVisitor, bool>::Visit;
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000213 using TypeLocVisitor<CursorVisitor, bool>::Visit;
Douglas Gregora59e3902010-01-21 23:27:09 +0000214 using StmtVisitor<CursorVisitor, bool>::Visit;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000215
216 /// \brief Determine whether this particular source range comes before, comes
217 /// after, or overlaps the region of interest.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000218 ///
Daniel Dunbard52864b2010-02-14 10:02:57 +0000219 /// \param R a half-open source range retrieved from the abstract syntax tree.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000220 RangeComparisonResult CompareRegionOfInterest(SourceRange R);
221
Steve Naroff89922f82009-08-31 00:59:03 +0000222public:
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000223 CursorVisitor(ASTUnit *TU, CXCursorVisitor Visitor, CXClientData ClientData,
224 unsigned MaxPCHLevel,
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000225 SourceRange RegionOfInterest = SourceRange())
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000226 : TU(TU), Visitor(Visitor), ClientData(ClientData),
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000227 MaxPCHLevel(MaxPCHLevel), RegionOfInterest(RegionOfInterest)
Douglas Gregorb1373d02010-01-20 20:59:29 +0000228 {
229 Parent.kind = CXCursor_NoDeclFound;
230 Parent.data[0] = 0;
231 Parent.data[1] = 0;
232 Parent.data[2] = 0;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000233 StmtParent = 0;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000234 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000235
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000236 bool Visit(CXCursor Cursor, bool CheckedRegionOfInterest = false);
Douglas Gregor788f5a12010-03-20 00:41:21 +0000237
238 std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
239 getPreprocessedEntities();
240
Douglas Gregorb1373d02010-01-20 20:59:29 +0000241 bool VisitChildren(CXCursor Parent);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000242
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000243 // Declaration visitors
Ted Kremenek09dfa372010-02-18 05:46:33 +0000244 bool VisitAttributes(Decl *D);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000245 bool VisitDeclContext(DeclContext *DC);
Ted Kremenek4540c9c2010-02-18 18:47:08 +0000246 bool VisitTranslationUnitDecl(TranslationUnitDecl *D);
247 bool VisitTypedefDecl(TypedefDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000248 bool VisitTagDecl(TagDecl *D);
249 bool VisitEnumConstantDecl(EnumConstantDecl *D);
250 bool VisitDeclaratorDecl(DeclaratorDecl *DD);
251 bool VisitFunctionDecl(FunctionDecl *ND);
252 bool VisitFieldDecl(FieldDecl *D);
Ted Kremenek4540c9c2010-02-18 18:47:08 +0000253 bool VisitVarDecl(VarDecl *);
Ted Kremenek79758f62010-02-18 22:36:18 +0000254 bool VisitObjCMethodDecl(ObjCMethodDecl *ND);
255 bool VisitObjCContainerDecl(ObjCContainerDecl *D);
256 bool VisitObjCCategoryDecl(ObjCCategoryDecl *ND);
257 bool VisitObjCProtocolDecl(ObjCProtocolDecl *PID);
258 bool VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
259 bool VisitObjCImplDecl(ObjCImplDecl *D);
260 bool VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
261 bool VisitObjCImplementationDecl(ObjCImplementationDecl *D);
262 // FIXME: ObjCPropertyDecl requires TypeSourceInfo, getter/setter locations,
263 // etc.
264 // FIXME: ObjCCompatibleAliasDecl requires aliased-class locations.
265 bool VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D);
266 bool VisitObjCClassDecl(ObjCClassDecl *D);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000267
268 // Type visitors
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000269 // FIXME: QualifiedTypeLoc doesn't provide any location information
270 bool VisitBuiltinTypeLoc(BuiltinTypeLoc TL);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000271 bool VisitTypedefTypeLoc(TypedefTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000272 bool VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL);
273 bool VisitTagTypeLoc(TagTypeLoc TL);
274 // FIXME: TemplateTypeParmTypeLoc doesn't provide any location information
275 bool VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL);
276 bool VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL);
277 bool VisitPointerTypeLoc(PointerTypeLoc TL);
278 bool VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL);
279 bool VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL);
280 bool VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL);
281 bool VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL);
282 bool VisitFunctionTypeLoc(FunctionTypeLoc TL);
283 bool VisitArrayTypeLoc(ArrayTypeLoc TL);
Douglas Gregor2332c112010-01-21 20:48:56 +0000284 // FIXME: Implement for TemplateSpecializationTypeLoc
285 // FIXME: Implement visitors here when the unimplemented TypeLocs get
286 // implemented
287 bool VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL);
288 bool VisitTypeOfTypeLoc(TypeOfTypeLoc TL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000289
Douglas Gregora59e3902010-01-21 23:27:09 +0000290 // Statement visitors
291 bool VisitStmt(Stmt *S);
292 bool VisitDeclStmt(DeclStmt *S);
Douglas Gregorf5bab412010-01-22 01:00:11 +0000293 // FIXME: LabelStmt label?
294 bool VisitIfStmt(IfStmt *S);
295 bool VisitSwitchStmt(SwitchStmt *S);
Douglas Gregor263b47b2010-01-25 16:12:32 +0000296 bool VisitWhileStmt(WhileStmt *S);
297 bool VisitForStmt(ForStmt *S);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000298
Douglas Gregor336fd812010-01-23 00:40:08 +0000299 // Expression visitors
300 bool VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E);
301 bool VisitExplicitCastExpr(ExplicitCastExpr *E);
302 bool VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
Douglas Gregorc2350e52010-03-08 16:40:19 +0000303 bool VisitObjCMessageExpr(ObjCMessageExpr *E);
Steve Naroff89922f82009-08-31 00:59:03 +0000304};
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000305
Ted Kremenekab188932010-01-05 19:32:54 +0000306} // end anonymous namespace
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000307
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000308RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000309 return RangeCompare(TU->getSourceManager(), R, RegionOfInterest);
310}
311
Douglas Gregorb1373d02010-01-20 20:59:29 +0000312/// \brief Visit the given cursor and, if requested by the visitor,
313/// its children.
314///
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000315/// \param Cursor the cursor to visit.
316///
317/// \param CheckRegionOfInterest if true, then the caller already checked that
318/// this cursor is within the region of interest.
319///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000320/// \returns true if the visitation should be aborted, false if it
321/// should continue.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000322bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
Douglas Gregorb1373d02010-01-20 20:59:29 +0000323 if (clang_isInvalid(Cursor.kind))
324 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000325
Douglas Gregorb1373d02010-01-20 20:59:29 +0000326 if (clang_isDeclaration(Cursor.kind)) {
327 Decl *D = getCursorDecl(Cursor);
328 assert(D && "Invalid declaration cursor");
329 if (D->getPCHLevel() > MaxPCHLevel)
330 return false;
331
332 if (D->isImplicit())
333 return false;
334 }
335
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000336 // If we have a range of interest, and this cursor doesn't intersect with it,
337 // we're done.
338 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
Daniel Dunbarf408f322010-02-14 08:32:05 +0000339 SourceRange Range =
340 cxloc::translateCXSourceRange(clang_getCursorExtent(Cursor));
341 if (Range.isInvalid() || CompareRegionOfInterest(Range))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000342 return false;
343 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000344
Douglas Gregorb1373d02010-01-20 20:59:29 +0000345 switch (Visitor(Cursor, Parent, ClientData)) {
346 case CXChildVisit_Break:
347 return true;
348
349 case CXChildVisit_Continue:
350 return false;
351
352 case CXChildVisit_Recurse:
353 return VisitChildren(Cursor);
354 }
355
Douglas Gregorfd643772010-01-25 16:45:46 +0000356 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000357}
358
Douglas Gregor788f5a12010-03-20 00:41:21 +0000359std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
360CursorVisitor::getPreprocessedEntities() {
361 PreprocessingRecord &PPRec
362 = *TU->getPreprocessor().getPreprocessingRecord();
363
364 bool OnlyLocalDecls
365 = !TU->isMainFileAST() && TU->getOnlyLocalDecls();
366
367 // There is no region of interest; we have to walk everything.
368 if (RegionOfInterest.isInvalid())
369 return std::make_pair(PPRec.begin(OnlyLocalDecls),
370 PPRec.end(OnlyLocalDecls));
371
372 // Find the file in which the region of interest lands.
373 SourceManager &SM = TU->getSourceManager();
374 std::pair<FileID, unsigned> Begin
375 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getBegin());
376 std::pair<FileID, unsigned> End
377 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getEnd());
378
379 // The region of interest spans files; we have to walk everything.
380 if (Begin.first != End.first)
381 return std::make_pair(PPRec.begin(OnlyLocalDecls),
382 PPRec.end(OnlyLocalDecls));
383
384 ASTUnit::PreprocessedEntitiesByFileMap &ByFileMap
385 = TU->getPreprocessedEntitiesByFile();
386 if (ByFileMap.empty()) {
387 // Build the mapping from files to sets of preprocessed entities.
388 for (PreprocessingRecord::iterator E = PPRec.begin(OnlyLocalDecls),
389 EEnd = PPRec.end(OnlyLocalDecls);
390 E != EEnd; ++E) {
391 std::pair<FileID, unsigned> P
392 = SM.getDecomposedInstantiationLoc((*E)->getSourceRange().getBegin());
393 ByFileMap[P.first].push_back(*E);
394 }
395 }
396
397 return std::make_pair(ByFileMap[Begin.first].begin(),
398 ByFileMap[Begin.first].end());
399}
400
Douglas Gregorb1373d02010-01-20 20:59:29 +0000401/// \brief Visit the children of the given cursor.
402///
403/// \returns true if the visitation should be aborted, false if it
404/// should continue.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000405bool CursorVisitor::VisitChildren(CXCursor Cursor) {
Douglas Gregora59e3902010-01-21 23:27:09 +0000406 if (clang_isReference(Cursor.kind)) {
407 // By definition, references have no children.
408 return false;
409 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000410
411 // Set the Parent field to Cursor, then back to its old value once we're
Douglas Gregorb1373d02010-01-20 20:59:29 +0000412 // done.
413 class SetParentRAII {
414 CXCursor &Parent;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000415 Decl *&StmtParent;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000416 CXCursor OldParent;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000417
Douglas Gregorb1373d02010-01-20 20:59:29 +0000418 public:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000419 SetParentRAII(CXCursor &Parent, Decl *&StmtParent, CXCursor NewParent)
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000420 : Parent(Parent), StmtParent(StmtParent), OldParent(Parent)
Douglas Gregorb1373d02010-01-20 20:59:29 +0000421 {
422 Parent = NewParent;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000423 if (clang_isDeclaration(Parent.kind))
424 StmtParent = getCursorDecl(Parent);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000425 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000426
Douglas Gregorb1373d02010-01-20 20:59:29 +0000427 ~SetParentRAII() {
428 Parent = OldParent;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000429 if (clang_isDeclaration(Parent.kind))
430 StmtParent = getCursorDecl(Parent);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000431 }
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000432 } SetParent(Parent, StmtParent, Cursor);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000433
Douglas Gregorb1373d02010-01-20 20:59:29 +0000434 if (clang_isDeclaration(Cursor.kind)) {
435 Decl *D = getCursorDecl(Cursor);
436 assert(D && "Invalid declaration cursor");
Ted Kremenek539311e2010-02-18 18:47:01 +0000437 return VisitAttributes(D) || Visit(D);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000438 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000439
Douglas Gregora59e3902010-01-21 23:27:09 +0000440 if (clang_isStatement(Cursor.kind))
441 return Visit(getCursorStmt(Cursor));
442 if (clang_isExpression(Cursor.kind))
443 return Visit(getCursorExpr(Cursor));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000444
Douglas Gregorb1373d02010-01-20 20:59:29 +0000445 if (clang_isTranslationUnit(Cursor.kind)) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000446 ASTUnit *CXXUnit = getCursorASTUnit(Cursor);
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000447 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
448 RegionOfInterest.isInvalid()) {
Douglas Gregor7b691f332010-01-20 21:13:59 +0000449 const std::vector<Decl*> &TLDs = CXXUnit->getTopLevelDecls();
450 for (std::vector<Decl*>::const_iterator it = TLDs.begin(),
451 ie = TLDs.end(); it != ie; ++it) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000452 if (Visit(MakeCXCursor(*it, CXXUnit), true))
Douglas Gregor7b691f332010-01-20 21:13:59 +0000453 return true;
454 }
Douglas Gregor0396f462010-03-19 05:22:59 +0000455 } else if (VisitDeclContext(
456 CXXUnit->getASTContext().getTranslationUnitDecl()))
457 return true;
Bob Wilson3178cb62010-03-19 03:57:57 +0000458
Douglas Gregor0396f462010-03-19 05:22:59 +0000459 // Walk the preprocessing record.
Daniel Dunbar8de30ff2010-03-20 01:11:56 +0000460 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000461 // FIXME: Once we have the ability to deserialize a preprocessing record,
462 // do so.
Douglas Gregor788f5a12010-03-20 00:41:21 +0000463 PreprocessingRecord::iterator E, EEnd;
464 for (llvm::tie(E, EEnd) = getPreprocessedEntities(); E != EEnd; ++E) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000465 if (MacroInstantiation *MI = dyn_cast<MacroInstantiation>(*E)) {
466 if (Visit(MakeMacroInstantiationCursor(MI, CXXUnit)))
467 return true;
Douglas Gregor788f5a12010-03-20 00:41:21 +0000468
Douglas Gregor0396f462010-03-19 05:22:59 +0000469 continue;
470 }
471
472 if (MacroDefinition *MD = dyn_cast<MacroDefinition>(*E)) {
473 if (Visit(MakeMacroDefinitionCursor(MD, CXXUnit)))
474 return true;
475
476 continue;
477 }
478 }
479 }
Douglas Gregor7b691f332010-01-20 21:13:59 +0000480 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000481 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000482
Douglas Gregorb1373d02010-01-20 20:59:29 +0000483 // Nothing to visit at the moment.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000484 return false;
485}
486
Douglas Gregorb1373d02010-01-20 20:59:29 +0000487bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000488 for (DeclContext::decl_iterator
Douglas Gregorb1373d02010-01-20 20:59:29 +0000489 I = DC->decls_begin(), E = DC->decls_end(); I != E; ++I) {
Ted Kremenek09dfa372010-02-18 05:46:33 +0000490
Daniel Dunbard52864b2010-02-14 10:02:57 +0000491 CXCursor Cursor = MakeCXCursor(*I, TU);
492
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000493 if (RegionOfInterest.isValid()) {
Daniel Dunbard52864b2010-02-14 10:02:57 +0000494 SourceRange Range =
495 cxloc::translateCXSourceRange(clang_getCursorExtent(Cursor));
496 if (Range.isInvalid())
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000497 continue;
Daniel Dunbard52864b2010-02-14 10:02:57 +0000498
499 switch (CompareRegionOfInterest(Range)) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000500 case RangeBefore:
501 // This declaration comes before the region of interest; skip it.
502 continue;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000503
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000504 case RangeAfter:
505 // This declaration comes after the region of interest; we're done.
506 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000507
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000508 case RangeOverlap:
509 // This declaration overlaps the region of interest; visit it.
510 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000511 }
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000512 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000513
Daniel Dunbard52864b2010-02-14 10:02:57 +0000514 if (Visit(Cursor, true))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000515 return true;
516 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000517
Douglas Gregorb1373d02010-01-20 20:59:29 +0000518 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000519}
520
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000521bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
522 llvm_unreachable("Translation units are visited directly by Visit()");
523 return false;
524}
525
526bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
527 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
528 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000529
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000530 return false;
531}
532
533bool CursorVisitor::VisitTagDecl(TagDecl *D) {
534 return VisitDeclContext(D);
535}
536
537bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
538 if (Expr *Init = D->getInitExpr())
539 return Visit(MakeCXCursor(Init, StmtParent, TU));
540 return false;
541}
542
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000543bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
544 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
545 if (Visit(TSInfo->getTypeLoc()))
546 return true;
547
548 return false;
549}
550
Douglas Gregorb1373d02010-01-20 20:59:29 +0000551bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000552 if (VisitDeclaratorDecl(ND))
553 return true;
554
Douglas Gregora59e3902010-01-21 23:27:09 +0000555 if (ND->isThisDeclarationADefinition() &&
556 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
557 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000558
Douglas Gregorb1373d02010-01-20 20:59:29 +0000559 return false;
560}
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000561
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000562bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
563 if (VisitDeclaratorDecl(D))
564 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000565
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000566 if (Expr *BitWidth = D->getBitWidth())
567 return Visit(MakeCXCursor(BitWidth, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000568
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000569 return false;
570}
571
572bool CursorVisitor::VisitVarDecl(VarDecl *D) {
573 if (VisitDeclaratorDecl(D))
574 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000575
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000576 if (Expr *Init = D->getInit())
577 return Visit(MakeCXCursor(Init, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000578
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000579 return false;
580}
581
582bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
Douglas Gregor4bc1cb62010-03-08 14:59:44 +0000583 if (TypeSourceInfo *TSInfo = ND->getResultTypeSourceInfo())
584 if (Visit(TSInfo->getTypeLoc()))
585 return true;
586
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000587 for (ObjCMethodDecl::param_iterator P = ND->param_begin(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000588 PEnd = ND->param_end();
589 P != PEnd; ++P) {
590 if (Visit(MakeCXCursor(*P, TU)))
591 return true;
592 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000593
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000594 if (ND->isThisDeclarationADefinition() &&
595 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
596 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000597
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000598 return false;
599}
600
Douglas Gregora59e3902010-01-21 23:27:09 +0000601bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
602 return VisitDeclContext(D);
603}
604
Douglas Gregorb1373d02010-01-20 20:59:29 +0000605bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000606 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
607 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000608 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000609
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000610 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
611 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
612 E = ND->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000613 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000614 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000615
Douglas Gregora59e3902010-01-21 23:27:09 +0000616 return VisitObjCContainerDecl(ND);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000617}
618
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000619bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
620 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
621 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
622 E = PID->protocol_end(); I != E; ++I, ++PL)
623 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
624 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000625
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000626 return VisitObjCContainerDecl(PID);
627}
628
Douglas Gregorb1373d02010-01-20 20:59:29 +0000629bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000630 // Issue callbacks for super class.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000631 if (D->getSuperClass() &&
632 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000633 D->getSuperClassLoc(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000634 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000635 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000636
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000637 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
638 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
639 E = D->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000640 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000641 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000642
Douglas Gregora59e3902010-01-21 23:27:09 +0000643 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000644}
645
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000646bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
647 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000648}
649
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000650bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
Ted Kremenekebfa3392010-03-19 20:39:03 +0000651 // 'ID' could be null when dealing with invalid code.
652 if (ObjCInterfaceDecl *ID = D->getClassInterface())
653 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
654 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000655
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000656 return VisitObjCImplDecl(D);
657}
658
659bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
660#if 0
661 // Issue callbacks for super class.
662 // FIXME: No source location information!
663 if (D->getSuperClass() &&
664 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000665 D->getSuperClassLoc(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000666 TU)))
667 return true;
668#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000669
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000670 return VisitObjCImplDecl(D);
671}
672
673bool CursorVisitor::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D) {
674 ObjCForwardProtocolDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
675 for (ObjCForwardProtocolDecl::protocol_iterator I = D->protocol_begin(),
676 E = D->protocol_end();
677 I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000678 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000679 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000680
681 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000682}
683
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000684bool CursorVisitor::VisitObjCClassDecl(ObjCClassDecl *D) {
685 for (ObjCClassDecl::iterator C = D->begin(), CEnd = D->end(); C != CEnd; ++C)
686 if (Visit(MakeCursorObjCClassRef(C->getInterface(), C->getLocation(), TU)))
687 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000688
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000689 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000690}
691
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000692bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
693 ASTContext &Context = TU->getASTContext();
694
695 // Some builtin types (such as Objective-C's "id", "sel", and
696 // "Class") have associated declarations. Create cursors for those.
697 QualType VisitType;
698 switch (TL.getType()->getAs<BuiltinType>()->getKind()) {
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000699 case BuiltinType::Void:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000700 case BuiltinType::Bool:
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000701 case BuiltinType::Char_U:
702 case BuiltinType::UChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000703 case BuiltinType::Char16:
704 case BuiltinType::Char32:
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000705 case BuiltinType::UShort:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000706 case BuiltinType::UInt:
707 case BuiltinType::ULong:
708 case BuiltinType::ULongLong:
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000709 case BuiltinType::UInt128:
710 case BuiltinType::Char_S:
711 case BuiltinType::SChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000712 case BuiltinType::WChar:
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000713 case BuiltinType::Short:
714 case BuiltinType::Int:
715 case BuiltinType::Long:
716 case BuiltinType::LongLong:
717 case BuiltinType::Int128:
718 case BuiltinType::Float:
719 case BuiltinType::Double:
720 case BuiltinType::LongDouble:
721 case BuiltinType::NullPtr:
722 case BuiltinType::Overload:
723 case BuiltinType::Dependent:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000724 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000725
726 case BuiltinType::UndeducedAuto: // FIXME: Deserves a cursor?
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000727 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000728
Ted Kremenekc4174cc2010-02-18 18:52:18 +0000729 case BuiltinType::ObjCId:
730 VisitType = Context.getObjCIdType();
731 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000732
733 case BuiltinType::ObjCClass:
734 VisitType = Context.getObjCClassType();
735 break;
736
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000737 case BuiltinType::ObjCSel:
738 VisitType = Context.getObjCSelType();
739 break;
740 }
741
742 if (!VisitType.isNull()) {
743 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000744 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000745 TU));
746 }
747
748 return false;
749}
750
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000751bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
752 return Visit(MakeCursorTypeRef(TL.getTypedefDecl(), TL.getNameLoc(), TU));
753}
754
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000755bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
756 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
757}
758
759bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
760 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
761}
762
763bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
764 if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
765 return true;
766
767 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
768 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
769 TU)))
770 return true;
771 }
772
773 return false;
774}
775
776bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
777 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseTypeLoc()))
778 return true;
779
780 if (TL.hasProtocolsAsWritten()) {
781 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000782 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I),
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000783 TL.getProtocolLoc(I),
784 TU)))
785 return true;
786 }
787 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000788
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000789 return false;
790}
791
792bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
793 return Visit(TL.getPointeeLoc());
794}
795
796bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
797 return Visit(TL.getPointeeLoc());
798}
799
800bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
801 return Visit(TL.getPointeeLoc());
802}
803
804bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000805 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000806}
807
808bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000809 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000810}
811
812bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
813 if (Visit(TL.getResultLoc()))
814 return true;
815
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000816 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
817 if (Visit(MakeCXCursor(TL.getArg(I), TU)))
818 return true;
819
820 return false;
821}
822
823bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
824 if (Visit(TL.getElementLoc()))
825 return true;
826
827 if (Expr *Size = TL.getSizeExpr())
828 return Visit(MakeCXCursor(Size, StmtParent, TU));
829
830 return false;
831}
832
Douglas Gregor2332c112010-01-21 20:48:56 +0000833bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
834 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
835}
836
837bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
838 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
839 return Visit(TSInfo->getTypeLoc());
840
841 return false;
842}
843
Douglas Gregora59e3902010-01-21 23:27:09 +0000844bool CursorVisitor::VisitStmt(Stmt *S) {
845 for (Stmt::child_iterator Child = S->child_begin(), ChildEnd = S->child_end();
846 Child != ChildEnd; ++Child) {
Daniel Dunbar54d67ca2010-01-25 00:40:30 +0000847 if (*Child && Visit(MakeCXCursor(*Child, StmtParent, TU)))
Douglas Gregora59e3902010-01-21 23:27:09 +0000848 return true;
849 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000850
Douglas Gregora59e3902010-01-21 23:27:09 +0000851 return false;
852}
853
854bool CursorVisitor::VisitDeclStmt(DeclStmt *S) {
855 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
856 D != DEnd; ++D) {
Douglas Gregor263b47b2010-01-25 16:12:32 +0000857 if (*D && Visit(MakeCXCursor(*D, TU)))
Douglas Gregora59e3902010-01-21 23:27:09 +0000858 return true;
859 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000860
Douglas Gregora59e3902010-01-21 23:27:09 +0000861 return false;
862}
863
Douglas Gregorf5bab412010-01-22 01:00:11 +0000864bool CursorVisitor::VisitIfStmt(IfStmt *S) {
865 if (VarDecl *Var = S->getConditionVariable()) {
866 if (Visit(MakeCXCursor(Var, TU)))
867 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000868 }
869
Douglas Gregor263b47b2010-01-25 16:12:32 +0000870 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
871 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +0000872 if (S->getThen() && Visit(MakeCXCursor(S->getThen(), StmtParent, TU)))
873 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +0000874 if (S->getElse() && Visit(MakeCXCursor(S->getElse(), StmtParent, TU)))
875 return true;
876
877 return false;
878}
879
880bool CursorVisitor::VisitSwitchStmt(SwitchStmt *S) {
881 if (VarDecl *Var = S->getConditionVariable()) {
882 if (Visit(MakeCXCursor(Var, TU)))
883 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000884 }
885
Douglas Gregor263b47b2010-01-25 16:12:32 +0000886 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
887 return true;
888 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
889 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000890
Douglas Gregor263b47b2010-01-25 16:12:32 +0000891 return false;
892}
893
894bool CursorVisitor::VisitWhileStmt(WhileStmt *S) {
895 if (VarDecl *Var = S->getConditionVariable()) {
896 if (Visit(MakeCXCursor(Var, TU)))
897 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000898 }
899
Douglas Gregor263b47b2010-01-25 16:12:32 +0000900 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
901 return true;
902 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
Douglas Gregorf5bab412010-01-22 01:00:11 +0000903 return true;
904
Douglas Gregor263b47b2010-01-25 16:12:32 +0000905 return false;
906}
907
908bool CursorVisitor::VisitForStmt(ForStmt *S) {
909 if (S->getInit() && Visit(MakeCXCursor(S->getInit(), StmtParent, TU)))
910 return true;
911 if (VarDecl *Var = S->getConditionVariable()) {
912 if (Visit(MakeCXCursor(Var, TU)))
913 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000914 }
915
Douglas Gregor263b47b2010-01-25 16:12:32 +0000916 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
917 return true;
918 if (S->getInc() && Visit(MakeCXCursor(S->getInc(), StmtParent, TU)))
919 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +0000920 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
921 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000922
Douglas Gregorf5bab412010-01-22 01:00:11 +0000923 return false;
924}
925
Douglas Gregor336fd812010-01-23 00:40:08 +0000926bool CursorVisitor::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E) {
927 if (E->isArgumentType()) {
928 if (TypeSourceInfo *TSInfo = E->getArgumentTypeInfo())
929 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000930
Douglas Gregor336fd812010-01-23 00:40:08 +0000931 return false;
932 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000933
Douglas Gregor336fd812010-01-23 00:40:08 +0000934 return VisitExpr(E);
935}
936
937bool CursorVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
938 if (TypeSourceInfo *TSInfo = E->getTypeInfoAsWritten())
939 if (Visit(TSInfo->getTypeLoc()))
940 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000941
Douglas Gregor336fd812010-01-23 00:40:08 +0000942 return VisitCastExpr(E);
943}
944
945bool CursorVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
946 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
947 if (Visit(TSInfo->getTypeLoc()))
948 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000949
Douglas Gregor336fd812010-01-23 00:40:08 +0000950 return VisitExpr(E);
951}
952
Douglas Gregorc2350e52010-03-08 16:40:19 +0000953bool CursorVisitor::VisitObjCMessageExpr(ObjCMessageExpr *E) {
954 ObjCMessageExpr::ClassInfo CI = E->getClassInfo();
955 if (CI.Decl && Visit(MakeCursorObjCClassRef(CI.Decl, CI.Loc, TU)))
956 return true;
957
958 return VisitExpr(E);
959}
960
Ted Kremenek09dfa372010-02-18 05:46:33 +0000961bool CursorVisitor::VisitAttributes(Decl *D) {
962 for (const Attr *A = D->getAttrs(); A; A = A->getNext())
963 if (Visit(MakeCXCursor(A, D, TU)))
964 return true;
965
966 return false;
967}
968
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000969extern "C" {
Douglas Gregor0a812cf2010-02-18 23:07:20 +0000970CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
971 int displayDiagnostics) {
Douglas Gregora030b7c2010-01-22 20:35:53 +0000972 CIndexer *CIdxr = new CIndexer();
Steve Naroffe56b4ba2009-10-20 14:46:24 +0000973 if (excludeDeclarationsFromPCH)
974 CIdxr->setOnlyLocalDecls();
Douglas Gregor0a812cf2010-02-18 23:07:20 +0000975 if (displayDiagnostics)
976 CIdxr->setDisplayDiagnostics();
Steve Naroffe56b4ba2009-10-20 14:46:24 +0000977 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +0000978}
979
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000980void clang_disposeIndex(CXIndex CIdx) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +0000981 if (CIdx)
982 delete static_cast<CIndexer *>(CIdx);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +0000983}
984
Daniel Dunbar8506dde2009-12-03 01:54:28 +0000985void clang_setUseExternalASTGeneration(CXIndex CIdx, int value) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +0000986 if (CIdx) {
987 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
988 CXXIdx->setUseExternalASTGeneration(value);
989 }
Daniel Dunbar8506dde2009-12-03 01:54:28 +0000990}
991
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000992CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
Douglas Gregora88084b2010-02-18 18:08:43 +0000993 const char *ast_filename) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +0000994 if (!CIdx)
995 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000996
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000997 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000998
Douglas Gregor5352ac02010-01-28 00:27:43 +0000999 // Configure the diagnostics.
1000 DiagnosticOptions DiagOpts;
1001 llvm::OwningPtr<Diagnostic> Diags;
1002 Diags.reset(CompilerInstance::createDiagnostics(DiagOpts, 0, 0));
Douglas Gregor5352ac02010-01-28 00:27:43 +00001003 return ASTUnit::LoadFromPCHFile(ast_filename, *Diags,
Douglas Gregora88084b2010-02-18 18:08:43 +00001004 CXXIdx->getOnlyLocalDecls(),
1005 0, 0, true);
Steve Naroff600866c2009-08-27 19:51:58 +00001006}
1007
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001008CXTranslationUnit
1009clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
1010 const char *source_filename,
1011 int num_command_line_args,
Douglas Gregor4db64a42010-01-23 00:14:00 +00001012 const char **command_line_args,
1013 unsigned num_unsaved_files,
Douglas Gregora88084b2010-02-18 18:08:43 +00001014 struct CXUnsavedFile *unsaved_files) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001015 if (!CIdx)
1016 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001017
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001018 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
1019
Douglas Gregor5352ac02010-01-28 00:27:43 +00001020 // Configure the diagnostics.
1021 DiagnosticOptions DiagOpts;
1022 llvm::OwningPtr<Diagnostic> Diags;
1023 Diags.reset(CompilerInstance::createDiagnostics(DiagOpts, 0, 0));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001024
Douglas Gregor4db64a42010-01-23 00:14:00 +00001025 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
1026 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001027 const llvm::MemoryBuffer *Buffer
Douglas Gregorc8dfe5e2010-02-27 01:32:48 +00001028 = llvm::MemoryBuffer::getMemBufferCopy(unsaved_files[I].Contents,
Douglas Gregor313e26c2010-02-18 23:35:40 +00001029 unsaved_files[I].Contents + unsaved_files[I].Length,
1030 unsaved_files[I].Filename);
Douglas Gregor4db64a42010-01-23 00:14:00 +00001031 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
1032 Buffer));
1033 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001034
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001035 if (!CXXIdx->getUseExternalASTGeneration()) {
1036 llvm::SmallVector<const char *, 16> Args;
1037
1038 // The 'source_filename' argument is optional. If the caller does not
1039 // specify it then it is assumed that the source file is specified
1040 // in the actual argument list.
1041 if (source_filename)
1042 Args.push_back(source_filename);
1043 Args.insert(Args.end(), command_line_args,
1044 command_line_args + num_command_line_args);
Douglas Gregor94dc8f62010-03-19 16:15:56 +00001045 Args.push_back("-Xclang");
1046 Args.push_back("-detailed-preprocessing-record");
Douglas Gregor5352ac02010-01-28 00:27:43 +00001047 unsigned NumErrors = Diags->getNumErrors();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001048
Ted Kremenek29b72842010-01-07 22:49:05 +00001049#ifdef USE_CRASHTRACER
1050 ArgsCrashTracerInfo ACTI(Args);
Ted Kremenek8a8da7d2010-01-06 03:42:32 +00001051#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001052
Daniel Dunbar94220972009-12-05 02:17:18 +00001053 llvm::OwningPtr<ASTUnit> Unit(
1054 ASTUnit::LoadFromCommandLine(Args.data(), Args.data() + Args.size(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001055 *Diags,
Daniel Dunbar869824e2009-12-13 03:46:13 +00001056 CXXIdx->getClangResourcesPath(),
Daniel Dunbar94220972009-12-05 02:17:18 +00001057 CXXIdx->getOnlyLocalDecls(),
Douglas Gregor4db64a42010-01-23 00:14:00 +00001058 RemappedFiles.data(),
Douglas Gregora88084b2010-02-18 18:08:43 +00001059 RemappedFiles.size(),
Douglas Gregor94dc8f62010-03-19 16:15:56 +00001060 /*CaptureDiagnostics=*/true));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001061
Daniel Dunbar94220972009-12-05 02:17:18 +00001062 // FIXME: Until we have broader testing, just drop the entire AST if we
1063 // encountered an error.
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001064 if (NumErrors != Diags->getNumErrors()) {
Ted Kremenek34f6a322010-03-05 22:43:29 +00001065 // Make sure to check that 'Unit' is non-NULL.
1066 if (CXXIdx->getDisplayDiagnostics() && Unit.get()) {
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001067 for (ASTUnit::diag_iterator D = Unit->diag_begin(),
1068 DEnd = Unit->diag_end();
1069 D != DEnd; ++D) {
1070 CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOptions());
Douglas Gregor274f1902010-02-22 23:17:23 +00001071 CXString Msg = clang_formatDiagnostic(&Diag,
1072 clang_defaultDiagnosticDisplayOptions());
1073 fprintf(stderr, "%s\n", clang_getCString(Msg));
1074 clang_disposeString(Msg);
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001075 }
Douglas Gregor274f1902010-02-22 23:17:23 +00001076#ifdef LLVM_ON_WIN32
1077 // On Windows, force a flush, since there may be multiple copies of
1078 // stderr and stdout in the file system, all with different buffers
1079 // but writing to the same device.
1080 fflush(stderr);
1081#endif
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001082 }
Daniel Dunbar94220972009-12-05 02:17:18 +00001083 return 0;
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001084 }
Daniel Dunbar94220972009-12-05 02:17:18 +00001085
1086 return Unit.take();
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001087 }
1088
Ted Kremenek139ba862009-10-22 00:03:57 +00001089 // Build up the arguments for invoking 'clang'.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001090 std::vector<const char *> argv;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001091
Ted Kremenek139ba862009-10-22 00:03:57 +00001092 // First add the complete path to the 'clang' executable.
1093 llvm::sys::Path ClangPath = static_cast<CIndexer *>(CIdx)->getClangPath();
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00001094 argv.push_back(ClangPath.c_str());
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001095
Ted Kremenek139ba862009-10-22 00:03:57 +00001096 // Add the '-emit-ast' option as our execution mode for 'clang'.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001097 argv.push_back("-emit-ast");
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001098
Ted Kremenek139ba862009-10-22 00:03:57 +00001099 // The 'source_filename' argument is optional. If the caller does not
1100 // specify it then it is assumed that the source file is specified
1101 // in the actual argument list.
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001102 if (source_filename)
1103 argv.push_back(source_filename);
Ted Kremenek139ba862009-10-22 00:03:57 +00001104
Steve Naroff37b5ac22009-10-15 20:50:09 +00001105 // Generate a temporary name for the AST file.
Ted Kremenek139ba862009-10-22 00:03:57 +00001106 argv.push_back("-o");
Benjamin Kramerc2a98162010-03-13 21:22:49 +00001107 char astTmpFile[L_tmpnam];
1108 argv.push_back(tmpnam(astTmpFile));
Ted Kremenek139ba862009-10-22 00:03:57 +00001109
Douglas Gregor4db64a42010-01-23 00:14:00 +00001110 // Remap any unsaved files to temporary files.
1111 std::vector<llvm::sys::Path> TemporaryFiles;
1112 std::vector<std::string> RemapArgs;
1113 if (RemapFiles(num_unsaved_files, unsaved_files, RemapArgs, TemporaryFiles))
1114 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001115
Douglas Gregor4db64a42010-01-23 00:14:00 +00001116 // The pointers into the elements of RemapArgs are stable because we
1117 // won't be adding anything to RemapArgs after this point.
1118 for (unsigned i = 0, e = RemapArgs.size(); i != e; ++i)
1119 argv.push_back(RemapArgs[i].c_str());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001120
Ted Kremenek139ba862009-10-22 00:03:57 +00001121 // Process the compiler options, stripping off '-o', '-c', '-fsyntax-only'.
1122 for (int i = 0; i < num_command_line_args; ++i)
1123 if (const char *arg = command_line_args[i]) {
1124 if (strcmp(arg, "-o") == 0) {
1125 ++i; // Also skip the matching argument.
1126 continue;
1127 }
1128 if (strcmp(arg, "-emit-ast") == 0 ||
1129 strcmp(arg, "-c") == 0 ||
1130 strcmp(arg, "-fsyntax-only") == 0) {
1131 continue;
1132 }
1133
1134 // Keep the argument.
1135 argv.push_back(arg);
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001136 }
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001137
Douglas Gregord93256e2010-01-28 06:00:51 +00001138 // Generate a temporary name for the diagnostics file.
Benjamin Kramerc2a98162010-03-13 21:22:49 +00001139 char tmpFileResults[L_tmpnam];
1140 char *tmpResultsFileName = tmpnam(tmpFileResults);
1141 llvm::sys::Path DiagnosticsFile(tmpResultsFileName);
Douglas Gregord93256e2010-01-28 06:00:51 +00001142 TemporaryFiles.push_back(DiagnosticsFile);
1143 argv.push_back("-fdiagnostics-binary");
1144
Douglas Gregor94dc8f62010-03-19 16:15:56 +00001145 argv.push_back("-Xclang");
1146 argv.push_back("-detailed-preprocessing-record");
1147
Ted Kremenek139ba862009-10-22 00:03:57 +00001148 // Add the null terminator.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001149 argv.push_back(NULL);
1150
Ted Kremenekfeb15e32009-10-26 22:14:08 +00001151 // Invoke 'clang'.
1152 llvm::sys::Path DevNull; // leave empty, causes redirection to /dev/null
1153 // on Unix or NUL (Windows).
Ted Kremenek379afec2009-10-22 03:24:01 +00001154 std::string ErrMsg;
Douglas Gregord93256e2010-01-28 06:00:51 +00001155 const llvm::sys::Path *Redirects[] = { &DevNull, &DevNull, &DiagnosticsFile,
1156 NULL };
Ted Kremenek379afec2009-10-22 03:24:01 +00001157 llvm::sys::Program::ExecuteAndWait(ClangPath, &argv[0], /* env */ NULL,
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001158 /* redirects */ &Redirects[0],
Ted Kremenek379afec2009-10-22 03:24:01 +00001159 /* secondsToWait */ 0, /* memoryLimits */ 0, &ErrMsg);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001160
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001161 if (!ErrMsg.empty()) {
1162 std::string AllArgs;
Ted Kremenek379afec2009-10-22 03:24:01 +00001163 for (std::vector<const char*>::iterator I = argv.begin(), E = argv.end();
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001164 I != E; ++I) {
1165 AllArgs += ' ';
Ted Kremenek779e5f42009-10-26 22:08:39 +00001166 if (*I)
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001167 AllArgs += *I;
Ted Kremenek779e5f42009-10-26 22:08:39 +00001168 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001169
Daniel Dunbar32141c82010-02-23 20:23:45 +00001170 Diags->Report(diag::err_fe_invoking) << AllArgs << ErrMsg;
Ted Kremenek379afec2009-10-22 03:24:01 +00001171 }
Benjamin Kramer0829a832009-10-18 11:19:36 +00001172
Benjamin Kramerc2a98162010-03-13 21:22:49 +00001173 ASTUnit *ATU = ASTUnit::LoadFromPCHFile(astTmpFile, *Diags,
Douglas Gregor4db64a42010-01-23 00:14:00 +00001174 CXXIdx->getOnlyLocalDecls(),
Douglas Gregor4db64a42010-01-23 00:14:00 +00001175 RemappedFiles.data(),
Douglas Gregora88084b2010-02-18 18:08:43 +00001176 RemappedFiles.size(),
1177 /*CaptureDiagnostics=*/true);
Douglas Gregora88084b2010-02-18 18:08:43 +00001178 if (ATU) {
1179 LoadSerializedDiagnostics(DiagnosticsFile,
1180 num_unsaved_files, unsaved_files,
1181 ATU->getFileManager(),
1182 ATU->getSourceManager(),
1183 ATU->getDiagnostics());
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001184 } else if (CXXIdx->getDisplayDiagnostics()) {
1185 // We failed to load the ASTUnit, but we can still deserialize the
1186 // diagnostics and emit them.
1187 FileManager FileMgr;
Douglas Gregorf715ca12010-03-16 00:06:06 +00001188 Diagnostic Diag;
1189 SourceManager SourceMgr(Diag);
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001190 // FIXME: Faked LangOpts!
1191 LangOptions LangOpts;
1192 llvm::SmallVector<StoredDiagnostic, 4> Diags;
1193 LoadSerializedDiagnostics(DiagnosticsFile,
1194 num_unsaved_files, unsaved_files,
1195 FileMgr, SourceMgr, Diags);
1196 for (llvm::SmallVector<StoredDiagnostic, 4>::iterator D = Diags.begin(),
1197 DEnd = Diags.end();
1198 D != DEnd; ++D) {
1199 CXStoredDiagnostic Diag(*D, LangOpts);
Douglas Gregor274f1902010-02-22 23:17:23 +00001200 CXString Msg = clang_formatDiagnostic(&Diag,
1201 clang_defaultDiagnosticDisplayOptions());
1202 fprintf(stderr, "%s\n", clang_getCString(Msg));
1203 clang_disposeString(Msg);
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001204 }
Douglas Gregor274f1902010-02-22 23:17:23 +00001205
1206#ifdef LLVM_ON_WIN32
1207 // On Windows, force a flush, since there may be multiple copies of
1208 // stderr and stdout in the file system, all with different buffers
1209 // but writing to the same device.
1210 fflush(stderr);
1211#endif
Douglas Gregora88084b2010-02-18 18:08:43 +00001212 }
Douglas Gregord93256e2010-01-28 06:00:51 +00001213
Douglas Gregor313e26c2010-02-18 23:35:40 +00001214 if (ATU) {
1215 // Make the translation unit responsible for destroying all temporary files.
1216 for (unsigned i = 0, e = TemporaryFiles.size(); i != e; ++i)
1217 ATU->addTemporaryFile(TemporaryFiles[i]);
1218 ATU->addTemporaryFile(llvm::sys::Path(ATU->getPCHFileName()));
1219 } else {
1220 // Destroy all of the temporary files now; they can't be referenced any
1221 // longer.
1222 llvm::sys::Path(astTmpFile).eraseFromDisk();
1223 for (unsigned i = 0, e = TemporaryFiles.size(); i != e; ++i)
1224 TemporaryFiles[i].eraseFromDisk();
1225 }
1226
Steve Naroffe19944c2009-10-15 22:23:48 +00001227 return ATU;
Steve Naroff5b7d8e22009-10-15 20:04:39 +00001228}
1229
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001230void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001231 if (CTUnit)
1232 delete static_cast<ASTUnit *>(CTUnit);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00001233}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001234
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001235CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001236 if (!CTUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001237 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001238
Steve Naroff77accc12009-09-03 18:19:54 +00001239 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001240 return createCXString(CXXUnit->getOriginalSourceFileName(), true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +00001241}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +00001242
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001243CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001244 CXCursor Result = { CXCursor_TranslationUnit, { 0, 0, TU } };
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001245 return Result;
1246}
1247
Ted Kremenekfb480492010-01-13 21:46:36 +00001248} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +00001249
Ted Kremenekfb480492010-01-13 21:46:36 +00001250//===----------------------------------------------------------------------===//
Douglas Gregor1db19de2010-01-19 21:36:55 +00001251// CXSourceLocation and CXSourceRange Operations.
1252//===----------------------------------------------------------------------===//
1253
Douglas Gregorb9790342010-01-22 21:44:22 +00001254extern "C" {
1255CXSourceLocation clang_getNullLocation() {
Douglas Gregor5352ac02010-01-28 00:27:43 +00001256 CXSourceLocation Result = { { 0, 0 }, 0 };
Douglas Gregorb9790342010-01-22 21:44:22 +00001257 return Result;
1258}
1259
1260unsigned clang_equalLocations(CXSourceLocation loc1, CXSourceLocation loc2) {
Daniel Dunbar90a6b9e2010-01-30 23:58:27 +00001261 return (loc1.ptr_data[0] == loc2.ptr_data[0] &&
1262 loc1.ptr_data[1] == loc2.ptr_data[1] &&
1263 loc1.int_data == loc2.int_data);
Douglas Gregorb9790342010-01-22 21:44:22 +00001264}
1265
1266CXSourceLocation clang_getLocation(CXTranslationUnit tu,
1267 CXFile file,
1268 unsigned line,
1269 unsigned column) {
1270 if (!tu)
1271 return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001272
Douglas Gregorb9790342010-01-22 21:44:22 +00001273 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
1274 SourceLocation SLoc
1275 = CXXUnit->getSourceManager().getLocation(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001276 static_cast<const FileEntry *>(file),
Douglas Gregorb9790342010-01-22 21:44:22 +00001277 line, column);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001278
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00001279 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
Douglas Gregorb9790342010-01-22 21:44:22 +00001280}
1281
Douglas Gregor5352ac02010-01-28 00:27:43 +00001282CXSourceRange clang_getNullRange() {
1283 CXSourceRange Result = { { 0, 0 }, 0, 0 };
1284 return Result;
1285}
Daniel Dunbard52864b2010-02-14 10:02:57 +00001286
Douglas Gregor5352ac02010-01-28 00:27:43 +00001287CXSourceRange clang_getRange(CXSourceLocation begin, CXSourceLocation end) {
1288 if (begin.ptr_data[0] != end.ptr_data[0] ||
1289 begin.ptr_data[1] != end.ptr_data[1])
1290 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001291
1292 CXSourceRange Result = { { begin.ptr_data[0], begin.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00001293 begin.int_data, end.int_data };
Douglas Gregorb9790342010-01-22 21:44:22 +00001294 return Result;
1295}
1296
Douglas Gregor46766dc2010-01-26 19:19:08 +00001297void clang_getInstantiationLocation(CXSourceLocation location,
1298 CXFile *file,
1299 unsigned *line,
1300 unsigned *column,
1301 unsigned *offset) {
Douglas Gregor1db19de2010-01-19 21:36:55 +00001302 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
1303
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00001304 if (!location.ptr_data[0] || Loc.isInvalid()) {
Douglas Gregor46766dc2010-01-26 19:19:08 +00001305 if (file)
1306 *file = 0;
1307 if (line)
1308 *line = 0;
1309 if (column)
1310 *column = 0;
1311 if (offset)
1312 *offset = 0;
1313 return;
1314 }
1315
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00001316 const SourceManager &SM =
1317 *static_cast<const SourceManager*>(location.ptr_data[0]);
Douglas Gregor1db19de2010-01-19 21:36:55 +00001318 SourceLocation InstLoc = SM.getInstantiationLoc(Loc);
Douglas Gregor1db19de2010-01-19 21:36:55 +00001319
1320 if (file)
1321 *file = (void *)SM.getFileEntryForID(SM.getFileID(InstLoc));
1322 if (line)
1323 *line = SM.getInstantiationLineNumber(InstLoc);
1324 if (column)
1325 *column = SM.getInstantiationColumnNumber(InstLoc);
Douglas Gregore69517c2010-01-26 03:07:15 +00001326 if (offset)
Douglas Gregor46766dc2010-01-26 19:19:08 +00001327 *offset = SM.getDecomposedLoc(InstLoc).second;
Douglas Gregore69517c2010-01-26 03:07:15 +00001328}
1329
Douglas Gregor1db19de2010-01-19 21:36:55 +00001330CXSourceLocation clang_getRangeStart(CXSourceRange range) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001331 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00001332 range.begin_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00001333 return Result;
1334}
1335
1336CXSourceLocation clang_getRangeEnd(CXSourceRange range) {
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00001337 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00001338 range.end_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00001339 return Result;
1340}
1341
Douglas Gregorb9790342010-01-22 21:44:22 +00001342} // end: extern "C"
1343
Douglas Gregor1db19de2010-01-19 21:36:55 +00001344//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00001345// CXFile Operations.
1346//===----------------------------------------------------------------------===//
1347
1348extern "C" {
Ted Kremenek74844072010-02-17 00:41:20 +00001349CXString clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00001350 if (!SFile)
Ted Kremenek74844072010-02-17 00:41:20 +00001351 return createCXString(NULL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001352
Steve Naroff88145032009-10-27 14:35:18 +00001353 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Ted Kremenek74844072010-02-17 00:41:20 +00001354 return createCXString(FEnt->getName());
Steve Naroff88145032009-10-27 14:35:18 +00001355}
1356
1357time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00001358 if (!SFile)
1359 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001360
Steve Naroff88145032009-10-27 14:35:18 +00001361 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
1362 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +00001363}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001364
Douglas Gregorb9790342010-01-22 21:44:22 +00001365CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
1366 if (!tu)
1367 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001368
Douglas Gregorb9790342010-01-22 21:44:22 +00001369 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001370
Douglas Gregorb9790342010-01-22 21:44:22 +00001371 FileManager &FMgr = CXXUnit->getFileManager();
1372 const FileEntry *File = FMgr.getFile(file_name, file_name+strlen(file_name));
1373 return const_cast<FileEntry *>(File);
1374}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001375
Ted Kremenekfb480492010-01-13 21:46:36 +00001376} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +00001377
Ted Kremenekfb480492010-01-13 21:46:36 +00001378//===----------------------------------------------------------------------===//
1379// CXCursor Operations.
1380//===----------------------------------------------------------------------===//
1381
Ted Kremenekfb480492010-01-13 21:46:36 +00001382static Decl *getDeclFromExpr(Stmt *E) {
1383 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
1384 return RefExpr->getDecl();
1385 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
1386 return ME->getMemberDecl();
1387 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
1388 return RE->getDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001389
Ted Kremenekfb480492010-01-13 21:46:36 +00001390 if (CallExpr *CE = dyn_cast<CallExpr>(E))
1391 return getDeclFromExpr(CE->getCallee());
1392 if (CastExpr *CE = dyn_cast<CastExpr>(E))
1393 return getDeclFromExpr(CE->getSubExpr());
1394 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
1395 return OME->getMethodDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001396
Ted Kremenekfb480492010-01-13 21:46:36 +00001397 return 0;
1398}
1399
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00001400static SourceLocation getLocationFromExpr(Expr *E) {
1401 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
1402 return /*FIXME:*/Msg->getLeftLoc();
1403 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
1404 return DRE->getLocation();
1405 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
1406 return Member->getMemberLoc();
1407 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
1408 return Ivar->getLocation();
1409 return E->getLocStart();
1410}
1411
Ted Kremenekfb480492010-01-13 21:46:36 +00001412extern "C" {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001413
1414unsigned clang_visitChildren(CXCursor parent,
Douglas Gregorb1373d02010-01-20 20:59:29 +00001415 CXCursorVisitor visitor,
1416 CXClientData client_data) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001417 ASTUnit *CXXUnit = getCursorASTUnit(parent);
Douglas Gregorb1373d02010-01-20 20:59:29 +00001418
1419 unsigned PCHLevel = Decl::MaxPCHLevel;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001420
Douglas Gregorb1373d02010-01-20 20:59:29 +00001421 // Set the PCHLevel to filter out unwanted decls if requested.
1422 if (CXXUnit->getOnlyLocalDecls()) {
1423 PCHLevel = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001424
Douglas Gregorb1373d02010-01-20 20:59:29 +00001425 // If the main input was an AST, bump the level.
1426 if (CXXUnit->isMainFileAST())
1427 ++PCHLevel;
1428 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001429
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001430 CursorVisitor CursorVis(CXXUnit, visitor, client_data, PCHLevel);
Douglas Gregorb1373d02010-01-20 20:59:29 +00001431 return CursorVis.VisitChildren(parent);
1432}
1433
Douglas Gregor78205d42010-01-20 21:45:58 +00001434static CXString getDeclSpelling(Decl *D) {
1435 NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
1436 if (!ND)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001437 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001438
Douglas Gregor78205d42010-01-20 21:45:58 +00001439 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001440 return createCXString(OMD->getSelector().getAsString());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001441
Douglas Gregor78205d42010-01-20 21:45:58 +00001442 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
1443 // No, this isn't the same as the code below. getIdentifier() is non-virtual
1444 // and returns different names. NamedDecl returns the class name and
1445 // ObjCCategoryImplDecl returns the category name.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001446 return createCXString(CIMP->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001447
Douglas Gregor78205d42010-01-20 21:45:58 +00001448 if (ND->getIdentifier())
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001449 return createCXString(ND->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001450
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001451 return createCXString("");
Douglas Gregor78205d42010-01-20 21:45:58 +00001452}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001453
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001454CXString clang_getCursorSpelling(CXCursor C) {
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001455 if (clang_isTranslationUnit(C.kind))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001456 return clang_getTranslationUnitSpelling(C.data[2]);
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001457
Steve Narofff334b4e2009-09-02 18:26:48 +00001458 if (clang_isReference(C.kind)) {
1459 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00001460 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +00001461 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001462 return createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00001463 }
1464 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +00001465 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001466 return createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00001467 }
1468 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +00001469 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +00001470 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001471 return createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00001472 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001473 case CXCursor_TypeRef: {
1474 TypeDecl *Type = getCursorTypeRef(C).first;
1475 assert(Type && "Missing type decl");
1476
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001477 return createCXString(getCursorContext(C).getTypeDeclType(Type).
1478 getAsString());
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001479 }
1480
Daniel Dunbaracca7252009-11-30 20:42:49 +00001481 default:
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001482 return createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +00001483 }
1484 }
Douglas Gregor97b98722010-01-19 23:20:36 +00001485
1486 if (clang_isExpression(C.kind)) {
1487 Decl *D = getDeclFromExpr(getCursorExpr(C));
1488 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +00001489 return getDeclSpelling(D);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001490 return createCXString("");
Douglas Gregor97b98722010-01-19 23:20:36 +00001491 }
1492
Douglas Gregor4ae8f292010-03-18 17:52:52 +00001493 if (C.kind == CXCursor_MacroInstantiation)
1494 return createCXString(getCursorMacroInstantiation(C)->getName()
1495 ->getNameStart());
1496
Douglas Gregor572feb22010-03-18 18:04:21 +00001497 if (C.kind == CXCursor_MacroDefinition)
1498 return createCXString(getCursorMacroDefinition(C)->getName()
1499 ->getNameStart());
1500
Douglas Gregor60cbfac2010-01-25 16:56:17 +00001501 if (clang_isDeclaration(C.kind))
1502 return getDeclSpelling(getCursorDecl(C));
Ted Kremeneke68fff62010-02-17 00:41:32 +00001503
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001504 return createCXString("");
Steve Narofff334b4e2009-09-02 18:26:48 +00001505}
1506
Ted Kremeneke68fff62010-02-17 00:41:32 +00001507CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00001508 switch (Kind) {
Ted Kremeneke68fff62010-02-17 00:41:32 +00001509 case CXCursor_FunctionDecl:
1510 return createCXString("FunctionDecl");
1511 case CXCursor_TypedefDecl:
1512 return createCXString("TypedefDecl");
1513 case CXCursor_EnumDecl:
1514 return createCXString("EnumDecl");
1515 case CXCursor_EnumConstantDecl:
1516 return createCXString("EnumConstantDecl");
1517 case CXCursor_StructDecl:
1518 return createCXString("StructDecl");
1519 case CXCursor_UnionDecl:
1520 return createCXString("UnionDecl");
1521 case CXCursor_ClassDecl:
1522 return createCXString("ClassDecl");
1523 case CXCursor_FieldDecl:
1524 return createCXString("FieldDecl");
1525 case CXCursor_VarDecl:
1526 return createCXString("VarDecl");
1527 case CXCursor_ParmDecl:
1528 return createCXString("ParmDecl");
1529 case CXCursor_ObjCInterfaceDecl:
1530 return createCXString("ObjCInterfaceDecl");
1531 case CXCursor_ObjCCategoryDecl:
1532 return createCXString("ObjCCategoryDecl");
1533 case CXCursor_ObjCProtocolDecl:
1534 return createCXString("ObjCProtocolDecl");
1535 case CXCursor_ObjCPropertyDecl:
1536 return createCXString("ObjCPropertyDecl");
1537 case CXCursor_ObjCIvarDecl:
1538 return createCXString("ObjCIvarDecl");
1539 case CXCursor_ObjCInstanceMethodDecl:
1540 return createCXString("ObjCInstanceMethodDecl");
1541 case CXCursor_ObjCClassMethodDecl:
1542 return createCXString("ObjCClassMethodDecl");
1543 case CXCursor_ObjCImplementationDecl:
1544 return createCXString("ObjCImplementationDecl");
1545 case CXCursor_ObjCCategoryImplDecl:
1546 return createCXString("ObjCCategoryImplDecl");
1547 case CXCursor_UnexposedDecl:
1548 return createCXString("UnexposedDecl");
1549 case CXCursor_ObjCSuperClassRef:
1550 return createCXString("ObjCSuperClassRef");
1551 case CXCursor_ObjCProtocolRef:
1552 return createCXString("ObjCProtocolRef");
1553 case CXCursor_ObjCClassRef:
1554 return createCXString("ObjCClassRef");
1555 case CXCursor_TypeRef:
1556 return createCXString("TypeRef");
1557 case CXCursor_UnexposedExpr:
1558 return createCXString("UnexposedExpr");
1559 case CXCursor_DeclRefExpr:
1560 return createCXString("DeclRefExpr");
1561 case CXCursor_MemberRefExpr:
1562 return createCXString("MemberRefExpr");
1563 case CXCursor_CallExpr:
1564 return createCXString("CallExpr");
1565 case CXCursor_ObjCMessageExpr:
1566 return createCXString("ObjCMessageExpr");
1567 case CXCursor_UnexposedStmt:
1568 return createCXString("UnexposedStmt");
1569 case CXCursor_InvalidFile:
1570 return createCXString("InvalidFile");
Ted Kremenek292db642010-03-19 20:39:05 +00001571 case CXCursor_InvalidCode:
1572 return createCXString("InvalidCode");
Ted Kremeneke68fff62010-02-17 00:41:32 +00001573 case CXCursor_NoDeclFound:
1574 return createCXString("NoDeclFound");
1575 case CXCursor_NotImplemented:
1576 return createCXString("NotImplemented");
1577 case CXCursor_TranslationUnit:
1578 return createCXString("TranslationUnit");
Ted Kremeneke77f4432010-02-18 03:09:07 +00001579 case CXCursor_UnexposedAttr:
1580 return createCXString("UnexposedAttr");
1581 case CXCursor_IBActionAttr:
1582 return createCXString("attribute(ibaction)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00001583 case CXCursor_IBOutletAttr:
1584 return createCXString("attribute(iboutlet)");
1585 case CXCursor_PreprocessingDirective:
1586 return createCXString("preprocessing directive");
Douglas Gregor572feb22010-03-18 18:04:21 +00001587 case CXCursor_MacroDefinition:
1588 return createCXString("macro definition");
Douglas Gregor48072312010-03-18 15:23:44 +00001589 case CXCursor_MacroInstantiation:
1590 return createCXString("macro instantiation");
Steve Naroff89922f82009-08-31 00:59:03 +00001591 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00001592
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00001593 llvm_unreachable("Unhandled CXCursorKind");
Ted Kremeneke68fff62010-02-17 00:41:32 +00001594 return createCXString(NULL);
Steve Naroff600866c2009-08-27 19:51:58 +00001595}
Steve Naroff89922f82009-08-31 00:59:03 +00001596
Ted Kremeneke68fff62010-02-17 00:41:32 +00001597enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
1598 CXCursor parent,
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001599 CXClientData client_data) {
1600 CXCursor *BestCursor = static_cast<CXCursor *>(client_data);
1601 *BestCursor = cursor;
1602 return CXChildVisit_Recurse;
1603}
Ted Kremeneke68fff62010-02-17 00:41:32 +00001604
Douglas Gregorb9790342010-01-22 21:44:22 +00001605CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
1606 if (!TU)
Ted Kremenekf4629892010-01-14 01:51:23 +00001607 return clang_getNullCursor();
Ted Kremeneke68fff62010-02-17 00:41:32 +00001608
Douglas Gregorb9790342010-01-22 21:44:22 +00001609 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
1610
Douglas Gregorbdf60622010-03-05 21:16:25 +00001611 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
1612
Ted Kremeneka297de22010-01-25 22:34:44 +00001613 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001614 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
1615 if (SLoc.isValid()) {
Daniel Dunbard52864b2010-02-14 10:02:57 +00001616 SourceRange RegionOfInterest(SLoc, SLoc.getFileLocWithOffset(1));
Ted Kremeneke68fff62010-02-17 00:41:32 +00001617
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001618 // FIXME: Would be great to have a "hint" cursor, then walk from that
1619 // hint cursor upward until we find a cursor whose source range encloses
1620 // the region of interest, rather than starting from the translation unit.
1621 CXCursor Parent = clang_getTranslationUnitCursor(CXXUnit);
Ted Kremeneke68fff62010-02-17 00:41:32 +00001622 CursorVisitor CursorVis(CXXUnit, GetCursorVisitor, &Result,
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001623 Decl::MaxPCHLevel, RegionOfInterest);
1624 CursorVis.VisitChildren(Parent);
Steve Naroff77128dd2009-09-15 20:25:34 +00001625 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00001626 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00001627}
1628
Ted Kremenek73885552009-11-17 19:28:59 +00001629CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00001630 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00001631}
1632
1633unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00001634 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00001635}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001636
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001637unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00001638 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
1639}
1640
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001641unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +00001642 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
1643}
Steve Naroff2d4d6292009-08-31 14:26:51 +00001644
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001645unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00001646 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
1647}
1648
Douglas Gregor97b98722010-01-19 23:20:36 +00001649unsigned clang_isExpression(enum CXCursorKind K) {
1650 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
1651}
1652
1653unsigned clang_isStatement(enum CXCursorKind K) {
1654 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
1655}
1656
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001657unsigned clang_isTranslationUnit(enum CXCursorKind K) {
1658 return K == CXCursor_TranslationUnit;
1659}
1660
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00001661unsigned clang_isPreprocessing(enum CXCursorKind K) {
1662 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
1663}
1664
Ted Kremenekad6eff62010-03-08 21:17:29 +00001665unsigned clang_isUnexposed(enum CXCursorKind K) {
1666 switch (K) {
1667 case CXCursor_UnexposedDecl:
1668 case CXCursor_UnexposedExpr:
1669 case CXCursor_UnexposedStmt:
1670 case CXCursor_UnexposedAttr:
1671 return true;
1672 default:
1673 return false;
1674 }
1675}
1676
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001677CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00001678 return C.kind;
1679}
1680
Douglas Gregor98258af2010-01-18 22:46:11 +00001681CXSourceLocation clang_getCursorLocation(CXCursor C) {
1682 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00001683 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001684 case CXCursor_ObjCSuperClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00001685 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1686 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001687 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001688 }
1689
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001690 case CXCursor_ObjCProtocolRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00001691 std::pair<ObjCProtocolDecl *, SourceLocation> P
1692 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001693 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001694 }
1695
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001696 case CXCursor_ObjCClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00001697 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1698 = getCursorObjCClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001699 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001700 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001701
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001702 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001703 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001704 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001705 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001706
Douglas Gregorf46034a2010-01-18 23:41:10 +00001707 default:
1708 // FIXME: Need a way to enumerate all non-reference cases.
1709 llvm_unreachable("Missed a reference kind");
1710 }
Douglas Gregor98258af2010-01-18 22:46:11 +00001711 }
Douglas Gregor97b98722010-01-19 23:20:36 +00001712
1713 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001714 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00001715 getLocationFromExpr(getCursorExpr(C)));
1716
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00001717 if (C.kind == CXCursor_PreprocessingDirective) {
1718 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
1719 return cxloc::translateSourceLocation(getCursorContext(C), L);
1720 }
Douglas Gregor48072312010-03-18 15:23:44 +00001721
1722 if (C.kind == CXCursor_MacroInstantiation) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00001723 SourceLocation L
1724 = cxcursor::getCursorMacroInstantiation(C)->getSourceRange().getBegin();
Douglas Gregor48072312010-03-18 15:23:44 +00001725 return cxloc::translateSourceLocation(getCursorContext(C), L);
1726 }
Douglas Gregor572feb22010-03-18 18:04:21 +00001727
1728 if (C.kind == CXCursor_MacroDefinition) {
1729 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
1730 return cxloc::translateSourceLocation(getCursorContext(C), L);
1731 }
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00001732
Douglas Gregor5352ac02010-01-28 00:27:43 +00001733 if (!getCursorDecl(C))
1734 return clang_getNullLocation();
Douglas Gregor98258af2010-01-18 22:46:11 +00001735
Douglas Gregorf46034a2010-01-18 23:41:10 +00001736 Decl *D = getCursorDecl(C);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001737 SourceLocation Loc = D->getLocation();
1738 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
1739 Loc = Class->getClassLoc();
Douglas Gregor2ca54fe2010-03-22 15:53:50 +00001740 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00001741}
Douglas Gregora7bde202010-01-19 00:34:46 +00001742
1743CXSourceRange clang_getCursorExtent(CXCursor C) {
1744 if (clang_isReference(C.kind)) {
1745 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001746 case CXCursor_ObjCSuperClassRef: {
Douglas Gregora7bde202010-01-19 00:34:46 +00001747 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1748 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001749 return cxloc::translateSourceRange(P.first->getASTContext(), P.second);
Douglas Gregora7bde202010-01-19 00:34:46 +00001750 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001751
1752 case CXCursor_ObjCProtocolRef: {
Douglas Gregora7bde202010-01-19 00:34:46 +00001753 std::pair<ObjCProtocolDecl *, SourceLocation> P
1754 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001755 return cxloc::translateSourceRange(P.first->getASTContext(), P.second);
Douglas Gregora7bde202010-01-19 00:34:46 +00001756 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001757
1758 case CXCursor_ObjCClassRef: {
Douglas Gregora7bde202010-01-19 00:34:46 +00001759 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1760 = getCursorObjCClassRef(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001761
Ted Kremeneka297de22010-01-25 22:34:44 +00001762 return cxloc::translateSourceRange(P.first->getASTContext(), P.second);
Douglas Gregora7bde202010-01-19 00:34:46 +00001763 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001764
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001765 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001766 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001767 return cxloc::translateSourceRange(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001768 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001769
Douglas Gregora7bde202010-01-19 00:34:46 +00001770 default:
1771 // FIXME: Need a way to enumerate all non-reference cases.
1772 llvm_unreachable("Missed a reference kind");
1773 }
1774 }
Douglas Gregor97b98722010-01-19 23:20:36 +00001775
1776 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001777 return cxloc::translateSourceRange(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00001778 getCursorExpr(C)->getSourceRange());
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001779
1780 if (clang_isStatement(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001781 return cxloc::translateSourceRange(getCursorContext(C),
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001782 getCursorStmt(C)->getSourceRange());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001783
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00001784 if (C.kind == CXCursor_PreprocessingDirective) {
1785 SourceRange R = cxcursor::getCursorPreprocessingDirective(C);
1786 return cxloc::translateSourceRange(getCursorContext(C), R);
1787 }
Douglas Gregor48072312010-03-18 15:23:44 +00001788
1789 if (C.kind == CXCursor_MacroInstantiation) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00001790 SourceRange R = cxcursor::getCursorMacroInstantiation(C)->getSourceRange();
Douglas Gregor48072312010-03-18 15:23:44 +00001791 return cxloc::translateSourceRange(getCursorContext(C), R);
1792 }
Douglas Gregor572feb22010-03-18 18:04:21 +00001793
1794 if (C.kind == CXCursor_MacroDefinition) {
1795 SourceRange R = cxcursor::getCursorMacroDefinition(C)->getSourceRange();
1796 return cxloc::translateSourceRange(getCursorContext(C), R);
1797 }
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00001798
Douglas Gregor5352ac02010-01-28 00:27:43 +00001799 if (!getCursorDecl(C))
1800 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001801
Douglas Gregora7bde202010-01-19 00:34:46 +00001802 Decl *D = getCursorDecl(C);
Douglas Gregor2ca54fe2010-03-22 15:53:50 +00001803 return cxloc::translateSourceRange(getCursorContext(C), D->getSourceRange());
Douglas Gregora7bde202010-01-19 00:34:46 +00001804}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001805
1806CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001807 if (clang_isInvalid(C.kind))
1808 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001809
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001810 ASTUnit *CXXUnit = getCursorASTUnit(C);
Douglas Gregorb6998662010-01-19 19:34:47 +00001811 if (clang_isDeclaration(C.kind))
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001812 return C;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001813
Douglas Gregor97b98722010-01-19 23:20:36 +00001814 if (clang_isExpression(C.kind)) {
1815 Decl *D = getDeclFromExpr(getCursorExpr(C));
1816 if (D)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001817 return MakeCXCursor(D, CXXUnit);
Douglas Gregor97b98722010-01-19 23:20:36 +00001818 return clang_getNullCursor();
1819 }
1820
Douglas Gregorbf7efa22010-03-18 18:23:03 +00001821 if (C.kind == CXCursor_MacroInstantiation) {
1822 if (MacroDefinition *Def = getCursorMacroInstantiation(C)->getDefinition())
1823 return MakeMacroDefinitionCursor(Def, CXXUnit);
1824 }
1825
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001826 if (!clang_isReference(C.kind))
1827 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001828
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001829 switch (C.kind) {
1830 case CXCursor_ObjCSuperClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001831 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001832
1833 case CXCursor_ObjCProtocolRef: {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001834 return MakeCXCursor(getCursorObjCProtocolRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001835
1836 case CXCursor_ObjCClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001837 return MakeCXCursor(getCursorObjCClassRef(C).first, CXXUnit);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001838
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001839 case CXCursor_TypeRef:
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001840 return MakeCXCursor(getCursorTypeRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001841
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001842 default:
1843 // We would prefer to enumerate all non-reference cursor kinds here.
1844 llvm_unreachable("Unhandled reference cursor kind");
1845 break;
1846 }
1847 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001848
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001849 return clang_getNullCursor();
1850}
1851
Douglas Gregorb6998662010-01-19 19:34:47 +00001852CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001853 if (clang_isInvalid(C.kind))
1854 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001855
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001856 ASTUnit *CXXUnit = getCursorASTUnit(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001857
Douglas Gregorb6998662010-01-19 19:34:47 +00001858 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00001859 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00001860 C = clang_getCursorReferenced(C);
1861 WasReference = true;
1862 }
1863
Douglas Gregorbf7efa22010-03-18 18:23:03 +00001864 if (C.kind == CXCursor_MacroInstantiation)
1865 return clang_getCursorReferenced(C);
1866
Douglas Gregorb6998662010-01-19 19:34:47 +00001867 if (!clang_isDeclaration(C.kind))
1868 return clang_getNullCursor();
1869
1870 Decl *D = getCursorDecl(C);
1871 if (!D)
1872 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001873
Douglas Gregorb6998662010-01-19 19:34:47 +00001874 switch (D->getKind()) {
1875 // Declaration kinds that don't really separate the notions of
1876 // declaration and definition.
1877 case Decl::Namespace:
1878 case Decl::Typedef:
1879 case Decl::TemplateTypeParm:
1880 case Decl::EnumConstant:
1881 case Decl::Field:
1882 case Decl::ObjCIvar:
1883 case Decl::ObjCAtDefsField:
1884 case Decl::ImplicitParam:
1885 case Decl::ParmVar:
1886 case Decl::NonTypeTemplateParm:
1887 case Decl::TemplateTemplateParm:
1888 case Decl::ObjCCategoryImpl:
1889 case Decl::ObjCImplementation:
1890 case Decl::LinkageSpec:
1891 case Decl::ObjCPropertyImpl:
1892 case Decl::FileScopeAsm:
1893 case Decl::StaticAssert:
1894 case Decl::Block:
1895 return C;
1896
1897 // Declaration kinds that don't make any sense here, but are
1898 // nonetheless harmless.
1899 case Decl::TranslationUnit:
1900 case Decl::Template:
1901 case Decl::ObjCContainer:
1902 break;
1903
1904 // Declaration kinds for which the definition is not resolvable.
1905 case Decl::UnresolvedUsingTypename:
1906 case Decl::UnresolvedUsingValue:
1907 break;
1908
1909 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001910 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
1911 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001912
1913 case Decl::NamespaceAlias:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001914 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001915
1916 case Decl::Enum:
1917 case Decl::Record:
1918 case Decl::CXXRecord:
1919 case Decl::ClassTemplateSpecialization:
1920 case Decl::ClassTemplatePartialSpecialization:
Douglas Gregor952b0172010-02-11 01:04:33 +00001921 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001922 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001923 return clang_getNullCursor();
1924
1925 case Decl::Function:
1926 case Decl::CXXMethod:
1927 case Decl::CXXConstructor:
1928 case Decl::CXXDestructor:
1929 case Decl::CXXConversion: {
1930 const FunctionDecl *Def = 0;
1931 if (cast<FunctionDecl>(D)->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001932 return MakeCXCursor(const_cast<FunctionDecl *>(Def), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001933 return clang_getNullCursor();
1934 }
1935
1936 case Decl::Var: {
Sebastian Redl31310a22010-02-01 20:16:42 +00001937 // Ask the variable if it has a definition.
1938 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
1939 return MakeCXCursor(Def, CXXUnit);
1940 return clang_getNullCursor();
Douglas Gregorb6998662010-01-19 19:34:47 +00001941 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001942
Douglas Gregorb6998662010-01-19 19:34:47 +00001943 case Decl::FunctionTemplate: {
1944 const FunctionDecl *Def = 0;
1945 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001946 return MakeCXCursor(Def->getDescribedFunctionTemplate(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001947 return clang_getNullCursor();
1948 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001949
Douglas Gregorb6998662010-01-19 19:34:47 +00001950 case Decl::ClassTemplate: {
1951 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
Douglas Gregor952b0172010-02-11 01:04:33 +00001952 ->getDefinition())
Douglas Gregorb6998662010-01-19 19:34:47 +00001953 return MakeCXCursor(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001954 cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001955 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001956 return clang_getNullCursor();
1957 }
1958
1959 case Decl::Using: {
1960 UsingDecl *Using = cast<UsingDecl>(D);
1961 CXCursor Def = clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001962 for (UsingDecl::shadow_iterator S = Using->shadow_begin(),
1963 SEnd = Using->shadow_end();
Douglas Gregorb6998662010-01-19 19:34:47 +00001964 S != SEnd; ++S) {
1965 if (Def != clang_getNullCursor()) {
1966 // FIXME: We have no way to return multiple results.
1967 return clang_getNullCursor();
1968 }
1969
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001970 Def = clang_getCursorDefinition(MakeCXCursor((*S)->getTargetDecl(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001971 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00001972 }
1973
1974 return Def;
1975 }
1976
1977 case Decl::UsingShadow:
1978 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001979 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001980 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00001981
1982 case Decl::ObjCMethod: {
1983 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
1984 if (Method->isThisDeclarationADefinition())
1985 return C;
1986
1987 // Dig out the method definition in the associated
1988 // @implementation, if we have it.
1989 // FIXME: The ASTs should make finding the definition easier.
1990 if (ObjCInterfaceDecl *Class
1991 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
1992 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
1993 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
1994 Method->isInstanceMethod()))
1995 if (Def->isThisDeclarationADefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001996 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001997
1998 return clang_getNullCursor();
1999 }
2000
2001 case Decl::ObjCCategory:
2002 if (ObjCCategoryImplDecl *Impl
2003 = cast<ObjCCategoryDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002004 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002005 return clang_getNullCursor();
2006
2007 case Decl::ObjCProtocol:
2008 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
2009 return C;
2010 return clang_getNullCursor();
2011
2012 case Decl::ObjCInterface:
2013 // There are two notions of a "definition" for an Objective-C
2014 // class: the interface and its implementation. When we resolved a
2015 // reference to an Objective-C class, produce the @interface as
2016 // the definition; when we were provided with the interface,
2017 // produce the @implementation as the definition.
2018 if (WasReference) {
2019 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
2020 return C;
2021 } else if (ObjCImplementationDecl *Impl
2022 = cast<ObjCInterfaceDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002023 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002024 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002025
Douglas Gregorb6998662010-01-19 19:34:47 +00002026 case Decl::ObjCProperty:
2027 // FIXME: We don't really know where to find the
2028 // ObjCPropertyImplDecls that implement this property.
2029 return clang_getNullCursor();
2030
2031 case Decl::ObjCCompatibleAlias:
2032 if (ObjCInterfaceDecl *Class
2033 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
2034 if (!Class->isForwardDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002035 return MakeCXCursor(Class, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002036
Douglas Gregorb6998662010-01-19 19:34:47 +00002037 return clang_getNullCursor();
2038
2039 case Decl::ObjCForwardProtocol: {
2040 ObjCForwardProtocolDecl *Forward = cast<ObjCForwardProtocolDecl>(D);
2041 if (Forward->protocol_size() == 1)
2042 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002043 MakeCXCursor(*Forward->protocol_begin(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002044 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002045
2046 // FIXME: Cannot return multiple definitions.
2047 return clang_getNullCursor();
2048 }
2049
2050 case Decl::ObjCClass: {
2051 ObjCClassDecl *Class = cast<ObjCClassDecl>(D);
2052 if (Class->size() == 1) {
2053 ObjCInterfaceDecl *IFace = Class->begin()->getInterface();
2054 if (!IFace->isForwardDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002055 return MakeCXCursor(IFace, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002056 return clang_getNullCursor();
2057 }
2058
2059 // FIXME: Cannot return multiple definitions.
2060 return clang_getNullCursor();
2061 }
2062
2063 case Decl::Friend:
2064 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002065 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002066 return clang_getNullCursor();
2067
2068 case Decl::FriendTemplate:
2069 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002070 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002071 return clang_getNullCursor();
2072 }
2073
2074 return clang_getNullCursor();
2075}
2076
2077unsigned clang_isCursorDefinition(CXCursor C) {
2078 if (!clang_isDeclaration(C.kind))
2079 return 0;
2080
2081 return clang_getCursorDefinition(C) == C;
2082}
2083
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002084void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00002085 const char **startBuf,
2086 const char **endBuf,
2087 unsigned *startLine,
2088 unsigned *startColumn,
2089 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002090 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00002091 assert(getCursorDecl(C) && "CXCursor has null decl");
2092 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00002093 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
2094 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002095
Steve Naroff4ade6d62009-09-23 17:52:52 +00002096 SourceManager &SM = FD->getASTContext().getSourceManager();
2097 *startBuf = SM.getCharacterData(Body->getLBracLoc());
2098 *endBuf = SM.getCharacterData(Body->getRBracLoc());
2099 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
2100 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
2101 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
2102 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
2103}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002104
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002105void clang_enableStackTraces(void) {
2106 llvm::sys::PrintStackTraceOnErrorSignal();
2107}
2108
Ted Kremenekfb480492010-01-13 21:46:36 +00002109} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00002110
Ted Kremenekfb480492010-01-13 21:46:36 +00002111//===----------------------------------------------------------------------===//
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002112// Token-based Operations.
2113//===----------------------------------------------------------------------===//
2114
2115/* CXToken layout:
2116 * int_data[0]: a CXTokenKind
2117 * int_data[1]: starting token location
2118 * int_data[2]: token length
2119 * int_data[3]: reserved
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002120 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002121 * otherwise unused.
2122 */
2123extern "C" {
2124
2125CXTokenKind clang_getTokenKind(CXToken CXTok) {
2126 return static_cast<CXTokenKind>(CXTok.int_data[0]);
2127}
2128
2129CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
2130 switch (clang_getTokenKind(CXTok)) {
2131 case CXToken_Identifier:
2132 case CXToken_Keyword:
2133 // We know we have an IdentifierInfo*, so use that.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002134 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
2135 ->getNameStart());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002136
2137 case CXToken_Literal: {
2138 // We have stashed the starting pointer in the ptr_data field. Use it.
2139 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002140 return createCXString(llvm::StringRef(Text, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002141 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002142
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002143 case CXToken_Punctuation:
2144 case CXToken_Comment:
2145 break;
2146 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002147
2148 // We have to find the starting buffer pointer the hard way, by
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002149 // deconstructing the source location.
2150 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2151 if (!CXXUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002152 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002153
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002154 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
2155 std::pair<FileID, unsigned> LocInfo
2156 = CXXUnit->getSourceManager().getDecomposedLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +00002157 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002158 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00002159 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
2160 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00002161 return createCXString("");
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002162
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002163 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002164}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002165
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002166CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
2167 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2168 if (!CXXUnit)
2169 return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002170
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002171 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
2172 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
2173}
2174
2175CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
2176 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregor5352ac02010-01-28 00:27:43 +00002177 if (!CXXUnit)
2178 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002179
2180 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002181 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
2182}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002183
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002184void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
2185 CXToken **Tokens, unsigned *NumTokens) {
2186 if (Tokens)
2187 *Tokens = 0;
2188 if (NumTokens)
2189 *NumTokens = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002190
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002191 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2192 if (!CXXUnit || !Tokens || !NumTokens)
2193 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002194
Douglas Gregorbdf60622010-03-05 21:16:25 +00002195 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
2196
Daniel Dunbar85b988f2010-02-14 08:31:57 +00002197 SourceRange R = cxloc::translateCXSourceRange(Range);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002198 if (R.isInvalid())
2199 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002200
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002201 SourceManager &SourceMgr = CXXUnit->getSourceManager();
2202 std::pair<FileID, unsigned> BeginLocInfo
2203 = SourceMgr.getDecomposedLoc(R.getBegin());
2204 std::pair<FileID, unsigned> EndLocInfo
2205 = SourceMgr.getDecomposedLoc(R.getEnd());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002206
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002207 // Cannot tokenize across files.
2208 if (BeginLocInfo.first != EndLocInfo.first)
2209 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002210
2211 // Create a lexer
Douglas Gregorf715ca12010-03-16 00:06:06 +00002212 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002213 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00002214 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
Douglas Gregor47a3fcd2010-03-16 20:26:15 +00002215 if (Invalid)
2216 return;
Douglas Gregoraea67db2010-03-15 22:54:52 +00002217
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002218 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
2219 CXXUnit->getASTContext().getLangOptions(),
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002220 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002221 Lex.SetCommentRetentionState(true);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002222
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002223 // Lex tokens until we hit the end of the range.
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002224 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002225 llvm::SmallVector<CXToken, 32> CXTokens;
2226 Token Tok;
2227 do {
2228 // Lex the next token
2229 Lex.LexFromRawLexer(Tok);
2230 if (Tok.is(tok::eof))
2231 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002232
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002233 // Initialize the CXToken.
2234 CXToken CXTok;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002235
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002236 // - Common fields
2237 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
2238 CXTok.int_data[2] = Tok.getLength();
2239 CXTok.int_data[3] = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002240
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002241 // - Kind-specific fields
2242 if (Tok.isLiteral()) {
2243 CXTok.int_data[0] = CXToken_Literal;
2244 CXTok.ptr_data = (void *)Tok.getLiteralData();
2245 } else if (Tok.is(tok::identifier)) {
Douglas Gregoraea67db2010-03-15 22:54:52 +00002246 // Lookup the identifier to determine whether we have a keyword.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002247 std::pair<FileID, unsigned> LocInfo
2248 = SourceMgr.getDecomposedLoc(Tok.getLocation());
Douglas Gregorf715ca12010-03-16 00:06:06 +00002249 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002250 llvm::StringRef Buf
Douglas Gregorf715ca12010-03-16 00:06:06 +00002251 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
2252 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00002253 return;
2254
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002255 const char *StartPos = Buf.data() + LocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002256 IdentifierInfo *II
2257 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok, StartPos);
2258 CXTok.int_data[0] = II->getTokenID() == tok::identifier?
2259 CXToken_Identifier
2260 : CXToken_Keyword;
2261 CXTok.ptr_data = II;
2262 } else if (Tok.is(tok::comment)) {
2263 CXTok.int_data[0] = CXToken_Comment;
2264 CXTok.ptr_data = 0;
2265 } else {
2266 CXTok.int_data[0] = CXToken_Punctuation;
2267 CXTok.ptr_data = 0;
2268 }
2269 CXTokens.push_back(CXTok);
2270 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002271
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002272 if (CXTokens.empty())
2273 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002274
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002275 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
2276 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
2277 *NumTokens = CXTokens.size();
2278}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002279
2280typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
2281
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002282enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
2283 CXCursor parent,
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002284 CXClientData client_data) {
2285 AnnotateTokensData *Data = static_cast<AnnotateTokensData *>(client_data);
2286
2287 // We only annotate the locations of declarations, simple
2288 // references, and expressions which directly reference something.
2289 CXCursorKind Kind = clang_getCursorKind(cursor);
2290 if (clang_isDeclaration(Kind) || clang_isReference(Kind)) {
2291 // Okay: We can annotate the location of this declaration with the
2292 // declaration or reference
2293 } else if (clang_isExpression(cursor.kind)) {
2294 if (Kind != CXCursor_DeclRefExpr &&
2295 Kind != CXCursor_MemberRefExpr &&
2296 Kind != CXCursor_ObjCMessageExpr)
2297 return CXChildVisit_Recurse;
2298
2299 CXCursor Referenced = clang_getCursorReferenced(cursor);
2300 if (Referenced == cursor || Referenced == clang_getNullCursor())
2301 return CXChildVisit_Recurse;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002302
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002303 // Okay: we can annotate the location of this expression
Douglas Gregor0396f462010-03-19 05:22:59 +00002304 } else if (clang_isPreprocessing(cursor.kind)) {
2305 // We can always annotate a preprocessing directive/macro instantiation.
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002306 } else {
2307 // Nothing to annotate
2308 return CXChildVisit_Recurse;
2309 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002310
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002311 CXSourceLocation Loc = clang_getCursorLocation(cursor);
2312 (*Data)[Loc.int_data] = cursor;
2313 return CXChildVisit_Recurse;
2314}
2315
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002316void clang_annotateTokens(CXTranslationUnit TU,
2317 CXToken *Tokens, unsigned NumTokens,
2318 CXCursor *Cursors) {
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002319 if (NumTokens == 0)
2320 return;
2321
2322 // Any token we don't specifically annotate will have a NULL cursor.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002323 for (unsigned I = 0; I != NumTokens; ++I)
2324 Cursors[I] = clang_getNullCursor();
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002325
2326 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2327 if (!CXXUnit || !Tokens)
2328 return;
2329
Douglas Gregorbdf60622010-03-05 21:16:25 +00002330 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
2331
Douglas Gregor0396f462010-03-19 05:22:59 +00002332 // Determine the region of interest, which contains all of the tokens.
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002333 SourceRange RegionOfInterest;
2334 RegionOfInterest.setBegin(
2335 cxloc::translateSourceLocation(clang_getTokenLocation(TU, Tokens[0])));
2336 SourceLocation End
Douglas Gregor0396f462010-03-19 05:22:59 +00002337 = cxloc::translateSourceLocation(clang_getTokenLocation(TU,
2338 Tokens[NumTokens - 1]));
Daniel Dunbard52864b2010-02-14 10:02:57 +00002339 RegionOfInterest.setEnd(CXXUnit->getPreprocessor().getLocForEndOfToken(End));
Douglas Gregor2507fa82010-03-19 00:18:31 +00002340
Douglas Gregor0396f462010-03-19 05:22:59 +00002341 // A mapping from the source locations found when re-lexing or traversing the
2342 // region of interest to the corresponding cursors.
2343 AnnotateTokensData Annotated;
2344
2345 // Relex the tokens within the source range to look for preprocessing
2346 // directives.
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002347 SourceManager &SourceMgr = CXXUnit->getSourceManager();
2348 std::pair<FileID, unsigned> BeginLocInfo
2349 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
2350 std::pair<FileID, unsigned> EndLocInfo
2351 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
2352
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002353 llvm::StringRef Buffer;
Douglas Gregor0396f462010-03-19 05:22:59 +00002354 bool Invalid = false;
2355 if (BeginLocInfo.first == EndLocInfo.first &&
2356 ((Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid)),true) &&
2357 !Invalid) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002358 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
2359 CXXUnit->getASTContext().getLangOptions(),
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002360 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
2361 Buffer.end());
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002362 Lex.SetCommentRetentionState(true);
2363
2364 // Lex tokens in raw mode until we hit the end of the range, to avoid
2365 // entering #includes or expanding macros.
Douglas Gregor48072312010-03-18 15:23:44 +00002366 while (true) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002367 Token Tok;
2368 Lex.LexFromRawLexer(Tok);
2369
2370 reprocess:
2371 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
2372 // We have found a preprocessing directive. Gobble it up so that we
2373 // don't see it while preprocessing these tokens later, but keep track of
2374 // all of the token locations inside this preprocessing directive so that
2375 // we can annotate them appropriately.
2376 //
2377 // FIXME: Some simple tests here could identify macro definitions and
2378 // #undefs, to provide specific cursor kinds for those.
2379 std::vector<SourceLocation> Locations;
2380 do {
2381 Locations.push_back(Tok.getLocation());
2382 Lex.LexFromRawLexer(Tok);
2383 } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
2384
2385 using namespace cxcursor;
2386 CXCursor Cursor
2387 = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
2388 Locations.back()),
2389 CXXUnit);
2390 for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
2391 Annotated[Locations[I].getRawEncoding()] = Cursor;
2392 }
2393
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002394 if (Tok.isAtStartOfLine())
2395 goto reprocess;
2396
2397 continue;
2398 }
2399
Douglas Gregor48072312010-03-18 15:23:44 +00002400 if (Tok.is(tok::eof))
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002401 break;
2402 }
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002403 }
Douglas Gregor0396f462010-03-19 05:22:59 +00002404
2405 // Annotate all of the source locations in the region of interest that map to
2406 // a specific cursor.
2407 CXCursor Parent = clang_getTranslationUnitCursor(CXXUnit);
2408 CursorVisitor AnnotateVis(CXXUnit, AnnotateTokensVisitor, &Annotated,
2409 Decl::MaxPCHLevel, RegionOfInterest);
2410 AnnotateVis.VisitChildren(Parent);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002411
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002412 for (unsigned I = 0; I != NumTokens; ++I) {
2413 // Determine whether we saw a cursor at this token's location.
2414 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
2415 if (Pos == Annotated.end())
2416 continue;
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002417
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002418 Cursors[I] = Pos->second;
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002419 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002420}
2421
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002422void clang_disposeTokens(CXTranslationUnit TU,
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002423 CXToken *Tokens, unsigned NumTokens) {
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002424 free(Tokens);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002425}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002426
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002427} // end: extern "C"
2428
2429//===----------------------------------------------------------------------===//
Ted Kremenek16b42592010-03-03 06:36:57 +00002430// Operations for querying linkage of a cursor.
2431//===----------------------------------------------------------------------===//
2432
2433extern "C" {
2434CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
Douglas Gregor0396f462010-03-19 05:22:59 +00002435 if (!clang_isDeclaration(cursor.kind))
2436 return CXLinkage_Invalid;
2437
Ted Kremenek16b42592010-03-03 06:36:57 +00002438 Decl *D = cxcursor::getCursorDecl(cursor);
2439 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
2440 switch (ND->getLinkage()) {
2441 case NoLinkage: return CXLinkage_NoLinkage;
2442 case InternalLinkage: return CXLinkage_Internal;
2443 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
2444 case ExternalLinkage: return CXLinkage_External;
2445 };
2446
2447 return CXLinkage_Invalid;
2448}
2449} // end: extern "C"
2450
2451//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00002452// CXString Operations.
2453//===----------------------------------------------------------------------===//
2454
2455extern "C" {
2456const char *clang_getCString(CXString string) {
2457 return string.Spelling;
2458}
2459
2460void clang_disposeString(CXString string) {
2461 if (string.MustFreeString && string.Spelling)
2462 free((void*)string.Spelling);
2463}
Ted Kremenek04bb7162010-01-22 22:44:15 +00002464
Ted Kremenekfb480492010-01-13 21:46:36 +00002465} // end: extern "C"
Ted Kremenek04bb7162010-01-22 22:44:15 +00002466
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002467namespace clang { namespace cxstring {
2468CXString createCXString(const char *String, bool DupString){
2469 CXString Str;
2470 if (DupString) {
2471 Str.Spelling = strdup(String);
2472 Str.MustFreeString = 1;
2473 } else {
2474 Str.Spelling = String;
2475 Str.MustFreeString = 0;
2476 }
2477 return Str;
2478}
2479
2480CXString createCXString(llvm::StringRef String, bool DupString) {
2481 CXString Result;
2482 if (DupString || (!String.empty() && String.data()[String.size()] != 0)) {
2483 char *Spelling = (char *)malloc(String.size() + 1);
2484 memmove(Spelling, String.data(), String.size());
2485 Spelling[String.size()] = 0;
2486 Result.Spelling = Spelling;
2487 Result.MustFreeString = 1;
2488 } else {
2489 Result.Spelling = String.data();
2490 Result.MustFreeString = 0;
2491 }
2492 return Result;
2493}
2494}}
2495
Ted Kremenek04bb7162010-01-22 22:44:15 +00002496//===----------------------------------------------------------------------===//
2497// Misc. utility functions.
2498//===----------------------------------------------------------------------===//
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002499
Ted Kremenek04bb7162010-01-22 22:44:15 +00002500extern "C" {
2501
Ted Kremeneka2a9d6e2010-02-12 22:54:40 +00002502CXString clang_getClangVersion() {
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002503 return createCXString(getClangFullVersion());
Ted Kremenek04bb7162010-01-22 22:44:15 +00002504}
2505
2506} // end: extern "C"