blob: eb40b7fe9948628092750cf0bfa50507fc397be6 [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 Kremenekab188932010-01-05 19:32:54 +000017
Ted Kremenek04bb7162010-01-22 22:44:15 +000018#include "clang/Basic/Version.h"
Steve Naroff50398192009-08-28 15:28:48 +000019#include "clang/AST/DeclVisitor.h"
Steve Narofffb570422009-09-22 19:25:29 +000020#include "clang/AST/StmtVisitor.h"
Douglas Gregor7d0d40e2010-01-21 16:28:34 +000021#include "clang/AST/TypeLocVisitor.h"
Ted Kremenekd8210652010-01-06 23:43:31 +000022#include "clang/Lex/Lexer.h"
Douglas Gregor33e9abd2010-01-22 19:49:59 +000023#include "clang/Lex/Preprocessor.h"
Douglas Gregor02465752009-10-16 21:24:31 +000024#include "llvm/Support/MemoryBuffer.h"
Benjamin Kramer0829a832009-10-18 11:19:36 +000025#include "llvm/System/Program.h"
Ted Kremenekfc062212009-10-19 21:44:57 +000026
Ted Kremenekdb3d0da2010-01-05 20:55:39 +000027// Needed to define L_TMPNAM on some systems.
28#include <cstdio>
29
Steve Naroff50398192009-08-28 15:28:48 +000030using namespace clang;
Ted Kremenek16c440a2010-01-15 20:35:54 +000031using namespace clang::cxcursor;
Steve Naroff50398192009-08-28 15:28:48 +000032using namespace idx;
33
Ted Kremenek8a8da7d2010-01-06 03:42:32 +000034//===----------------------------------------------------------------------===//
35// Crash Reporting.
36//===----------------------------------------------------------------------===//
37
38#ifdef __APPLE__
Ted Kremenek29b72842010-01-07 22:49:05 +000039#ifndef NDEBUG
40#define USE_CRASHTRACER
Ted Kremenek8a8da7d2010-01-06 03:42:32 +000041#include "clang/Analysis/Support/SaveAndRestore.h"
42// Integrate with crash reporter.
43extern "C" const char *__crashreporter_info__;
Ted Kremenek29b72842010-01-07 22:49:05 +000044#define NUM_CRASH_STRINGS 16
45static unsigned crashtracer_counter = 0;
Ted Kremenek254ba7c2010-01-07 23:13:53 +000046static unsigned crashtracer_counter_id[NUM_CRASH_STRINGS] = { 0 };
Ted Kremenek29b72842010-01-07 22:49:05 +000047static const char *crashtracer_strings[NUM_CRASH_STRINGS] = { 0 };
48static const char *agg_crashtracer_strings[NUM_CRASH_STRINGS] = { 0 };
49
50static unsigned SetCrashTracerInfo(const char *str,
51 llvm::SmallString<1024> &AggStr) {
52
Ted Kremenek254ba7c2010-01-07 23:13:53 +000053 unsigned slot = 0;
Ted Kremenek29b72842010-01-07 22:49:05 +000054 while (crashtracer_strings[slot]) {
55 if (++slot == NUM_CRASH_STRINGS)
56 slot = 0;
57 }
58 crashtracer_strings[slot] = str;
Ted Kremenek254ba7c2010-01-07 23:13:53 +000059 crashtracer_counter_id[slot] = ++crashtracer_counter;
Ted Kremenek29b72842010-01-07 22:49:05 +000060
61 // We need to create an aggregate string because multiple threads
62 // may be in this method at one time. The crash reporter string
63 // will attempt to overapproximate the set of in-flight invocations
64 // of this function. Race conditions can still cause this goal
65 // to not be achieved.
66 {
67 llvm::raw_svector_ostream Out(AggStr);
68 for (unsigned i = 0; i < NUM_CRASH_STRINGS; ++i)
69 if (crashtracer_strings[i]) Out << crashtracer_strings[i] << '\n';
70 }
71 __crashreporter_info__ = agg_crashtracer_strings[slot] = AggStr.c_str();
72 return slot;
73}
74
75static void ResetCrashTracerInfo(unsigned slot) {
Ted Kremenek254ba7c2010-01-07 23:13:53 +000076 unsigned max_slot = 0;
77 unsigned max_value = 0;
78
79 crashtracer_strings[slot] = agg_crashtracer_strings[slot] = 0;
80
81 for (unsigned i = 0 ; i < NUM_CRASH_STRINGS; ++i)
82 if (agg_crashtracer_strings[i] &&
83 crashtracer_counter_id[i] > max_value) {
84 max_slot = i;
85 max_value = crashtracer_counter_id[i];
Ted Kremenek29b72842010-01-07 22:49:05 +000086 }
Ted Kremenek254ba7c2010-01-07 23:13:53 +000087
88 __crashreporter_info__ = agg_crashtracer_strings[max_slot];
Ted Kremenek29b72842010-01-07 22:49:05 +000089}
90
91namespace {
92class ArgsCrashTracerInfo {
93 llvm::SmallString<1024> CrashString;
94 llvm::SmallString<1024> AggregateString;
95 unsigned crashtracerSlot;
96public:
97 ArgsCrashTracerInfo(llvm::SmallVectorImpl<const char*> &Args)
98 : crashtracerSlot(0)
99 {
100 {
101 llvm::raw_svector_ostream Out(CrashString);
102 Out << "ClangCIndex [createTranslationUnitFromSourceFile]: clang";
103 for (llvm::SmallVectorImpl<const char*>::iterator I=Args.begin(),
104 E=Args.end(); I!=E; ++I)
105 Out << ' ' << *I;
106 }
107 crashtracerSlot = SetCrashTracerInfo(CrashString.c_str(),
108 AggregateString);
109 }
110
111 ~ArgsCrashTracerInfo() {
112 ResetCrashTracerInfo(crashtracerSlot);
113 }
114};
115}
116#endif
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000117#endif
118
Douglas Gregor1db19de2010-01-19 21:36:55 +0000119typedef llvm::PointerIntPair<ASTContext *, 1, bool> CXSourceLocationPtr;
120
Douglas Gregor98258af2010-01-18 22:46:11 +0000121/// \brief Translate a Clang source location into a CIndex source location.
Douglas Gregor1db19de2010-01-19 21:36:55 +0000122static CXSourceLocation translateSourceLocation(ASTContext &Context,
123 SourceLocation Loc,
124 bool AtEnd = false) {
125 CXSourceLocationPtr Ptr(&Context, AtEnd);
126 CXSourceLocation Result = { Ptr.getOpaqueValue(), Loc.getRawEncoding() };
127 return Result;
Douglas Gregor98258af2010-01-18 22:46:11 +0000128}
129
Douglas Gregora7bde202010-01-19 00:34:46 +0000130/// \brief Translate a Clang source range into a CIndex source range.
Douglas Gregor1db19de2010-01-19 21:36:55 +0000131static CXSourceRange translateSourceRange(ASTContext &Context, SourceRange R) {
132 CXSourceRange Result = { &Context,
133 R.getBegin().getRawEncoding(),
134 R.getEnd().getRawEncoding() };
135 return Result;
Douglas Gregora7bde202010-01-19 00:34:46 +0000136}
137
Douglas Gregorb9790342010-01-22 21:44:22 +0000138static SourceLocation translateSourceLocation(CXSourceLocation L) {
139 return SourceLocation::getFromRawEncoding(L.int_data);
140}
141
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000142static SourceRange translateSourceRange(CXSourceRange R) {
143 return SourceRange(SourceLocation::getFromRawEncoding(R.begin_int_data),
144 SourceLocation::getFromRawEncoding(R.end_int_data));
145}
146
147/// \brief The result of comparing two source ranges.
148enum RangeComparisonResult {
149 /// \brief Either the ranges overlap or one of the ranges is invalid.
150 RangeOverlap,
151
152 /// \brief The first range ends before the second range starts.
153 RangeBefore,
154
155 /// \brief The first range starts after the second range ends.
156 RangeAfter
157};
158
159/// \brief Compare two source ranges to determine their relative position in
160/// the translation unit.
161static RangeComparisonResult RangeCompare(SourceManager &SM,
162 SourceRange R1,
163 SourceRange R2) {
164 assert(R1.isValid() && "First range is invalid?");
165 assert(R2.isValid() && "Second range is invalid?");
166 if (SM.isBeforeInTranslationUnit(R1.getEnd(), R2.getBegin()))
167 return RangeBefore;
168 if (SM.isBeforeInTranslationUnit(R2.getEnd(), R1.getBegin()))
169 return RangeAfter;
170 return RangeOverlap;
171}
172
Douglas Gregor1db19de2010-01-19 21:36:55 +0000173
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000174//===----------------------------------------------------------------------===//
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000175// Cursor visitor.
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000176//===----------------------------------------------------------------------===//
177
Steve Naroff89922f82009-08-31 00:59:03 +0000178namespace {
Ted Kremenekedc8aa62010-01-16 00:36:30 +0000179
Douglas Gregorb1373d02010-01-20 20:59:29 +0000180// Cursor visitor.
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000181class CursorVisitor : public DeclVisitor<CursorVisitor, bool>,
Douglas Gregora59e3902010-01-21 23:27:09 +0000182 public TypeLocVisitor<CursorVisitor, bool>,
183 public StmtVisitor<CursorVisitor, bool>
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000184{
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000185 /// \brief The translation unit we are traversing.
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000186 ASTUnit *TU;
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000187
188 /// \brief The parent cursor whose children we are traversing.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000189 CXCursor Parent;
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000190
191 /// \brief The declaration that serves at the parent of any statement or
192 /// expression nodes.
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000193 Decl *StmtParent;
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000194
195 /// \brief The visitor function.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000196 CXCursorVisitor Visitor;
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000197
198 /// \brief The opaque client data, to be passed along to the visitor.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000199 CXClientData ClientData;
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000200
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000201 // MaxPCHLevel - the maximum PCH level of declarations that we will pass on
202 // to the visitor. Declarations with a PCH level greater than this value will
203 // be suppressed.
204 unsigned MaxPCHLevel;
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000205
206 /// \brief When valid, a source range to which the cursor should restrict
207 /// its search.
208 SourceRange RegionOfInterest;
209
Douglas Gregorb1373d02010-01-20 20:59:29 +0000210 using DeclVisitor<CursorVisitor, bool>::Visit;
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000211 using TypeLocVisitor<CursorVisitor, bool>::Visit;
Douglas Gregora59e3902010-01-21 23:27:09 +0000212 using StmtVisitor<CursorVisitor, bool>::Visit;
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000213
214 /// \brief Determine whether this particular source range comes before, comes
215 /// after, or overlaps the region of interest.
216 ///
217 /// \param R a source range retrieved from the abstract syntax tree.
218 RangeComparisonResult CompareRegionOfInterest(SourceRange R);
219
220 /// \brief Determine whether this particular source range comes before, comes
221 /// after, or overlaps the region of interest.
222 ///
223 /// \param CXR a source range retrieved from a cursor.
224 RangeComparisonResult CompareRegionOfInterest(CXSourceRange CXR);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000225
Steve Naroff89922f82009-08-31 00:59:03 +0000226public:
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000227 CursorVisitor(ASTUnit *TU, CXCursorVisitor Visitor, CXClientData ClientData,
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000228 unsigned MaxPCHLevel,
229 SourceRange RegionOfInterest = SourceRange())
230 : TU(TU), Visitor(Visitor), ClientData(ClientData),
231 MaxPCHLevel(MaxPCHLevel), RegionOfInterest(RegionOfInterest)
Douglas Gregorb1373d02010-01-20 20:59:29 +0000232 {
233 Parent.kind = CXCursor_NoDeclFound;
234 Parent.data[0] = 0;
235 Parent.data[1] = 0;
236 Parent.data[2] = 0;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000237 StmtParent = 0;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000238 }
239
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000240 bool Visit(CXCursor Cursor, bool CheckedRegionOfInterest = false);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000241 bool VisitChildren(CXCursor Parent);
242
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000243 // Declaration visitors
Douglas Gregorb1373d02010-01-20 20:59:29 +0000244 bool VisitDeclContext(DeclContext *DC);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000245 bool VisitTranslationUnitDecl(TranslationUnitDecl *D);
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000246 bool VisitTypedefDecl(TypedefDecl *D);
247 bool VisitTagDecl(TagDecl *D);
248 bool VisitEnumConstantDecl(EnumConstantDecl *D);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000249 bool VisitDeclaratorDecl(DeclaratorDecl *DD);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000250 bool VisitFunctionDecl(FunctionDecl *ND);
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000251 bool VisitFieldDecl(FieldDecl *D);
252 bool VisitVarDecl(VarDecl *);
253 bool VisitObjCMethodDecl(ObjCMethodDecl *ND);
Douglas Gregora59e3902010-01-21 23:27:09 +0000254 bool VisitObjCContainerDecl(ObjCContainerDecl *D);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000255 bool VisitObjCCategoryDecl(ObjCCategoryDecl *ND);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000256 bool VisitObjCProtocolDecl(ObjCProtocolDecl *PID);
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000257 bool VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
258 bool VisitObjCImplDecl(ObjCImplDecl *D);
259 bool VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
260 bool VisitObjCImplementationDecl(ObjCImplementationDecl *D);
261 // FIXME: ObjCPropertyDecl requires TypeSourceInfo, getter/setter locations,
262 // etc.
263 // FIXME: ObjCCompatibleAliasDecl requires aliased-class locations.
264 bool VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D);
265 bool VisitObjCClassDecl(ObjCClassDecl *D);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000266
267 // Type visitors
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000268 // FIXME: QualifiedTypeLoc doesn't provide any location information
269 bool VisitBuiltinTypeLoc(BuiltinTypeLoc TL);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000270 bool VisitTypedefTypeLoc(TypedefTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000271 bool VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL);
272 bool VisitTagTypeLoc(TagTypeLoc TL);
273 // FIXME: TemplateTypeParmTypeLoc doesn't provide any location information
274 bool VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL);
275 bool VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL);
276 bool VisitPointerTypeLoc(PointerTypeLoc TL);
277 bool VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL);
278 bool VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL);
279 bool VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL);
280 bool VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL);
281 bool VisitFunctionTypeLoc(FunctionTypeLoc TL);
282 bool VisitArrayTypeLoc(ArrayTypeLoc TL);
Douglas Gregor2332c112010-01-21 20:48:56 +0000283 // FIXME: Implement for TemplateSpecializationTypeLoc
284 // FIXME: Implement visitors here when the unimplemented TypeLocs get
285 // implemented
286 bool VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL);
287 bool VisitTypeOfTypeLoc(TypeOfTypeLoc TL);
Douglas Gregora59e3902010-01-21 23:27:09 +0000288
289 // Statement visitors
290 bool VisitStmt(Stmt *S);
291 bool VisitDeclStmt(DeclStmt *S);
Douglas Gregorf5bab412010-01-22 01:00:11 +0000292 // FIXME: LabelStmt label?
293 bool VisitIfStmt(IfStmt *S);
294 bool VisitSwitchStmt(SwitchStmt *S);
Douglas Gregor263b47b2010-01-25 16:12:32 +0000295 bool VisitWhileStmt(WhileStmt *S);
296 bool VisitForStmt(ForStmt *S);
Douglas Gregor336fd812010-01-23 00:40:08 +0000297
298 // Expression visitors
299 bool VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E);
300 bool VisitExplicitCastExpr(ExplicitCastExpr *E);
301 bool VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
Steve Naroff89922f82009-08-31 00:59:03 +0000302};
Douglas Gregorb1373d02010-01-20 20:59:29 +0000303
Ted Kremenekab188932010-01-05 19:32:54 +0000304} // end anonymous namespace
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000305
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000306RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
307 assert(RegionOfInterest.isValid() && "RangeCompare called with invalid range");
308 if (R.isInvalid())
309 return RangeOverlap;
310
311 // Move the end of the input range to the end of the last token in that
312 // range.
313 R.setEnd(TU->getPreprocessor().getLocForEndOfToken(R.getEnd(), 1));
314 return RangeCompare(TU->getSourceManager(), R, RegionOfInterest);
315}
316
317RangeComparisonResult CursorVisitor::CompareRegionOfInterest(CXSourceRange CXR) {
318 return CompareRegionOfInterest(translateSourceRange(CXR));
319}
320
Douglas Gregorb1373d02010-01-20 20:59:29 +0000321/// \brief Visit the given cursor and, if requested by the visitor,
322/// its children.
323///
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000324/// \param Cursor the cursor to visit.
325///
326/// \param CheckRegionOfInterest if true, then the caller already checked that
327/// this cursor is within the region of interest.
328///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000329/// \returns true if the visitation should be aborted, false if it
330/// should continue.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000331bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
Douglas Gregorb1373d02010-01-20 20:59:29 +0000332 if (clang_isInvalid(Cursor.kind))
333 return false;
334
335 if (clang_isDeclaration(Cursor.kind)) {
336 Decl *D = getCursorDecl(Cursor);
337 assert(D && "Invalid declaration cursor");
338 if (D->getPCHLevel() > MaxPCHLevel)
339 return false;
340
341 if (D->isImplicit())
342 return false;
343 }
344
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000345 // If we have a range of interest, and this cursor doesn't intersect with it,
346 // we're done.
347 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
348 CXSourceRange Range = clang_getCursorExtent(Cursor);
349 if (translateSourceRange(Range).isInvalid() ||
350 CompareRegionOfInterest(Range))
351 return false;
352 }
353
Douglas Gregorb1373d02010-01-20 20:59:29 +0000354 switch (Visitor(Cursor, Parent, ClientData)) {
355 case CXChildVisit_Break:
356 return true;
357
358 case CXChildVisit_Continue:
359 return false;
360
361 case CXChildVisit_Recurse:
362 return VisitChildren(Cursor);
363 }
364
Douglas Gregorfd643772010-01-25 16:45:46 +0000365 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000366}
367
368/// \brief Visit the children of the given cursor.
369///
370/// \returns true if the visitation should be aborted, false if it
371/// should continue.
372bool CursorVisitor::VisitChildren(CXCursor Cursor) {
Douglas Gregora59e3902010-01-21 23:27:09 +0000373 if (clang_isReference(Cursor.kind)) {
374 // By definition, references have no children.
375 return false;
376 }
377
Douglas Gregorb1373d02010-01-20 20:59:29 +0000378 // Set the Parent field to Cursor, then back to its old value once we're
379 // done.
380 class SetParentRAII {
381 CXCursor &Parent;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000382 Decl *&StmtParent;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000383 CXCursor OldParent;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000384
Douglas Gregorb1373d02010-01-20 20:59:29 +0000385 public:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000386 SetParentRAII(CXCursor &Parent, Decl *&StmtParent, CXCursor NewParent)
387 : Parent(Parent), StmtParent(StmtParent), OldParent(Parent)
Douglas Gregorb1373d02010-01-20 20:59:29 +0000388 {
389 Parent = NewParent;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000390 if (clang_isDeclaration(Parent.kind))
391 StmtParent = getCursorDecl(Parent);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000392 }
393
394 ~SetParentRAII() {
395 Parent = OldParent;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000396 if (clang_isDeclaration(Parent.kind))
397 StmtParent = getCursorDecl(Parent);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000398 }
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000399 } SetParent(Parent, StmtParent, Cursor);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000400
401 if (clang_isDeclaration(Cursor.kind)) {
402 Decl *D = getCursorDecl(Cursor);
403 assert(D && "Invalid declaration cursor");
404 return Visit(D);
405 }
406
Douglas Gregora59e3902010-01-21 23:27:09 +0000407 if (clang_isStatement(Cursor.kind))
408 return Visit(getCursorStmt(Cursor));
409 if (clang_isExpression(Cursor.kind))
410 return Visit(getCursorExpr(Cursor));
411
Douglas Gregorb1373d02010-01-20 20:59:29 +0000412 if (clang_isTranslationUnit(Cursor.kind)) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000413 ASTUnit *CXXUnit = getCursorASTUnit(Cursor);
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000414 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
415 RegionOfInterest.isInvalid()) {
Douglas Gregor7b691f332010-01-20 21:13:59 +0000416 const std::vector<Decl*> &TLDs = CXXUnit->getTopLevelDecls();
417 for (std::vector<Decl*>::const_iterator it = TLDs.begin(),
418 ie = TLDs.end(); it != ie; ++it) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000419 if (Visit(MakeCXCursor(*it, CXXUnit), true))
Douglas Gregor7b691f332010-01-20 21:13:59 +0000420 return true;
421 }
422 } else {
423 return VisitDeclContext(
Douglas Gregorb1373d02010-01-20 20:59:29 +0000424 CXXUnit->getASTContext().getTranslationUnitDecl());
Douglas Gregor7b691f332010-01-20 21:13:59 +0000425 }
426
427 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000428 }
Douglas Gregora59e3902010-01-21 23:27:09 +0000429
Douglas Gregorb1373d02010-01-20 20:59:29 +0000430 // Nothing to visit at the moment.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000431 return false;
432}
433
Douglas Gregorb1373d02010-01-20 20:59:29 +0000434bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000435 for (DeclContext::decl_iterator
Douglas Gregorb1373d02010-01-20 20:59:29 +0000436 I = DC->decls_begin(), E = DC->decls_end(); I != E; ++I) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000437 if (RegionOfInterest.isValid()) {
438 SourceRange R = (*I)->getSourceRange();
439 if (R.isInvalid())
440 continue;
441
442 switch (CompareRegionOfInterest(R)) {
443 case RangeBefore:
444 // This declaration comes before the region of interest; skip it.
445 continue;
446
447 case RangeAfter:
448 // This declaration comes after the region of interest; we're done.
449 return false;
450
451 case RangeOverlap:
452 // This declaration overlaps the region of interest; visit it.
453 break;
454 }
455 }
456
457 if (Visit(MakeCXCursor(*I, TU), true))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000458 return true;
459 }
460
461 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000462}
463
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000464bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
465 llvm_unreachable("Translation units are visited directly by Visit()");
466 return false;
467}
468
469bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
470 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
471 return Visit(TSInfo->getTypeLoc());
472
473 return false;
474}
475
476bool CursorVisitor::VisitTagDecl(TagDecl *D) {
477 return VisitDeclContext(D);
478}
479
480bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
481 if (Expr *Init = D->getInitExpr())
482 return Visit(MakeCXCursor(Init, StmtParent, TU));
483 return false;
484}
485
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000486bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
487 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
488 if (Visit(TSInfo->getTypeLoc()))
489 return true;
490
491 return false;
492}
493
Douglas Gregorb1373d02010-01-20 20:59:29 +0000494bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000495 if (VisitDeclaratorDecl(ND))
496 return true;
497
Douglas Gregora59e3902010-01-21 23:27:09 +0000498 if (ND->isThisDeclarationADefinition() &&
499 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
500 return true;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000501
502 return false;
503}
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000504
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000505bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
506 if (VisitDeclaratorDecl(D))
507 return true;
508
509 if (Expr *BitWidth = D->getBitWidth())
510 return Visit(MakeCXCursor(BitWidth, StmtParent, TU));
511
512 return false;
513}
514
515bool CursorVisitor::VisitVarDecl(VarDecl *D) {
516 if (VisitDeclaratorDecl(D))
517 return true;
518
519 if (Expr *Init = D->getInit())
520 return Visit(MakeCXCursor(Init, StmtParent, TU));
521
522 return false;
523}
524
525bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
526 // FIXME: We really need a TypeLoc covering Objective-C method declarations.
527 // At the moment, we don't have information about locations in the return
528 // type.
529 for (ObjCMethodDecl::param_iterator P = ND->param_begin(),
530 PEnd = ND->param_end();
531 P != PEnd; ++P) {
532 if (Visit(MakeCXCursor(*P, TU)))
533 return true;
534 }
535
536 if (ND->isThisDeclarationADefinition() &&
537 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
538 return true;
539
540 return false;
541}
542
Douglas Gregora59e3902010-01-21 23:27:09 +0000543bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
544 return VisitDeclContext(D);
545}
546
Douglas Gregorb1373d02010-01-20 20:59:29 +0000547bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000548 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
549 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000550 return true;
551
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000552 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
553 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
554 E = ND->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000555 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000556 return true;
557
Douglas Gregora59e3902010-01-21 23:27:09 +0000558 return VisitObjCContainerDecl(ND);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000559}
560
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000561bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
562 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
563 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
564 E = PID->protocol_end(); I != E; ++I, ++PL)
565 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
566 return true;
567
568 return VisitObjCContainerDecl(PID);
569}
570
Douglas Gregorb1373d02010-01-20 20:59:29 +0000571bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000572 // Issue callbacks for super class.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000573 if (D->getSuperClass() &&
574 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000575 D->getSuperClassLoc(),
576 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000577 return true;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000578
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000579 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
580 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
581 E = D->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000582 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000583 return true;
584
Douglas Gregora59e3902010-01-21 23:27:09 +0000585 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000586}
587
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000588bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
589 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000590}
591
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000592bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
593 if (Visit(MakeCursorObjCClassRef(D->getCategoryDecl()->getClassInterface(),
594 D->getLocation(), TU)))
595 return true;
596
597 return VisitObjCImplDecl(D);
598}
599
600bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
601#if 0
602 // Issue callbacks for super class.
603 // FIXME: No source location information!
604 if (D->getSuperClass() &&
605 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
606 D->getSuperClassLoc(),
607 TU)))
608 return true;
609#endif
610
611 return VisitObjCImplDecl(D);
612}
613
614bool CursorVisitor::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D) {
615 ObjCForwardProtocolDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
616 for (ObjCForwardProtocolDecl::protocol_iterator I = D->protocol_begin(),
617 E = D->protocol_end();
618 I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000619 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000620 return true;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000621
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000622 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000623}
624
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000625bool CursorVisitor::VisitObjCClassDecl(ObjCClassDecl *D) {
626 for (ObjCClassDecl::iterator C = D->begin(), CEnd = D->end(); C != CEnd; ++C)
627 if (Visit(MakeCursorObjCClassRef(C->getInterface(), C->getLocation(), TU)))
628 return true;
629
630 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000631}
632
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000633bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
634 ASTContext &Context = TU->getASTContext();
635
636 // Some builtin types (such as Objective-C's "id", "sel", and
637 // "Class") have associated declarations. Create cursors for those.
638 QualType VisitType;
639 switch (TL.getType()->getAs<BuiltinType>()->getKind()) {
640 case BuiltinType::Void:
641 case BuiltinType::Bool:
642 case BuiltinType::Char_U:
643 case BuiltinType::UChar:
644 case BuiltinType::Char16:
645 case BuiltinType::Char32:
646 case BuiltinType::UShort:
647 case BuiltinType::UInt:
648 case BuiltinType::ULong:
649 case BuiltinType::ULongLong:
650 case BuiltinType::UInt128:
651 case BuiltinType::Char_S:
652 case BuiltinType::SChar:
653 case BuiltinType::WChar:
654 case BuiltinType::Short:
655 case BuiltinType::Int:
656 case BuiltinType::Long:
657 case BuiltinType::LongLong:
658 case BuiltinType::Int128:
659 case BuiltinType::Float:
660 case BuiltinType::Double:
661 case BuiltinType::LongDouble:
662 case BuiltinType::NullPtr:
663 case BuiltinType::Overload:
664 case BuiltinType::Dependent:
665 break;
666
667 case BuiltinType::UndeducedAuto: // FIXME: Deserves a cursor?
668 break;
669
670 case BuiltinType::ObjCId:
671 VisitType = Context.getObjCIdType();
672 break;
673
674 case BuiltinType::ObjCClass:
675 VisitType = Context.getObjCClassType();
676 break;
677
678 case BuiltinType::ObjCSel:
679 VisitType = Context.getObjCSelType();
680 break;
681 }
682
683 if (!VisitType.isNull()) {
684 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
685 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
686 TU));
687 }
688
689 return false;
690}
691
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000692bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
693 return Visit(MakeCursorTypeRef(TL.getTypedefDecl(), TL.getNameLoc(), TU));
694}
695
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000696bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
697 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
698}
699
700bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
701 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
702}
703
704bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
705 if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
706 return true;
707
708 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
709 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
710 TU)))
711 return true;
712 }
713
714 return false;
715}
716
717bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
718 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseTypeLoc()))
719 return true;
720
721 if (TL.hasProtocolsAsWritten()) {
722 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
723 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I),
724 TL.getProtocolLoc(I),
725 TU)))
726 return true;
727 }
728 }
729
730 return false;
731}
732
733bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
734 return Visit(TL.getPointeeLoc());
735}
736
737bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
738 return Visit(TL.getPointeeLoc());
739}
740
741bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
742 return Visit(TL.getPointeeLoc());
743}
744
745bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
746 return Visit(TL.getPointeeLoc());
747}
748
749bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
750 return Visit(TL.getPointeeLoc());
751}
752
753bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
754 if (Visit(TL.getResultLoc()))
755 return true;
756
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000757 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
758 if (Visit(MakeCXCursor(TL.getArg(I), TU)))
759 return true;
760
761 return false;
762}
763
764bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
765 if (Visit(TL.getElementLoc()))
766 return true;
767
768 if (Expr *Size = TL.getSizeExpr())
769 return Visit(MakeCXCursor(Size, StmtParent, TU));
770
771 return false;
772}
773
Douglas Gregor2332c112010-01-21 20:48:56 +0000774bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
775 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
776}
777
778bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
779 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
780 return Visit(TSInfo->getTypeLoc());
781
782 return false;
783}
784
Douglas Gregora59e3902010-01-21 23:27:09 +0000785bool CursorVisitor::VisitStmt(Stmt *S) {
786 for (Stmt::child_iterator Child = S->child_begin(), ChildEnd = S->child_end();
787 Child != ChildEnd; ++Child) {
Daniel Dunbar54d67ca2010-01-25 00:40:30 +0000788 if (*Child && Visit(MakeCXCursor(*Child, StmtParent, TU)))
Douglas Gregora59e3902010-01-21 23:27:09 +0000789 return true;
790 }
791
792 return false;
793}
794
795bool CursorVisitor::VisitDeclStmt(DeclStmt *S) {
796 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
797 D != DEnd; ++D) {
Douglas Gregor263b47b2010-01-25 16:12:32 +0000798 if (*D && Visit(MakeCXCursor(*D, TU)))
Douglas Gregora59e3902010-01-21 23:27:09 +0000799 return true;
800 }
801
802 return false;
803}
804
Douglas Gregorf5bab412010-01-22 01:00:11 +0000805bool CursorVisitor::VisitIfStmt(IfStmt *S) {
806 if (VarDecl *Var = S->getConditionVariable()) {
807 if (Visit(MakeCXCursor(Var, TU)))
808 return true;
Douglas Gregor263b47b2010-01-25 16:12:32 +0000809 }
Douglas Gregorf5bab412010-01-22 01:00:11 +0000810
Douglas Gregor263b47b2010-01-25 16:12:32 +0000811 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
812 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +0000813 if (S->getThen() && Visit(MakeCXCursor(S->getThen(), StmtParent, TU)))
814 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +0000815 if (S->getElse() && Visit(MakeCXCursor(S->getElse(), StmtParent, TU)))
816 return true;
817
818 return false;
819}
820
821bool CursorVisitor::VisitSwitchStmt(SwitchStmt *S) {
822 if (VarDecl *Var = S->getConditionVariable()) {
823 if (Visit(MakeCXCursor(Var, TU)))
824 return true;
Douglas Gregor263b47b2010-01-25 16:12:32 +0000825 }
826
827 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
828 return true;
829 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
830 return true;
831
832 return false;
833}
834
835bool CursorVisitor::VisitWhileStmt(WhileStmt *S) {
836 if (VarDecl *Var = S->getConditionVariable()) {
837 if (Visit(MakeCXCursor(Var, TU)))
838 return true;
839 }
840
841 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
842 return true;
843 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
Douglas Gregorf5bab412010-01-22 01:00:11 +0000844 return true;
845
Douglas Gregor263b47b2010-01-25 16:12:32 +0000846 return false;
847}
848
849bool CursorVisitor::VisitForStmt(ForStmt *S) {
850 if (S->getInit() && Visit(MakeCXCursor(S->getInit(), StmtParent, TU)))
851 return true;
852 if (VarDecl *Var = S->getConditionVariable()) {
853 if (Visit(MakeCXCursor(Var, TU)))
854 return true;
855 }
856
857 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
858 return true;
859 if (S->getInc() && Visit(MakeCXCursor(S->getInc(), StmtParent, TU)))
860 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +0000861 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
862 return true;
863
864 return false;
865}
866
Douglas Gregor336fd812010-01-23 00:40:08 +0000867bool CursorVisitor::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E) {
868 if (E->isArgumentType()) {
869 if (TypeSourceInfo *TSInfo = E->getArgumentTypeInfo())
870 return Visit(TSInfo->getTypeLoc());
871
872 return false;
873 }
874
875 return VisitExpr(E);
876}
877
878bool CursorVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
879 if (TypeSourceInfo *TSInfo = E->getTypeInfoAsWritten())
880 if (Visit(TSInfo->getTypeLoc()))
881 return true;
882
883 return VisitCastExpr(E);
884}
885
886bool CursorVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
887 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
888 if (Visit(TSInfo->getTypeLoc()))
889 return true;
890
891 return VisitExpr(E);
892}
893
Daniel Dunbar140fce22010-01-12 02:34:07 +0000894CXString CIndexer::createCXString(const char *String, bool DupString){
Benjamin Kramer62cf3222009-11-09 19:13:48 +0000895 CXString Str;
896 if (DupString) {
897 Str.Spelling = strdup(String);
898 Str.MustFreeString = 1;
899 } else {
900 Str.Spelling = String;
901 Str.MustFreeString = 0;
902 }
903 return Str;
904}
905
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000906extern "C" {
Steve Naroffe56b4ba2009-10-20 14:46:24 +0000907CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000908 int displayDiagnostics) {
Douglas Gregora030b7c2010-01-22 20:35:53 +0000909 CIndexer *CIdxr = new CIndexer();
Steve Naroffe56b4ba2009-10-20 14:46:24 +0000910 if (excludeDeclarationsFromPCH)
911 CIdxr->setOnlyLocalDecls();
912 if (displayDiagnostics)
913 CIdxr->setDisplayDiagnostics();
914 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +0000915}
916
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000917void clang_disposeIndex(CXIndex CIdx) {
Steve Naroff2bd6b9f2009-09-17 18:33:27 +0000918 assert(CIdx && "Passed null CXIndex");
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000919 delete static_cast<CIndexer *>(CIdx);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +0000920}
921
Daniel Dunbar8506dde2009-12-03 01:54:28 +0000922void clang_setUseExternalASTGeneration(CXIndex CIdx, int value) {
923 assert(CIdx && "Passed null CXIndex");
924 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
925 CXXIdx->setUseExternalASTGeneration(value);
926}
927
Steve Naroff50398192009-08-28 15:28:48 +0000928// FIXME: need to pass back error info.
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000929CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
930 const char *ast_filename) {
Steve Naroff50398192009-08-28 15:28:48 +0000931 assert(CIdx && "Passed null CXIndex");
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000932 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000933
Daniel Dunbar5262fda2009-12-03 01:45:44 +0000934 return ASTUnit::LoadFromPCHFile(ast_filename, CXXIdx->getDiags(),
935 CXXIdx->getOnlyLocalDecls(),
936 /* UseBumpAllocator = */ true);
Steve Naroff600866c2009-08-27 19:51:58 +0000937}
938
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000939CXTranslationUnit
940clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
941 const char *source_filename,
942 int num_command_line_args,
Douglas Gregor4db64a42010-01-23 00:14:00 +0000943 const char **command_line_args,
944 unsigned num_unsaved_files,
945 struct CXUnsavedFile *unsaved_files) {
Steve Naroffe56b4ba2009-10-20 14:46:24 +0000946 assert(CIdx && "Passed null CXIndex");
947 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
948
Douglas Gregor4db64a42010-01-23 00:14:00 +0000949 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
950 for (unsigned I = 0; I != num_unsaved_files; ++I) {
951 const llvm::MemoryBuffer *Buffer
952 = llvm::MemoryBuffer::getMemBuffer(unsaved_files[I].Contents,
953 unsaved_files[I].Contents + unsaved_files[I].Length,
954 unsaved_files[I].Filename);
955 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
956 Buffer));
957 }
958
Daniel Dunbar8506dde2009-12-03 01:54:28 +0000959 if (!CXXIdx->getUseExternalASTGeneration()) {
960 llvm::SmallVector<const char *, 16> Args;
961
962 // The 'source_filename' argument is optional. If the caller does not
963 // specify it then it is assumed that the source file is specified
964 // in the actual argument list.
965 if (source_filename)
966 Args.push_back(source_filename);
967 Args.insert(Args.end(), command_line_args,
968 command_line_args + num_command_line_args);
969
Daniel Dunbar94220972009-12-05 02:17:18 +0000970 unsigned NumErrors = CXXIdx->getDiags().getNumErrors();
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000971
Ted Kremenek29b72842010-01-07 22:49:05 +0000972#ifdef USE_CRASHTRACER
973 ArgsCrashTracerInfo ACTI(Args);
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000974#endif
975
Daniel Dunbar94220972009-12-05 02:17:18 +0000976 llvm::OwningPtr<ASTUnit> Unit(
977 ASTUnit::LoadFromCommandLine(Args.data(), Args.data() + Args.size(),
Daniel Dunbar869824e2009-12-13 03:46:13 +0000978 CXXIdx->getDiags(),
979 CXXIdx->getClangResourcesPath(),
Daniel Dunbar94220972009-12-05 02:17:18 +0000980 CXXIdx->getOnlyLocalDecls(),
Douglas Gregor4db64a42010-01-23 00:14:00 +0000981 /* UseBumpAllocator = */ true,
982 RemappedFiles.data(),
983 RemappedFiles.size()));
Ted Kremenek29b72842010-01-07 22:49:05 +0000984
Daniel Dunbar94220972009-12-05 02:17:18 +0000985 // FIXME: Until we have broader testing, just drop the entire AST if we
986 // encountered an error.
987 if (NumErrors != CXXIdx->getDiags().getNumErrors())
988 return 0;
989
990 return Unit.take();
Daniel Dunbar8506dde2009-12-03 01:54:28 +0000991 }
992
Ted Kremenek139ba862009-10-22 00:03:57 +0000993 // Build up the arguments for invoking 'clang'.
Ted Kremenek74cd0692009-10-15 23:21:22 +0000994 std::vector<const char *> argv;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000995
Ted Kremenek139ba862009-10-22 00:03:57 +0000996 // First add the complete path to the 'clang' executable.
997 llvm::sys::Path ClangPath = static_cast<CIndexer *>(CIdx)->getClangPath();
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000998 argv.push_back(ClangPath.c_str());
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000999
Ted Kremenek139ba862009-10-22 00:03:57 +00001000 // Add the '-emit-ast' option as our execution mode for 'clang'.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001001 argv.push_back("-emit-ast");
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001002
Ted Kremenek139ba862009-10-22 00:03:57 +00001003 // The 'source_filename' argument is optional. If the caller does not
1004 // specify it then it is assumed that the source file is specified
1005 // in the actual argument list.
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001006 if (source_filename)
1007 argv.push_back(source_filename);
Ted Kremenek139ba862009-10-22 00:03:57 +00001008
Steve Naroff37b5ac22009-10-15 20:50:09 +00001009 // Generate a temporary name for the AST file.
Ted Kremenek139ba862009-10-22 00:03:57 +00001010 argv.push_back("-o");
Steve Naroff37b5ac22009-10-15 20:50:09 +00001011 char astTmpFile[L_tmpnam];
Ted Kremenek74cd0692009-10-15 23:21:22 +00001012 argv.push_back(tmpnam(astTmpFile));
Ted Kremenek139ba862009-10-22 00:03:57 +00001013
Douglas Gregor4db64a42010-01-23 00:14:00 +00001014 // Remap any unsaved files to temporary files.
1015 std::vector<llvm::sys::Path> TemporaryFiles;
1016 std::vector<std::string> RemapArgs;
1017 if (RemapFiles(num_unsaved_files, unsaved_files, RemapArgs, TemporaryFiles))
1018 return 0;
1019
1020 // The pointers into the elements of RemapArgs are stable because we
1021 // won't be adding anything to RemapArgs after this point.
1022 for (unsigned i = 0, e = RemapArgs.size(); i != e; ++i)
1023 argv.push_back(RemapArgs[i].c_str());
1024
Ted Kremenek139ba862009-10-22 00:03:57 +00001025 // Process the compiler options, stripping off '-o', '-c', '-fsyntax-only'.
1026 for (int i = 0; i < num_command_line_args; ++i)
1027 if (const char *arg = command_line_args[i]) {
1028 if (strcmp(arg, "-o") == 0) {
1029 ++i; // Also skip the matching argument.
1030 continue;
1031 }
1032 if (strcmp(arg, "-emit-ast") == 0 ||
1033 strcmp(arg, "-c") == 0 ||
1034 strcmp(arg, "-fsyntax-only") == 0) {
1035 continue;
1036 }
1037
1038 // Keep the argument.
1039 argv.push_back(arg);
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001040 }
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001041
Ted Kremenek139ba862009-10-22 00:03:57 +00001042 // Add the null terminator.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001043 argv.push_back(NULL);
1044
Ted Kremenekfeb15e32009-10-26 22:14:08 +00001045 // Invoke 'clang'.
1046 llvm::sys::Path DevNull; // leave empty, causes redirection to /dev/null
1047 // on Unix or NUL (Windows).
Ted Kremenek379afec2009-10-22 03:24:01 +00001048 std::string ErrMsg;
Ted Kremenekc46e4632009-10-19 22:27:32 +00001049 const llvm::sys::Path *Redirects[] = { &DevNull, &DevNull, &DevNull, NULL };
Ted Kremenek379afec2009-10-22 03:24:01 +00001050 llvm::sys::Program::ExecuteAndWait(ClangPath, &argv[0], /* env */ NULL,
1051 /* redirects */ !CXXIdx->getDisplayDiagnostics() ? &Redirects[0] : NULL,
1052 /* secondsToWait */ 0, /* memoryLimits */ 0, &ErrMsg);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001053
Ted Kremenek0854d702009-11-10 19:18:52 +00001054 if (CXXIdx->getDisplayDiagnostics() && !ErrMsg.empty()) {
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001055 llvm::errs() << "clang_createTranslationUnitFromSourceFile: " << ErrMsg
Daniel Dunbaracca7252009-11-30 20:42:49 +00001056 << '\n' << "Arguments: \n";
Ted Kremenek379afec2009-10-22 03:24:01 +00001057 for (std::vector<const char*>::iterator I = argv.begin(), E = argv.end();
Ted Kremenek779e5f42009-10-26 22:08:39 +00001058 I!=E; ++I) {
1059 if (*I)
1060 llvm::errs() << ' ' << *I << '\n';
1061 }
1062 llvm::errs() << '\n';
Ted Kremenek379afec2009-10-22 03:24:01 +00001063 }
Benjamin Kramer0829a832009-10-18 11:19:36 +00001064
Douglas Gregor4db64a42010-01-23 00:14:00 +00001065 ASTUnit *ATU = ASTUnit::LoadFromPCHFile(astTmpFile, CXXIdx->getDiags(),
1066 CXXIdx->getOnlyLocalDecls(),
1067 /* UseBumpAllocator = */ true,
1068 RemappedFiles.data(),
1069 RemappedFiles.size());
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001070 if (ATU)
1071 ATU->unlinkTemporaryFile();
Douglas Gregor4db64a42010-01-23 00:14:00 +00001072
1073 for (unsigned i = 0, e = TemporaryFiles.size(); i != e; ++i)
1074 TemporaryFiles[i].eraseFromDisk();
1075
Steve Naroffe19944c2009-10-15 22:23:48 +00001076 return ATU;
Steve Naroff5b7d8e22009-10-15 20:04:39 +00001077}
1078
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001079void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00001080 assert(CTUnit && "Passed null CXTranslationUnit");
1081 delete static_cast<ASTUnit *>(CTUnit);
1082}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001083
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001084CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Steve Naroffaf08ddc2009-09-03 15:49:00 +00001085 assert(CTUnit && "Passed null CXTranslationUnit");
Steve Naroff77accc12009-09-03 18:19:54 +00001086 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit);
Ted Kremenek4b333d22010-01-12 00:36:38 +00001087 return CIndexer::createCXString(CXXUnit->getOriginalSourceFileName().c_str(),
1088 true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +00001089}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +00001090
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001091CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001092 CXCursor Result = { CXCursor_TranslationUnit, { 0, 0, TU } };
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001093 return Result;
1094}
1095
Ted Kremenekfb480492010-01-13 21:46:36 +00001096} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +00001097
Ted Kremenekfb480492010-01-13 21:46:36 +00001098//===----------------------------------------------------------------------===//
Douglas Gregor1db19de2010-01-19 21:36:55 +00001099// CXSourceLocation and CXSourceRange Operations.
1100//===----------------------------------------------------------------------===//
1101
Douglas Gregorb9790342010-01-22 21:44:22 +00001102extern "C" {
1103CXSourceLocation clang_getNullLocation() {
1104 CXSourceLocation Result = { 0, 0 };
1105 return Result;
1106}
1107
1108unsigned clang_equalLocations(CXSourceLocation loc1, CXSourceLocation loc2) {
1109 return loc1.ptr_data == loc2.ptr_data && loc1.int_data == loc2.int_data;
1110}
1111
1112CXSourceLocation clang_getLocation(CXTranslationUnit tu,
1113 CXFile file,
1114 unsigned line,
1115 unsigned column) {
1116 if (!tu)
1117 return clang_getNullLocation();
1118
1119 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
1120 SourceLocation SLoc
1121 = CXXUnit->getSourceManager().getLocation(
1122 static_cast<const FileEntry *>(file),
1123 line, column);
1124
1125 return translateSourceLocation(CXXUnit->getASTContext(), SLoc, false);
1126}
1127
1128CXSourceRange clang_getRange(CXSourceLocation begin, CXSourceLocation end) {
1129 if (begin.ptr_data != end.ptr_data) {
1130 CXSourceRange Result = { 0, 0, 0 };
1131 return Result;
1132 }
1133
1134 CXSourceRange Result = { begin.ptr_data, begin.int_data, end.int_data };
1135 return Result;
1136}
1137
Douglas Gregor1db19de2010-01-19 21:36:55 +00001138void clang_getInstantiationLocation(CXSourceLocation location,
1139 CXFile *file,
1140 unsigned *line,
1141 unsigned *column) {
1142 CXSourceLocationPtr Ptr
1143 = CXSourceLocationPtr::getFromOpaqueValue(location.ptr_data);
1144 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
1145
1146 if (!Ptr.getPointer() || Loc.isInvalid()) {
1147 if (file)
1148 *file = 0;
1149 if (line)
1150 *line = 0;
1151 if (column)
1152 *column = 0;
1153 return;
1154 }
1155
1156 // FIXME: This is largely copy-paste from
1157 ///TextDiagnosticPrinter::HighlightRange. When it is clear that this is
1158 // what we want the two routines should be refactored.
1159 ASTContext &Context = *Ptr.getPointer();
1160 SourceManager &SM = Context.getSourceManager();
1161 SourceLocation InstLoc = SM.getInstantiationLoc(Loc);
1162
1163 if (Ptr.getInt()) {
1164 // We want the last character in this location, so we will adjust
1165 // the instantiation location accordingly.
1166
1167 // If the location is from a macro instantiation, get the end of
1168 // the instantiation range.
1169 if (Loc.isMacroID())
1170 InstLoc = SM.getInstantiationRange(Loc).second;
1171
1172 // Measure the length token we're pointing at, so we can adjust
1173 // the physical location in the file to point at the last
1174 // character.
1175 // FIXME: This won't cope with trigraphs or escaped newlines
1176 // well. For that, we actually need a preprocessor, which isn't
1177 // currently available here. Eventually, we'll switch the pointer
1178 // data of CXSourceLocation/CXSourceRange to a translation unit
1179 // (CXXUnit), so that the preprocessor will be available here. At
1180 // that point, we can use Preprocessor::getLocForEndOfToken().
1181 unsigned Length = Lexer::MeasureTokenLength(InstLoc, SM,
1182 Context.getLangOptions());
1183 if (Length > 0)
1184 InstLoc = InstLoc.getFileLocWithOffset(Length - 1);
1185 }
1186
1187 if (file)
1188 *file = (void *)SM.getFileEntryForID(SM.getFileID(InstLoc));
1189 if (line)
1190 *line = SM.getInstantiationLineNumber(InstLoc);
1191 if (column)
1192 *column = SM.getInstantiationColumnNumber(InstLoc);
1193}
1194
1195CXSourceLocation clang_getRangeStart(CXSourceRange range) {
1196 CXSourceLocation Result = { range.ptr_data, range.begin_int_data };
1197 return Result;
1198}
1199
1200CXSourceLocation clang_getRangeEnd(CXSourceRange range) {
1201 llvm::PointerIntPair<ASTContext *, 1, bool> Ptr;
1202 Ptr.setPointer(static_cast<ASTContext *>(range.ptr_data));
1203 Ptr.setInt(true);
1204 CXSourceLocation Result = { Ptr.getOpaqueValue(), range.end_int_data };
1205 return Result;
1206}
1207
Douglas Gregorb9790342010-01-22 21:44:22 +00001208} // end: extern "C"
1209
Douglas Gregor1db19de2010-01-19 21:36:55 +00001210//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00001211// CXFile Operations.
1212//===----------------------------------------------------------------------===//
1213
1214extern "C" {
Steve Naroff88145032009-10-27 14:35:18 +00001215const char *clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00001216 if (!SFile)
1217 return 0;
1218
Steve Naroff88145032009-10-27 14:35:18 +00001219 assert(SFile && "Passed null CXFile");
1220 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
1221 return FEnt->getName();
1222}
1223
1224time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00001225 if (!SFile)
1226 return 0;
1227
Steve Naroff88145032009-10-27 14:35:18 +00001228 assert(SFile && "Passed null CXFile");
1229 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
1230 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +00001231}
Douglas Gregorb9790342010-01-22 21:44:22 +00001232
1233CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
1234 if (!tu)
1235 return 0;
1236
1237 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
1238
1239 FileManager &FMgr = CXXUnit->getFileManager();
1240 const FileEntry *File = FMgr.getFile(file_name, file_name+strlen(file_name));
1241 return const_cast<FileEntry *>(File);
1242}
1243
Ted Kremenekfb480492010-01-13 21:46:36 +00001244} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +00001245
Ted Kremenekfb480492010-01-13 21:46:36 +00001246//===----------------------------------------------------------------------===//
1247// CXCursor Operations.
1248//===----------------------------------------------------------------------===//
1249
Ted Kremenekfb480492010-01-13 21:46:36 +00001250static Decl *getDeclFromExpr(Stmt *E) {
1251 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
1252 return RefExpr->getDecl();
1253 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
1254 return ME->getMemberDecl();
1255 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
1256 return RE->getDecl();
1257
1258 if (CallExpr *CE = dyn_cast<CallExpr>(E))
1259 return getDeclFromExpr(CE->getCallee());
1260 if (CastExpr *CE = dyn_cast<CastExpr>(E))
1261 return getDeclFromExpr(CE->getSubExpr());
1262 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
1263 return OME->getMethodDecl();
1264
1265 return 0;
1266}
1267
1268extern "C" {
Douglas Gregorb1373d02010-01-20 20:59:29 +00001269
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001270unsigned clang_visitChildren(CXCursor parent,
Douglas Gregorb1373d02010-01-20 20:59:29 +00001271 CXCursorVisitor visitor,
1272 CXClientData client_data) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001273 ASTUnit *CXXUnit = getCursorASTUnit(parent);
Douglas Gregorb1373d02010-01-20 20:59:29 +00001274
1275 unsigned PCHLevel = Decl::MaxPCHLevel;
1276
1277 // Set the PCHLevel to filter out unwanted decls if requested.
1278 if (CXXUnit->getOnlyLocalDecls()) {
1279 PCHLevel = 0;
1280
1281 // If the main input was an AST, bump the level.
1282 if (CXXUnit->isMainFileAST())
1283 ++PCHLevel;
1284 }
1285
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001286 CursorVisitor CursorVis(CXXUnit, visitor, client_data, PCHLevel);
Douglas Gregorb1373d02010-01-20 20:59:29 +00001287 return CursorVis.VisitChildren(parent);
1288}
1289
Douglas Gregor78205d42010-01-20 21:45:58 +00001290static CXString getDeclSpelling(Decl *D) {
1291 NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
1292 if (!ND)
1293 return CIndexer::createCXString("");
1294
1295 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
1296 return CIndexer::createCXString(OMD->getSelector().getAsString().c_str(),
1297 true);
1298
1299 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
1300 // No, this isn't the same as the code below. getIdentifier() is non-virtual
1301 // and returns different names. NamedDecl returns the class name and
1302 // ObjCCategoryImplDecl returns the category name.
1303 return CIndexer::createCXString(CIMP->getIdentifier()->getNameStart());
1304
1305 if (ND->getIdentifier())
1306 return CIndexer::createCXString(ND->getIdentifier()->getNameStart());
1307
1308 return CIndexer::createCXString("");
1309}
1310
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001311CXString clang_getCursorSpelling(CXCursor C) {
Daniel Dunbarc81d7182010-01-18 17:52:42 +00001312 assert(getCursorDecl(C) && "CXCursor has null decl");
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001313 if (clang_isTranslationUnit(C.kind))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001314 return clang_getTranslationUnitSpelling(C.data[2]);
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001315
Steve Narofff334b4e2009-09-02 18:26:48 +00001316 if (clang_isReference(C.kind)) {
1317 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00001318 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +00001319 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
1320 return CIndexer::createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00001321 }
1322 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +00001323 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
1324 return CIndexer::createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00001325 }
1326 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +00001327 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +00001328 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenek4b333d22010-01-12 00:36:38 +00001329 return CIndexer::createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00001330 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001331 case CXCursor_TypeRef: {
1332 TypeDecl *Type = getCursorTypeRef(C).first;
1333 assert(Type && "Missing type decl");
1334
1335 return CIndexer::createCXString(
1336 getCursorContext(C).getTypeDeclType(Type).getAsString().c_str(),
1337 true);
1338 }
1339
Daniel Dunbaracca7252009-11-30 20:42:49 +00001340 default:
Ted Kremenek4b333d22010-01-12 00:36:38 +00001341 return CIndexer::createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +00001342 }
1343 }
Douglas Gregor97b98722010-01-19 23:20:36 +00001344
1345 if (clang_isExpression(C.kind)) {
1346 Decl *D = getDeclFromExpr(getCursorExpr(C));
1347 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +00001348 return getDeclSpelling(D);
Douglas Gregor97b98722010-01-19 23:20:36 +00001349 return CIndexer::createCXString("");
1350 }
1351
Douglas Gregor78205d42010-01-20 21:45:58 +00001352 return getDeclSpelling(getCursorDecl(C));
Steve Narofff334b4e2009-09-02 18:26:48 +00001353}
1354
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001355const char *clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00001356 switch (Kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00001357 case CXCursor_FunctionDecl: return "FunctionDecl";
1358 case CXCursor_TypedefDecl: return "TypedefDecl";
1359 case CXCursor_EnumDecl: return "EnumDecl";
1360 case CXCursor_EnumConstantDecl: return "EnumConstantDecl";
1361 case CXCursor_StructDecl: return "StructDecl";
1362 case CXCursor_UnionDecl: return "UnionDecl";
1363 case CXCursor_ClassDecl: return "ClassDecl";
1364 case CXCursor_FieldDecl: return "FieldDecl";
1365 case CXCursor_VarDecl: return "VarDecl";
1366 case CXCursor_ParmDecl: return "ParmDecl";
1367 case CXCursor_ObjCInterfaceDecl: return "ObjCInterfaceDecl";
1368 case CXCursor_ObjCCategoryDecl: return "ObjCCategoryDecl";
1369 case CXCursor_ObjCProtocolDecl: return "ObjCProtocolDecl";
1370 case CXCursor_ObjCPropertyDecl: return "ObjCPropertyDecl";
1371 case CXCursor_ObjCIvarDecl: return "ObjCIvarDecl";
1372 case CXCursor_ObjCInstanceMethodDecl: return "ObjCInstanceMethodDecl";
1373 case CXCursor_ObjCClassMethodDecl: return "ObjCClassMethodDecl";
Douglas Gregorb6998662010-01-19 19:34:47 +00001374 case CXCursor_ObjCImplementationDecl: return "ObjCImplementationDecl";
1375 case CXCursor_ObjCCategoryImplDecl: return "ObjCCategoryImplDecl";
Douglas Gregor30122132010-01-19 22:07:56 +00001376 case CXCursor_UnexposedDecl: return "UnexposedDecl";
Daniel Dunbaracca7252009-11-30 20:42:49 +00001377 case CXCursor_ObjCSuperClassRef: return "ObjCSuperClassRef";
1378 case CXCursor_ObjCProtocolRef: return "ObjCProtocolRef";
1379 case CXCursor_ObjCClassRef: return "ObjCClassRef";
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001380 case CXCursor_TypeRef: return "TypeRef";
Douglas Gregor97b98722010-01-19 23:20:36 +00001381 case CXCursor_UnexposedExpr: return "UnexposedExpr";
1382 case CXCursor_DeclRefExpr: return "DeclRefExpr";
1383 case CXCursor_MemberRefExpr: return "MemberRefExpr";
1384 case CXCursor_CallExpr: return "CallExpr";
1385 case CXCursor_ObjCMessageExpr: return "ObjCMessageExpr";
1386 case CXCursor_UnexposedStmt: return "UnexposedStmt";
Daniel Dunbaracca7252009-11-30 20:42:49 +00001387 case CXCursor_InvalidFile: return "InvalidFile";
1388 case CXCursor_NoDeclFound: return "NoDeclFound";
1389 case CXCursor_NotImplemented: return "NotImplemented";
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001390 case CXCursor_TranslationUnit: return "TranslationUnit";
Steve Naroff89922f82009-08-31 00:59:03 +00001391 }
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00001392
1393 llvm_unreachable("Unhandled CXCursorKind");
1394 return NULL;
Steve Naroff600866c2009-08-27 19:51:58 +00001395}
Steve Naroff89922f82009-08-31 00:59:03 +00001396
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001397enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
1398 CXCursor parent,
1399 CXClientData client_data) {
1400 CXCursor *BestCursor = static_cast<CXCursor *>(client_data);
1401 *BestCursor = cursor;
1402 return CXChildVisit_Recurse;
1403}
1404
Douglas Gregorb9790342010-01-22 21:44:22 +00001405CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
1406 if (!TU)
Ted Kremenekf4629892010-01-14 01:51:23 +00001407 return clang_getNullCursor();
Ted Kremenekf4629892010-01-14 01:51:23 +00001408
Douglas Gregorb9790342010-01-22 21:44:22 +00001409 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
1410
1411 SourceLocation SLoc = translateSourceLocation(Loc);
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001412 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
1413 if (SLoc.isValid()) {
1414 SourceRange RegionOfInterest(SLoc,
1415 CXXUnit->getPreprocessor().getLocForEndOfToken(SLoc, 1));
1416
1417 // FIXME: Would be great to have a "hint" cursor, then walk from that
1418 // hint cursor upward until we find a cursor whose source range encloses
1419 // the region of interest, rather than starting from the translation unit.
1420 CXCursor Parent = clang_getTranslationUnitCursor(CXXUnit);
1421 CursorVisitor CursorVis(CXXUnit, GetCursorVisitor, &Result,
1422 Decl::MaxPCHLevel, RegionOfInterest);
1423 CursorVis.VisitChildren(Parent);
Steve Naroff77128dd2009-09-15 20:25:34 +00001424 }
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001425 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00001426}
1427
Ted Kremenek73885552009-11-17 19:28:59 +00001428CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00001429 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00001430}
1431
1432unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00001433 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00001434}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001435
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001436unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00001437 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
1438}
1439
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001440unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +00001441 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
1442}
Steve Naroff2d4d6292009-08-31 14:26:51 +00001443
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001444unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00001445 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
1446}
1447
Douglas Gregor97b98722010-01-19 23:20:36 +00001448unsigned clang_isExpression(enum CXCursorKind K) {
1449 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
1450}
1451
1452unsigned clang_isStatement(enum CXCursorKind K) {
1453 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
1454}
1455
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001456unsigned clang_isTranslationUnit(enum CXCursorKind K) {
1457 return K == CXCursor_TranslationUnit;
1458}
1459
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001460CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00001461 return C.kind;
1462}
1463
Douglas Gregor97b98722010-01-19 23:20:36 +00001464static SourceLocation getLocationFromExpr(Expr *E) {
1465 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
1466 return /*FIXME:*/Msg->getLeftLoc();
1467 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
1468 return DRE->getLocation();
1469 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
1470 return Member->getMemberLoc();
1471 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
1472 return Ivar->getLocation();
1473 return E->getLocStart();
1474}
1475
Douglas Gregor98258af2010-01-18 22:46:11 +00001476CXSourceLocation clang_getCursorLocation(CXCursor C) {
1477 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00001478 switch (C.kind) {
1479 case CXCursor_ObjCSuperClassRef: {
1480 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1481 = getCursorObjCSuperClassRef(C);
Douglas Gregor1db19de2010-01-19 21:36:55 +00001482 return translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001483 }
1484
1485 case CXCursor_ObjCProtocolRef: {
1486 std::pair<ObjCProtocolDecl *, SourceLocation> P
1487 = getCursorObjCProtocolRef(C);
Douglas Gregor1db19de2010-01-19 21:36:55 +00001488 return translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001489 }
1490
1491 case CXCursor_ObjCClassRef: {
1492 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1493 = getCursorObjCClassRef(C);
Douglas Gregor1db19de2010-01-19 21:36:55 +00001494 return translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001495 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001496
1497 case CXCursor_TypeRef: {
1498 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
1499 return translateSourceLocation(P.first->getASTContext(), P.second);
1500 }
Douglas Gregorf46034a2010-01-18 23:41:10 +00001501
Douglas Gregorf46034a2010-01-18 23:41:10 +00001502 default:
1503 // FIXME: Need a way to enumerate all non-reference cases.
1504 llvm_unreachable("Missed a reference kind");
1505 }
Douglas Gregor98258af2010-01-18 22:46:11 +00001506 }
Douglas Gregor97b98722010-01-19 23:20:36 +00001507
1508 if (clang_isExpression(C.kind))
1509 return translateSourceLocation(getCursorContext(C),
1510 getLocationFromExpr(getCursorExpr(C)));
1511
Douglas Gregor98258af2010-01-18 22:46:11 +00001512 if (!getCursorDecl(C)) {
Douglas Gregor1db19de2010-01-19 21:36:55 +00001513 CXSourceLocation empty = { 0, 0 };
Douglas Gregor98258af2010-01-18 22:46:11 +00001514 return empty;
1515 }
1516
Douglas Gregorf46034a2010-01-18 23:41:10 +00001517 Decl *D = getCursorDecl(C);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001518 SourceLocation Loc = D->getLocation();
1519 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
1520 Loc = Class->getClassLoc();
Douglas Gregor1db19de2010-01-19 21:36:55 +00001521 return translateSourceLocation(D->getASTContext(), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00001522}
Douglas Gregora7bde202010-01-19 00:34:46 +00001523
1524CXSourceRange clang_getCursorExtent(CXCursor C) {
1525 if (clang_isReference(C.kind)) {
1526 switch (C.kind) {
1527 case CXCursor_ObjCSuperClassRef: {
1528 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1529 = getCursorObjCSuperClassRef(C);
1530 return translateSourceRange(P.first->getASTContext(), P.second);
1531 }
1532
1533 case CXCursor_ObjCProtocolRef: {
1534 std::pair<ObjCProtocolDecl *, SourceLocation> P
1535 = getCursorObjCProtocolRef(C);
1536 return translateSourceRange(P.first->getASTContext(), P.second);
1537 }
1538
1539 case CXCursor_ObjCClassRef: {
1540 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1541 = getCursorObjCClassRef(C);
1542
1543 return translateSourceRange(P.first->getASTContext(), P.second);
1544 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001545
1546 case CXCursor_TypeRef: {
1547 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
1548 return translateSourceRange(P.first->getASTContext(), P.second);
1549 }
Douglas Gregora7bde202010-01-19 00:34:46 +00001550
Douglas Gregora7bde202010-01-19 00:34:46 +00001551 default:
1552 // FIXME: Need a way to enumerate all non-reference cases.
1553 llvm_unreachable("Missed a reference kind");
1554 }
1555 }
Douglas Gregor97b98722010-01-19 23:20:36 +00001556
1557 if (clang_isExpression(C.kind))
1558 return translateSourceRange(getCursorContext(C),
1559 getCursorExpr(C)->getSourceRange());
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001560
1561 if (clang_isStatement(C.kind))
1562 return translateSourceRange(getCursorContext(C),
1563 getCursorStmt(C)->getSourceRange());
Douglas Gregora7bde202010-01-19 00:34:46 +00001564
1565 if (!getCursorDecl(C)) {
Douglas Gregor1db19de2010-01-19 21:36:55 +00001566 CXSourceRange empty = { 0, 0, 0 };
Douglas Gregora7bde202010-01-19 00:34:46 +00001567 return empty;
1568 }
1569
1570 Decl *D = getCursorDecl(C);
1571 return translateSourceRange(D->getASTContext(), D->getSourceRange());
1572}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001573
1574CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001575 if (clang_isInvalid(C.kind))
1576 return clang_getNullCursor();
1577
1578 ASTUnit *CXXUnit = getCursorASTUnit(C);
Douglas Gregorb6998662010-01-19 19:34:47 +00001579 if (clang_isDeclaration(C.kind))
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001580 return C;
Douglas Gregor98258af2010-01-18 22:46:11 +00001581
Douglas Gregor97b98722010-01-19 23:20:36 +00001582 if (clang_isExpression(C.kind)) {
1583 Decl *D = getDeclFromExpr(getCursorExpr(C));
1584 if (D)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001585 return MakeCXCursor(D, CXXUnit);
Douglas Gregor97b98722010-01-19 23:20:36 +00001586 return clang_getNullCursor();
1587 }
1588
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001589 if (!clang_isReference(C.kind))
1590 return clang_getNullCursor();
1591
1592 switch (C.kind) {
1593 case CXCursor_ObjCSuperClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001594 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, CXXUnit);
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001595
1596 case CXCursor_ObjCProtocolRef: {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001597 return MakeCXCursor(getCursorObjCProtocolRef(C).first, CXXUnit);
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001598
1599 case CXCursor_ObjCClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001600 return MakeCXCursor(getCursorObjCClassRef(C).first, CXXUnit);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001601
1602 case CXCursor_TypeRef:
1603 return MakeCXCursor(getCursorTypeRef(C).first, CXXUnit);
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001604
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001605 default:
1606 // We would prefer to enumerate all non-reference cursor kinds here.
1607 llvm_unreachable("Unhandled reference cursor kind");
1608 break;
1609 }
1610 }
1611
1612 return clang_getNullCursor();
1613}
1614
Douglas Gregorb6998662010-01-19 19:34:47 +00001615CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001616 if (clang_isInvalid(C.kind))
1617 return clang_getNullCursor();
1618
1619 ASTUnit *CXXUnit = getCursorASTUnit(C);
1620
Douglas Gregorb6998662010-01-19 19:34:47 +00001621 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00001622 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00001623 C = clang_getCursorReferenced(C);
1624 WasReference = true;
1625 }
1626
1627 if (!clang_isDeclaration(C.kind))
1628 return clang_getNullCursor();
1629
1630 Decl *D = getCursorDecl(C);
1631 if (!D)
1632 return clang_getNullCursor();
1633
1634 switch (D->getKind()) {
1635 // Declaration kinds that don't really separate the notions of
1636 // declaration and definition.
1637 case Decl::Namespace:
1638 case Decl::Typedef:
1639 case Decl::TemplateTypeParm:
1640 case Decl::EnumConstant:
1641 case Decl::Field:
1642 case Decl::ObjCIvar:
1643 case Decl::ObjCAtDefsField:
1644 case Decl::ImplicitParam:
1645 case Decl::ParmVar:
1646 case Decl::NonTypeTemplateParm:
1647 case Decl::TemplateTemplateParm:
1648 case Decl::ObjCCategoryImpl:
1649 case Decl::ObjCImplementation:
1650 case Decl::LinkageSpec:
1651 case Decl::ObjCPropertyImpl:
1652 case Decl::FileScopeAsm:
1653 case Decl::StaticAssert:
1654 case Decl::Block:
1655 return C;
1656
1657 // Declaration kinds that don't make any sense here, but are
1658 // nonetheless harmless.
1659 case Decl::TranslationUnit:
1660 case Decl::Template:
1661 case Decl::ObjCContainer:
1662 break;
1663
1664 // Declaration kinds for which the definition is not resolvable.
1665 case Decl::UnresolvedUsingTypename:
1666 case Decl::UnresolvedUsingValue:
1667 break;
1668
1669 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001670 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
1671 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001672
1673 case Decl::NamespaceAlias:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001674 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001675
1676 case Decl::Enum:
1677 case Decl::Record:
1678 case Decl::CXXRecord:
1679 case Decl::ClassTemplateSpecialization:
1680 case Decl::ClassTemplatePartialSpecialization:
1681 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition(D->getASTContext()))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001682 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001683 return clang_getNullCursor();
1684
1685 case Decl::Function:
1686 case Decl::CXXMethod:
1687 case Decl::CXXConstructor:
1688 case Decl::CXXDestructor:
1689 case Decl::CXXConversion: {
1690 const FunctionDecl *Def = 0;
1691 if (cast<FunctionDecl>(D)->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001692 return MakeCXCursor(const_cast<FunctionDecl *>(Def), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001693 return clang_getNullCursor();
1694 }
1695
1696 case Decl::Var: {
1697 VarDecl *Var = cast<VarDecl>(D);
1698
1699 // Variables with initializers have definitions.
1700 const VarDecl *Def = 0;
1701 if (Var->getDefinition(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001702 return MakeCXCursor(const_cast<VarDecl *>(Def), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001703
1704 // extern and private_extern variables are not definitions.
1705 if (Var->hasExternalStorage())
1706 return clang_getNullCursor();
1707
1708 // In-line static data members do not have definitions.
1709 if (Var->isStaticDataMember() && !Var->isOutOfLine())
1710 return clang_getNullCursor();
1711
1712 // All other variables are themselves definitions.
1713 return C;
1714 }
1715
1716 case Decl::FunctionTemplate: {
1717 const FunctionDecl *Def = 0;
1718 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001719 return MakeCXCursor(Def->getDescribedFunctionTemplate(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001720 return clang_getNullCursor();
1721 }
1722
1723 case Decl::ClassTemplate: {
1724 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
1725 ->getDefinition(D->getASTContext()))
1726 return MakeCXCursor(
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001727 cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
1728 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001729 return clang_getNullCursor();
1730 }
1731
1732 case Decl::Using: {
1733 UsingDecl *Using = cast<UsingDecl>(D);
1734 CXCursor Def = clang_getNullCursor();
1735 for (UsingDecl::shadow_iterator S = Using->shadow_begin(),
1736 SEnd = Using->shadow_end();
1737 S != SEnd; ++S) {
1738 if (Def != clang_getNullCursor()) {
1739 // FIXME: We have no way to return multiple results.
1740 return clang_getNullCursor();
1741 }
1742
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001743 Def = clang_getCursorDefinition(MakeCXCursor((*S)->getTargetDecl(),
1744 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00001745 }
1746
1747 return Def;
1748 }
1749
1750 case Decl::UsingShadow:
1751 return clang_getCursorDefinition(
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001752 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
1753 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00001754
1755 case Decl::ObjCMethod: {
1756 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
1757 if (Method->isThisDeclarationADefinition())
1758 return C;
1759
1760 // Dig out the method definition in the associated
1761 // @implementation, if we have it.
1762 // FIXME: The ASTs should make finding the definition easier.
1763 if (ObjCInterfaceDecl *Class
1764 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
1765 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
1766 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
1767 Method->isInstanceMethod()))
1768 if (Def->isThisDeclarationADefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001769 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001770
1771 return clang_getNullCursor();
1772 }
1773
1774 case Decl::ObjCCategory:
1775 if (ObjCCategoryImplDecl *Impl
1776 = cast<ObjCCategoryDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001777 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001778 return clang_getNullCursor();
1779
1780 case Decl::ObjCProtocol:
1781 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
1782 return C;
1783 return clang_getNullCursor();
1784
1785 case Decl::ObjCInterface:
1786 // There are two notions of a "definition" for an Objective-C
1787 // class: the interface and its implementation. When we resolved a
1788 // reference to an Objective-C class, produce the @interface as
1789 // the definition; when we were provided with the interface,
1790 // produce the @implementation as the definition.
1791 if (WasReference) {
1792 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
1793 return C;
1794 } else if (ObjCImplementationDecl *Impl
1795 = cast<ObjCInterfaceDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001796 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001797 return clang_getNullCursor();
1798
1799 case Decl::ObjCProperty:
1800 // FIXME: We don't really know where to find the
1801 // ObjCPropertyImplDecls that implement this property.
1802 return clang_getNullCursor();
1803
1804 case Decl::ObjCCompatibleAlias:
1805 if (ObjCInterfaceDecl *Class
1806 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
1807 if (!Class->isForwardDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001808 return MakeCXCursor(Class, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001809
1810 return clang_getNullCursor();
1811
1812 case Decl::ObjCForwardProtocol: {
1813 ObjCForwardProtocolDecl *Forward = cast<ObjCForwardProtocolDecl>(D);
1814 if (Forward->protocol_size() == 1)
1815 return clang_getCursorDefinition(
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001816 MakeCXCursor(*Forward->protocol_begin(),
1817 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00001818
1819 // FIXME: Cannot return multiple definitions.
1820 return clang_getNullCursor();
1821 }
1822
1823 case Decl::ObjCClass: {
1824 ObjCClassDecl *Class = cast<ObjCClassDecl>(D);
1825 if (Class->size() == 1) {
1826 ObjCInterfaceDecl *IFace = Class->begin()->getInterface();
1827 if (!IFace->isForwardDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001828 return MakeCXCursor(IFace, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001829 return clang_getNullCursor();
1830 }
1831
1832 // FIXME: Cannot return multiple definitions.
1833 return clang_getNullCursor();
1834 }
1835
1836 case Decl::Friend:
1837 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001838 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00001839 return clang_getNullCursor();
1840
1841 case Decl::FriendTemplate:
1842 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001843 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00001844 return clang_getNullCursor();
1845 }
1846
1847 return clang_getNullCursor();
1848}
1849
1850unsigned clang_isCursorDefinition(CXCursor C) {
1851 if (!clang_isDeclaration(C.kind))
1852 return 0;
1853
1854 return clang_getCursorDefinition(C) == C;
1855}
1856
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001857void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00001858 const char **startBuf,
1859 const char **endBuf,
1860 unsigned *startLine,
1861 unsigned *startColumn,
1862 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001863 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00001864 assert(getCursorDecl(C) && "CXCursor has null decl");
1865 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00001866 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
1867 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekfb480492010-01-13 21:46:36 +00001868
Steve Naroff4ade6d62009-09-23 17:52:52 +00001869 SourceManager &SM = FD->getASTContext().getSourceManager();
1870 *startBuf = SM.getCharacterData(Body->getLBracLoc());
1871 *endBuf = SM.getCharacterData(Body->getRBracLoc());
1872 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
1873 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
1874 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
1875 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
1876}
Ted Kremenekfb480492010-01-13 21:46:36 +00001877
1878} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00001879
Ted Kremenekfb480492010-01-13 21:46:36 +00001880//===----------------------------------------------------------------------===//
1881// CXString Operations.
1882//===----------------------------------------------------------------------===//
1883
1884extern "C" {
1885const char *clang_getCString(CXString string) {
1886 return string.Spelling;
1887}
1888
1889void clang_disposeString(CXString string) {
1890 if (string.MustFreeString && string.Spelling)
1891 free((void*)string.Spelling);
1892}
Ted Kremenek04bb7162010-01-22 22:44:15 +00001893
Ted Kremenekfb480492010-01-13 21:46:36 +00001894} // end: extern "C"
Ted Kremenek04bb7162010-01-22 22:44:15 +00001895
1896//===----------------------------------------------------------------------===//
1897// Misc. utility functions.
1898//===----------------------------------------------------------------------===//
1899
1900extern "C" {
1901
1902const char *clang_getClangVersion() {
Ted Kremeneka18f1b82010-01-23 02:11:34 +00001903 return getClangFullVersion();
Ted Kremenek04bb7162010-01-22 22:44:15 +00001904}
1905
1906} // end: extern "C"
1907