blob: 8ce3db63d58f00726d493c5a347d4ee06a6ee48f [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
Steve Naroff50398192009-08-28 15:28:48 +000018#include "clang/AST/DeclVisitor.h"
Steve Narofffb570422009-09-22 19:25:29 +000019#include "clang/AST/StmtVisitor.h"
Douglas Gregor7d0d40e2010-01-21 16:28:34 +000020#include "clang/AST/TypeLocVisitor.h"
Ted Kremenekd8210652010-01-06 23:43:31 +000021#include "clang/Lex/Lexer.h"
Douglas Gregor33e9abd2010-01-22 19:49:59 +000022#include "clang/Lex/Preprocessor.h"
Douglas Gregor02465752009-10-16 21:24:31 +000023#include "llvm/Support/MemoryBuffer.h"
Benjamin Kramer0829a832009-10-18 11:19:36 +000024#include "llvm/System/Program.h"
Ted Kremenekfc062212009-10-19 21:44:57 +000025
Ted Kremenekdb3d0da2010-01-05 20:55:39 +000026// Needed to define L_TMPNAM on some systems.
27#include <cstdio>
28
Steve Naroff50398192009-08-28 15:28:48 +000029using namespace clang;
Ted Kremenek16c440a2010-01-15 20:35:54 +000030using namespace clang::cxcursor;
Steve Naroff50398192009-08-28 15:28:48 +000031using namespace idx;
32
Ted Kremenek8a8da7d2010-01-06 03:42:32 +000033//===----------------------------------------------------------------------===//
34// Crash Reporting.
35//===----------------------------------------------------------------------===//
36
37#ifdef __APPLE__
Ted Kremenek29b72842010-01-07 22:49:05 +000038#ifndef NDEBUG
39#define USE_CRASHTRACER
Ted Kremenek8a8da7d2010-01-06 03:42:32 +000040#include "clang/Analysis/Support/SaveAndRestore.h"
41// Integrate with crash reporter.
42extern "C" const char *__crashreporter_info__;
Ted Kremenek29b72842010-01-07 22:49:05 +000043#define NUM_CRASH_STRINGS 16
44static unsigned crashtracer_counter = 0;
Ted Kremenek254ba7c2010-01-07 23:13:53 +000045static unsigned crashtracer_counter_id[NUM_CRASH_STRINGS] = { 0 };
Ted Kremenek29b72842010-01-07 22:49:05 +000046static const char *crashtracer_strings[NUM_CRASH_STRINGS] = { 0 };
47static const char *agg_crashtracer_strings[NUM_CRASH_STRINGS] = { 0 };
48
49static unsigned SetCrashTracerInfo(const char *str,
50 llvm::SmallString<1024> &AggStr) {
51
Ted Kremenek254ba7c2010-01-07 23:13:53 +000052 unsigned slot = 0;
Ted Kremenek29b72842010-01-07 22:49:05 +000053 while (crashtracer_strings[slot]) {
54 if (++slot == NUM_CRASH_STRINGS)
55 slot = 0;
56 }
57 crashtracer_strings[slot] = str;
Ted Kremenek254ba7c2010-01-07 23:13:53 +000058 crashtracer_counter_id[slot] = ++crashtracer_counter;
Ted Kremenek29b72842010-01-07 22:49:05 +000059
60 // We need to create an aggregate string because multiple threads
61 // may be in this method at one time. The crash reporter string
62 // will attempt to overapproximate the set of in-flight invocations
63 // of this function. Race conditions can still cause this goal
64 // to not be achieved.
65 {
66 llvm::raw_svector_ostream Out(AggStr);
67 for (unsigned i = 0; i < NUM_CRASH_STRINGS; ++i)
68 if (crashtracer_strings[i]) Out << crashtracer_strings[i] << '\n';
69 }
70 __crashreporter_info__ = agg_crashtracer_strings[slot] = AggStr.c_str();
71 return slot;
72}
73
74static void ResetCrashTracerInfo(unsigned slot) {
Ted Kremenek254ba7c2010-01-07 23:13:53 +000075 unsigned max_slot = 0;
76 unsigned max_value = 0;
77
78 crashtracer_strings[slot] = agg_crashtracer_strings[slot] = 0;
79
80 for (unsigned i = 0 ; i < NUM_CRASH_STRINGS; ++i)
81 if (agg_crashtracer_strings[i] &&
82 crashtracer_counter_id[i] > max_value) {
83 max_slot = i;
84 max_value = crashtracer_counter_id[i];
Ted Kremenek29b72842010-01-07 22:49:05 +000085 }
Ted Kremenek254ba7c2010-01-07 23:13:53 +000086
87 __crashreporter_info__ = agg_crashtracer_strings[max_slot];
Ted Kremenek29b72842010-01-07 22:49:05 +000088}
89
90namespace {
91class ArgsCrashTracerInfo {
92 llvm::SmallString<1024> CrashString;
93 llvm::SmallString<1024> AggregateString;
94 unsigned crashtracerSlot;
95public:
96 ArgsCrashTracerInfo(llvm::SmallVectorImpl<const char*> &Args)
97 : crashtracerSlot(0)
98 {
99 {
100 llvm::raw_svector_ostream Out(CrashString);
101 Out << "ClangCIndex [createTranslationUnitFromSourceFile]: clang";
102 for (llvm::SmallVectorImpl<const char*>::iterator I=Args.begin(),
103 E=Args.end(); I!=E; ++I)
104 Out << ' ' << *I;
105 }
106 crashtracerSlot = SetCrashTracerInfo(CrashString.c_str(),
107 AggregateString);
108 }
109
110 ~ArgsCrashTracerInfo() {
111 ResetCrashTracerInfo(crashtracerSlot);
112 }
113};
114}
115#endif
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000116#endif
117
Douglas Gregor1db19de2010-01-19 21:36:55 +0000118typedef llvm::PointerIntPair<ASTContext *, 1, bool> CXSourceLocationPtr;
119
Douglas Gregor98258af2010-01-18 22:46:11 +0000120/// \brief Translate a Clang source location into a CIndex source location.
Douglas Gregor1db19de2010-01-19 21:36:55 +0000121static CXSourceLocation translateSourceLocation(ASTContext &Context,
122 SourceLocation Loc,
123 bool AtEnd = false) {
124 CXSourceLocationPtr Ptr(&Context, AtEnd);
125 CXSourceLocation Result = { Ptr.getOpaqueValue(), Loc.getRawEncoding() };
126 return Result;
Douglas Gregor98258af2010-01-18 22:46:11 +0000127}
128
Douglas Gregora7bde202010-01-19 00:34:46 +0000129/// \brief Translate a Clang source range into a CIndex source range.
Douglas Gregor1db19de2010-01-19 21:36:55 +0000130static CXSourceRange translateSourceRange(ASTContext &Context, SourceRange R) {
131 CXSourceRange Result = { &Context,
132 R.getBegin().getRawEncoding(),
133 R.getEnd().getRawEncoding() };
134 return Result;
Douglas Gregora7bde202010-01-19 00:34:46 +0000135}
136
Douglas Gregorb9790342010-01-22 21:44:22 +0000137static SourceLocation translateSourceLocation(CXSourceLocation L) {
138 return SourceLocation::getFromRawEncoding(L.int_data);
139}
140
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000141static SourceRange translateSourceRange(CXSourceRange R) {
142 return SourceRange(SourceLocation::getFromRawEncoding(R.begin_int_data),
143 SourceLocation::getFromRawEncoding(R.end_int_data));
144}
145
146/// \brief The result of comparing two source ranges.
147enum RangeComparisonResult {
148 /// \brief Either the ranges overlap or one of the ranges is invalid.
149 RangeOverlap,
150
151 /// \brief The first range ends before the second range starts.
152 RangeBefore,
153
154 /// \brief The first range starts after the second range ends.
155 RangeAfter
156};
157
158/// \brief Compare two source ranges to determine their relative position in
159/// the translation unit.
160static RangeComparisonResult RangeCompare(SourceManager &SM,
161 SourceRange R1,
162 SourceRange R2) {
163 assert(R1.isValid() && "First range is invalid?");
164 assert(R2.isValid() && "Second range is invalid?");
165 if (SM.isBeforeInTranslationUnit(R1.getEnd(), R2.getBegin()))
166 return RangeBefore;
167 if (SM.isBeforeInTranslationUnit(R2.getEnd(), R1.getBegin()))
168 return RangeAfter;
169 return RangeOverlap;
170}
171
Douglas Gregor1db19de2010-01-19 21:36:55 +0000172
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000173//===----------------------------------------------------------------------===//
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000174// Cursor visitor.
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000175//===----------------------------------------------------------------------===//
176
Steve Naroff89922f82009-08-31 00:59:03 +0000177namespace {
Ted Kremenekedc8aa62010-01-16 00:36:30 +0000178
Douglas Gregorb1373d02010-01-20 20:59:29 +0000179// Cursor visitor.
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000180class CursorVisitor : public DeclVisitor<CursorVisitor, bool>,
Douglas Gregora59e3902010-01-21 23:27:09 +0000181 public TypeLocVisitor<CursorVisitor, bool>,
182 public StmtVisitor<CursorVisitor, bool>
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000183{
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000184 /// \brief The translation unit we are traversing.
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000185 ASTUnit *TU;
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000186
187 /// \brief The parent cursor whose children we are traversing.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000188 CXCursor Parent;
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000189
190 /// \brief The declaration that serves at the parent of any statement or
191 /// expression nodes.
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000192 Decl *StmtParent;
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000193
194 /// \brief The visitor function.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000195 CXCursorVisitor Visitor;
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000196
197 /// \brief The opaque client data, to be passed along to the visitor.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000198 CXClientData ClientData;
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000199
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000200 // MaxPCHLevel - the maximum PCH level of declarations that we will pass on
201 // to the visitor. Declarations with a PCH level greater than this value will
202 // be suppressed.
203 unsigned MaxPCHLevel;
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000204
205 /// \brief When valid, a source range to which the cursor should restrict
206 /// its search.
207 SourceRange RegionOfInterest;
208
Douglas Gregorb1373d02010-01-20 20:59:29 +0000209 using DeclVisitor<CursorVisitor, bool>::Visit;
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000210 using TypeLocVisitor<CursorVisitor, bool>::Visit;
Douglas Gregora59e3902010-01-21 23:27:09 +0000211 using StmtVisitor<CursorVisitor, bool>::Visit;
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000212
213 /// \brief Determine whether this particular source range comes before, comes
214 /// after, or overlaps the region of interest.
215 ///
216 /// \param R a source range retrieved from the abstract syntax tree.
217 RangeComparisonResult CompareRegionOfInterest(SourceRange R);
218
219 /// \brief Determine whether this particular source range comes before, comes
220 /// after, or overlaps the region of interest.
221 ///
222 /// \param CXR a source range retrieved from a cursor.
223 RangeComparisonResult CompareRegionOfInterest(CXSourceRange CXR);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000224
Steve Naroff89922f82009-08-31 00:59:03 +0000225public:
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000226 CursorVisitor(ASTUnit *TU, CXCursorVisitor Visitor, CXClientData ClientData,
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000227 unsigned MaxPCHLevel,
228 SourceRange RegionOfInterest = SourceRange())
229 : TU(TU), Visitor(Visitor), ClientData(ClientData),
230 MaxPCHLevel(MaxPCHLevel), RegionOfInterest(RegionOfInterest)
Douglas Gregorb1373d02010-01-20 20:59:29 +0000231 {
232 Parent.kind = CXCursor_NoDeclFound;
233 Parent.data[0] = 0;
234 Parent.data[1] = 0;
235 Parent.data[2] = 0;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000236 StmtParent = 0;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000237 }
238
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000239 bool Visit(CXCursor Cursor, bool CheckedRegionOfInterest = false);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000240 bool VisitChildren(CXCursor Parent);
241
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000242 // Declaration visitors
Douglas Gregorb1373d02010-01-20 20:59:29 +0000243 bool VisitDeclContext(DeclContext *DC);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000244 bool VisitTranslationUnitDecl(TranslationUnitDecl *D);
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000245 bool VisitTypedefDecl(TypedefDecl *D);
246 bool VisitTagDecl(TagDecl *D);
247 bool VisitEnumConstantDecl(EnumConstantDecl *D);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000248 bool VisitDeclaratorDecl(DeclaratorDecl *DD);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000249 bool VisitFunctionDecl(FunctionDecl *ND);
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000250 bool VisitFieldDecl(FieldDecl *D);
251 bool VisitVarDecl(VarDecl *);
252 bool VisitObjCMethodDecl(ObjCMethodDecl *ND);
Douglas Gregora59e3902010-01-21 23:27:09 +0000253 bool VisitObjCContainerDecl(ObjCContainerDecl *D);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000254 bool VisitObjCCategoryDecl(ObjCCategoryDecl *ND);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000255 bool VisitObjCProtocolDecl(ObjCProtocolDecl *PID);
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000256 bool VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
257 bool VisitObjCImplDecl(ObjCImplDecl *D);
258 bool VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
259 bool VisitObjCImplementationDecl(ObjCImplementationDecl *D);
260 // FIXME: ObjCPropertyDecl requires TypeSourceInfo, getter/setter locations,
261 // etc.
262 // FIXME: ObjCCompatibleAliasDecl requires aliased-class locations.
263 bool VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D);
264 bool VisitObjCClassDecl(ObjCClassDecl *D);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000265
266 // Type visitors
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000267 // FIXME: QualifiedTypeLoc doesn't provide any location information
268 bool VisitBuiltinTypeLoc(BuiltinTypeLoc TL);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000269 bool VisitTypedefTypeLoc(TypedefTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000270 bool VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL);
271 bool VisitTagTypeLoc(TagTypeLoc TL);
272 // FIXME: TemplateTypeParmTypeLoc doesn't provide any location information
273 bool VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL);
274 bool VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL);
275 bool VisitPointerTypeLoc(PointerTypeLoc TL);
276 bool VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL);
277 bool VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL);
278 bool VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL);
279 bool VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL);
280 bool VisitFunctionTypeLoc(FunctionTypeLoc TL);
281 bool VisitArrayTypeLoc(ArrayTypeLoc TL);
Douglas Gregor2332c112010-01-21 20:48:56 +0000282 // FIXME: Implement for TemplateSpecializationTypeLoc
283 // FIXME: Implement visitors here when the unimplemented TypeLocs get
284 // implemented
285 bool VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL);
286 bool VisitTypeOfTypeLoc(TypeOfTypeLoc TL);
Douglas Gregora59e3902010-01-21 23:27:09 +0000287
288 // Statement visitors
289 bool VisitStmt(Stmt *S);
290 bool VisitDeclStmt(DeclStmt *S);
Douglas Gregorf5bab412010-01-22 01:00:11 +0000291 // FIXME: LabelStmt label?
292 bool VisitIfStmt(IfStmt *S);
293 bool VisitSwitchStmt(SwitchStmt *S);
Steve Naroff89922f82009-08-31 00:59:03 +0000294};
Douglas Gregorb1373d02010-01-20 20:59:29 +0000295
Ted Kremenekab188932010-01-05 19:32:54 +0000296} // end anonymous namespace
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000297
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000298RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
299 assert(RegionOfInterest.isValid() && "RangeCompare called with invalid range");
300 if (R.isInvalid())
301 return RangeOverlap;
302
303 // Move the end of the input range to the end of the last token in that
304 // range.
305 R.setEnd(TU->getPreprocessor().getLocForEndOfToken(R.getEnd(), 1));
306 return RangeCompare(TU->getSourceManager(), R, RegionOfInterest);
307}
308
309RangeComparisonResult CursorVisitor::CompareRegionOfInterest(CXSourceRange CXR) {
310 return CompareRegionOfInterest(translateSourceRange(CXR));
311}
312
Douglas Gregorb1373d02010-01-20 20:59:29 +0000313/// \brief Visit the given cursor and, if requested by the visitor,
314/// its children.
315///
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000316/// \param Cursor the cursor to visit.
317///
318/// \param CheckRegionOfInterest if true, then the caller already checked that
319/// this cursor is within the region of interest.
320///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000321/// \returns true if the visitation should be aborted, false if it
322/// should continue.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000323bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
Douglas Gregorb1373d02010-01-20 20:59:29 +0000324 if (clang_isInvalid(Cursor.kind))
325 return false;
326
327 if (clang_isDeclaration(Cursor.kind)) {
328 Decl *D = getCursorDecl(Cursor);
329 assert(D && "Invalid declaration cursor");
330 if (D->getPCHLevel() > MaxPCHLevel)
331 return false;
332
333 if (D->isImplicit())
334 return false;
335 }
336
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000337 // If we have a range of interest, and this cursor doesn't intersect with it,
338 // we're done.
339 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
340 CXSourceRange Range = clang_getCursorExtent(Cursor);
341 if (translateSourceRange(Range).isInvalid() ||
342 CompareRegionOfInterest(Range))
343 return false;
344 }
345
Douglas Gregorb1373d02010-01-20 20:59:29 +0000346 switch (Visitor(Cursor, Parent, ClientData)) {
347 case CXChildVisit_Break:
348 return true;
349
350 case CXChildVisit_Continue:
351 return false;
352
353 case CXChildVisit_Recurse:
354 return VisitChildren(Cursor);
355 }
356
357 llvm_unreachable("Silly GCC, we can't get here");
358}
359
360/// \brief Visit the children of the given cursor.
361///
362/// \returns true if the visitation should be aborted, false if it
363/// should continue.
364bool CursorVisitor::VisitChildren(CXCursor Cursor) {
Douglas Gregora59e3902010-01-21 23:27:09 +0000365 if (clang_isReference(Cursor.kind)) {
366 // By definition, references have no children.
367 return false;
368 }
369
Douglas Gregorb1373d02010-01-20 20:59:29 +0000370 // Set the Parent field to Cursor, then back to its old value once we're
371 // done.
372 class SetParentRAII {
373 CXCursor &Parent;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000374 Decl *&StmtParent;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000375 CXCursor OldParent;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000376
Douglas Gregorb1373d02010-01-20 20:59:29 +0000377 public:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000378 SetParentRAII(CXCursor &Parent, Decl *&StmtParent, CXCursor NewParent)
379 : Parent(Parent), StmtParent(StmtParent), OldParent(Parent)
Douglas Gregorb1373d02010-01-20 20:59:29 +0000380 {
381 Parent = NewParent;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000382 if (clang_isDeclaration(Parent.kind))
383 StmtParent = getCursorDecl(Parent);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000384 }
385
386 ~SetParentRAII() {
387 Parent = OldParent;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000388 if (clang_isDeclaration(Parent.kind))
389 StmtParent = getCursorDecl(Parent);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000390 }
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000391 } SetParent(Parent, StmtParent, Cursor);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000392
393 if (clang_isDeclaration(Cursor.kind)) {
394 Decl *D = getCursorDecl(Cursor);
395 assert(D && "Invalid declaration cursor");
396 return Visit(D);
397 }
398
Douglas Gregora59e3902010-01-21 23:27:09 +0000399 if (clang_isStatement(Cursor.kind))
400 return Visit(getCursorStmt(Cursor));
401 if (clang_isExpression(Cursor.kind))
402 return Visit(getCursorExpr(Cursor));
403
Douglas Gregorb1373d02010-01-20 20:59:29 +0000404 if (clang_isTranslationUnit(Cursor.kind)) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000405 ASTUnit *CXXUnit = getCursorASTUnit(Cursor);
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000406 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
407 RegionOfInterest.isInvalid()) {
Douglas Gregor7b691f332010-01-20 21:13:59 +0000408 const std::vector<Decl*> &TLDs = CXXUnit->getTopLevelDecls();
409 for (std::vector<Decl*>::const_iterator it = TLDs.begin(),
410 ie = TLDs.end(); it != ie; ++it) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000411 if (Visit(MakeCXCursor(*it, CXXUnit), true))
Douglas Gregor7b691f332010-01-20 21:13:59 +0000412 return true;
413 }
414 } else {
415 return VisitDeclContext(
Douglas Gregorb1373d02010-01-20 20:59:29 +0000416 CXXUnit->getASTContext().getTranslationUnitDecl());
Douglas Gregor7b691f332010-01-20 21:13:59 +0000417 }
418
419 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000420 }
Douglas Gregora59e3902010-01-21 23:27:09 +0000421
Douglas Gregorb1373d02010-01-20 20:59:29 +0000422 // Nothing to visit at the moment.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000423 return false;
424}
425
Douglas Gregorb1373d02010-01-20 20:59:29 +0000426bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000427 for (DeclContext::decl_iterator
Douglas Gregorb1373d02010-01-20 20:59:29 +0000428 I = DC->decls_begin(), E = DC->decls_end(); I != E; ++I) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000429 if (RegionOfInterest.isValid()) {
430 SourceRange R = (*I)->getSourceRange();
431 if (R.isInvalid())
432 continue;
433
434 switch (CompareRegionOfInterest(R)) {
435 case RangeBefore:
436 // This declaration comes before the region of interest; skip it.
437 continue;
438
439 case RangeAfter:
440 // This declaration comes after the region of interest; we're done.
441 return false;
442
443 case RangeOverlap:
444 // This declaration overlaps the region of interest; visit it.
445 break;
446 }
447 }
448
449 if (Visit(MakeCXCursor(*I, TU), true))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000450 return true;
451 }
452
453 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000454}
455
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000456bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
457 llvm_unreachable("Translation units are visited directly by Visit()");
458 return false;
459}
460
461bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
462 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
463 return Visit(TSInfo->getTypeLoc());
464
465 return false;
466}
467
468bool CursorVisitor::VisitTagDecl(TagDecl *D) {
469 return VisitDeclContext(D);
470}
471
472bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
473 if (Expr *Init = D->getInitExpr())
474 return Visit(MakeCXCursor(Init, StmtParent, TU));
475 return false;
476}
477
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000478bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
479 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
480 if (Visit(TSInfo->getTypeLoc()))
481 return true;
482
483 return false;
484}
485
Douglas Gregorb1373d02010-01-20 20:59:29 +0000486bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000487 if (VisitDeclaratorDecl(ND))
488 return true;
489
Douglas Gregora59e3902010-01-21 23:27:09 +0000490 if (ND->isThisDeclarationADefinition() &&
491 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
492 return true;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000493
494 return false;
495}
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000496
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000497bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
498 if (VisitDeclaratorDecl(D))
499 return true;
500
501 if (Expr *BitWidth = D->getBitWidth())
502 return Visit(MakeCXCursor(BitWidth, StmtParent, TU));
503
504 return false;
505}
506
507bool CursorVisitor::VisitVarDecl(VarDecl *D) {
508 if (VisitDeclaratorDecl(D))
509 return true;
510
511 if (Expr *Init = D->getInit())
512 return Visit(MakeCXCursor(Init, StmtParent, TU));
513
514 return false;
515}
516
517bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
518 // FIXME: We really need a TypeLoc covering Objective-C method declarations.
519 // At the moment, we don't have information about locations in the return
520 // type.
521 for (ObjCMethodDecl::param_iterator P = ND->param_begin(),
522 PEnd = ND->param_end();
523 P != PEnd; ++P) {
524 if (Visit(MakeCXCursor(*P, TU)))
525 return true;
526 }
527
528 if (ND->isThisDeclarationADefinition() &&
529 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
530 return true;
531
532 return false;
533}
534
Douglas Gregora59e3902010-01-21 23:27:09 +0000535bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
536 return VisitDeclContext(D);
537}
538
Douglas Gregorb1373d02010-01-20 20:59:29 +0000539bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000540 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
541 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000542 return true;
543
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000544 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
545 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
546 E = ND->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000547 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000548 return true;
549
Douglas Gregora59e3902010-01-21 23:27:09 +0000550 return VisitObjCContainerDecl(ND);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000551}
552
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000553bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
554 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
555 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
556 E = PID->protocol_end(); I != E; ++I, ++PL)
557 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
558 return true;
559
560 return VisitObjCContainerDecl(PID);
561}
562
Douglas Gregorb1373d02010-01-20 20:59:29 +0000563bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000564 // Issue callbacks for super class.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000565 if (D->getSuperClass() &&
566 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000567 D->getSuperClassLoc(),
568 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000569 return true;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000570
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000571 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
572 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
573 E = D->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000574 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000575 return true;
576
Douglas Gregora59e3902010-01-21 23:27:09 +0000577 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000578}
579
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000580bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
581 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000582}
583
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000584bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
585 if (Visit(MakeCursorObjCClassRef(D->getCategoryDecl()->getClassInterface(),
586 D->getLocation(), TU)))
587 return true;
588
589 return VisitObjCImplDecl(D);
590}
591
592bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
593#if 0
594 // Issue callbacks for super class.
595 // FIXME: No source location information!
596 if (D->getSuperClass() &&
597 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
598 D->getSuperClassLoc(),
599 TU)))
600 return true;
601#endif
602
603 return VisitObjCImplDecl(D);
604}
605
606bool CursorVisitor::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D) {
607 ObjCForwardProtocolDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
608 for (ObjCForwardProtocolDecl::protocol_iterator I = D->protocol_begin(),
609 E = D->protocol_end();
610 I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000611 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000612 return true;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000613
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000614 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000615}
616
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000617bool CursorVisitor::VisitObjCClassDecl(ObjCClassDecl *D) {
618 for (ObjCClassDecl::iterator C = D->begin(), CEnd = D->end(); C != CEnd; ++C)
619 if (Visit(MakeCursorObjCClassRef(C->getInterface(), C->getLocation(), TU)))
620 return true;
621
622 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000623}
624
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000625bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
626 ASTContext &Context = TU->getASTContext();
627
628 // Some builtin types (such as Objective-C's "id", "sel", and
629 // "Class") have associated declarations. Create cursors for those.
630 QualType VisitType;
631 switch (TL.getType()->getAs<BuiltinType>()->getKind()) {
632 case BuiltinType::Void:
633 case BuiltinType::Bool:
634 case BuiltinType::Char_U:
635 case BuiltinType::UChar:
636 case BuiltinType::Char16:
637 case BuiltinType::Char32:
638 case BuiltinType::UShort:
639 case BuiltinType::UInt:
640 case BuiltinType::ULong:
641 case BuiltinType::ULongLong:
642 case BuiltinType::UInt128:
643 case BuiltinType::Char_S:
644 case BuiltinType::SChar:
645 case BuiltinType::WChar:
646 case BuiltinType::Short:
647 case BuiltinType::Int:
648 case BuiltinType::Long:
649 case BuiltinType::LongLong:
650 case BuiltinType::Int128:
651 case BuiltinType::Float:
652 case BuiltinType::Double:
653 case BuiltinType::LongDouble:
654 case BuiltinType::NullPtr:
655 case BuiltinType::Overload:
656 case BuiltinType::Dependent:
657 break;
658
659 case BuiltinType::UndeducedAuto: // FIXME: Deserves a cursor?
660 break;
661
662 case BuiltinType::ObjCId:
663 VisitType = Context.getObjCIdType();
664 break;
665
666 case BuiltinType::ObjCClass:
667 VisitType = Context.getObjCClassType();
668 break;
669
670 case BuiltinType::ObjCSel:
671 VisitType = Context.getObjCSelType();
672 break;
673 }
674
675 if (!VisitType.isNull()) {
676 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
677 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
678 TU));
679 }
680
681 return false;
682}
683
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000684bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
685 return Visit(MakeCursorTypeRef(TL.getTypedefDecl(), TL.getNameLoc(), TU));
686}
687
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000688bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
689 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
690}
691
692bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
693 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
694}
695
696bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
697 if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
698 return true;
699
700 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
701 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
702 TU)))
703 return true;
704 }
705
706 return false;
707}
708
709bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
710 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseTypeLoc()))
711 return true;
712
713 if (TL.hasProtocolsAsWritten()) {
714 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
715 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I),
716 TL.getProtocolLoc(I),
717 TU)))
718 return true;
719 }
720 }
721
722 return false;
723}
724
725bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
726 return Visit(TL.getPointeeLoc());
727}
728
729bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
730 return Visit(TL.getPointeeLoc());
731}
732
733bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
734 return Visit(TL.getPointeeLoc());
735}
736
737bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
738 return Visit(TL.getPointeeLoc());
739}
740
741bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
742 return Visit(TL.getPointeeLoc());
743}
744
745bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
746 if (Visit(TL.getResultLoc()))
747 return true;
748
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000749 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
750 if (Visit(MakeCXCursor(TL.getArg(I), TU)))
751 return true;
752
753 return false;
754}
755
756bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
757 if (Visit(TL.getElementLoc()))
758 return true;
759
760 if (Expr *Size = TL.getSizeExpr())
761 return Visit(MakeCXCursor(Size, StmtParent, TU));
762
763 return false;
764}
765
Douglas Gregor2332c112010-01-21 20:48:56 +0000766bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
767 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
768}
769
770bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
771 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
772 return Visit(TSInfo->getTypeLoc());
773
774 return false;
775}
776
Douglas Gregora59e3902010-01-21 23:27:09 +0000777bool CursorVisitor::VisitStmt(Stmt *S) {
778 for (Stmt::child_iterator Child = S->child_begin(), ChildEnd = S->child_end();
779 Child != ChildEnd; ++Child) {
780 if (Visit(MakeCXCursor(*Child, StmtParent, TU)))
781 return true;
782 }
783
784 return false;
785}
786
787bool CursorVisitor::VisitDeclStmt(DeclStmt *S) {
788 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
789 D != DEnd; ++D) {
790 if (Visit(MakeCXCursor(*D, TU)))
791 return true;
792 }
793
794 return false;
795}
796
Douglas Gregorf5bab412010-01-22 01:00:11 +0000797bool CursorVisitor::VisitIfStmt(IfStmt *S) {
798 if (VarDecl *Var = S->getConditionVariable()) {
799 if (Visit(MakeCXCursor(Var, TU)))
800 return true;
801 } else if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
802 return true;
803
804 if (S->getThen() && Visit(MakeCXCursor(S->getThen(), StmtParent, TU)))
805 return true;
806
807 if (S->getElse() && Visit(MakeCXCursor(S->getElse(), StmtParent, TU)))
808 return true;
809
810 return false;
811}
812
813bool CursorVisitor::VisitSwitchStmt(SwitchStmt *S) {
814 if (VarDecl *Var = S->getConditionVariable()) {
815 if (Visit(MakeCXCursor(Var, TU)))
816 return true;
817 } else if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
818 return true;
819
820 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
821 return true;
822
823 return false;
824}
825
Daniel Dunbar140fce22010-01-12 02:34:07 +0000826CXString CIndexer::createCXString(const char *String, bool DupString){
Benjamin Kramer62cf3222009-11-09 19:13:48 +0000827 CXString Str;
828 if (DupString) {
829 Str.Spelling = strdup(String);
830 Str.MustFreeString = 1;
831 } else {
832 Str.Spelling = String;
833 Str.MustFreeString = 0;
834 }
835 return Str;
836}
837
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000838extern "C" {
Steve Naroffe56b4ba2009-10-20 14:46:24 +0000839CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000840 int displayDiagnostics) {
Douglas Gregora030b7c2010-01-22 20:35:53 +0000841 CIndexer *CIdxr = new CIndexer();
Steve Naroffe56b4ba2009-10-20 14:46:24 +0000842 if (excludeDeclarationsFromPCH)
843 CIdxr->setOnlyLocalDecls();
844 if (displayDiagnostics)
845 CIdxr->setDisplayDiagnostics();
846 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +0000847}
848
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000849void clang_disposeIndex(CXIndex CIdx) {
Steve Naroff2bd6b9f2009-09-17 18:33:27 +0000850 assert(CIdx && "Passed null CXIndex");
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000851 delete static_cast<CIndexer *>(CIdx);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +0000852}
853
Daniel Dunbar8506dde2009-12-03 01:54:28 +0000854void clang_setUseExternalASTGeneration(CXIndex CIdx, int value) {
855 assert(CIdx && "Passed null CXIndex");
856 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
857 CXXIdx->setUseExternalASTGeneration(value);
858}
859
Steve Naroff50398192009-08-28 15:28:48 +0000860// FIXME: need to pass back error info.
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000861CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
862 const char *ast_filename) {
Steve Naroff50398192009-08-28 15:28:48 +0000863 assert(CIdx && "Passed null CXIndex");
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000864 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000865
Daniel Dunbar5262fda2009-12-03 01:45:44 +0000866 return ASTUnit::LoadFromPCHFile(ast_filename, CXXIdx->getDiags(),
867 CXXIdx->getOnlyLocalDecls(),
868 /* UseBumpAllocator = */ true);
Steve Naroff600866c2009-08-27 19:51:58 +0000869}
870
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000871CXTranslationUnit
872clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
873 const char *source_filename,
874 int num_command_line_args,
875 const char **command_line_args) {
Steve Naroffe56b4ba2009-10-20 14:46:24 +0000876 assert(CIdx && "Passed null CXIndex");
877 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
878
Daniel Dunbar8506dde2009-12-03 01:54:28 +0000879 if (!CXXIdx->getUseExternalASTGeneration()) {
880 llvm::SmallVector<const char *, 16> Args;
881
882 // The 'source_filename' argument is optional. If the caller does not
883 // specify it then it is assumed that the source file is specified
884 // in the actual argument list.
885 if (source_filename)
886 Args.push_back(source_filename);
887 Args.insert(Args.end(), command_line_args,
888 command_line_args + num_command_line_args);
889
Daniel Dunbar94220972009-12-05 02:17:18 +0000890 unsigned NumErrors = CXXIdx->getDiags().getNumErrors();
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000891
Ted Kremenek29b72842010-01-07 22:49:05 +0000892#ifdef USE_CRASHTRACER
893 ArgsCrashTracerInfo ACTI(Args);
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000894#endif
895
Daniel Dunbar94220972009-12-05 02:17:18 +0000896 llvm::OwningPtr<ASTUnit> Unit(
897 ASTUnit::LoadFromCommandLine(Args.data(), Args.data() + Args.size(),
Daniel Dunbar869824e2009-12-13 03:46:13 +0000898 CXXIdx->getDiags(),
899 CXXIdx->getClangResourcesPath(),
Daniel Dunbar94220972009-12-05 02:17:18 +0000900 CXXIdx->getOnlyLocalDecls(),
901 /* UseBumpAllocator = */ true));
Ted Kremenek29b72842010-01-07 22:49:05 +0000902
Daniel Dunbar94220972009-12-05 02:17:18 +0000903 // FIXME: Until we have broader testing, just drop the entire AST if we
904 // encountered an error.
905 if (NumErrors != CXXIdx->getDiags().getNumErrors())
906 return 0;
907
908 return Unit.take();
Daniel Dunbar8506dde2009-12-03 01:54:28 +0000909 }
910
Ted Kremenek139ba862009-10-22 00:03:57 +0000911 // Build up the arguments for invoking 'clang'.
Ted Kremenek74cd0692009-10-15 23:21:22 +0000912 std::vector<const char *> argv;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000913
Ted Kremenek139ba862009-10-22 00:03:57 +0000914 // First add the complete path to the 'clang' executable.
915 llvm::sys::Path ClangPath = static_cast<CIndexer *>(CIdx)->getClangPath();
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000916 argv.push_back(ClangPath.c_str());
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000917
Ted Kremenek139ba862009-10-22 00:03:57 +0000918 // Add the '-emit-ast' option as our execution mode for 'clang'.
Ted Kremenek74cd0692009-10-15 23:21:22 +0000919 argv.push_back("-emit-ast");
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000920
Ted Kremenek139ba862009-10-22 00:03:57 +0000921 // The 'source_filename' argument is optional. If the caller does not
922 // specify it then it is assumed that the source file is specified
923 // in the actual argument list.
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000924 if (source_filename)
925 argv.push_back(source_filename);
Ted Kremenek139ba862009-10-22 00:03:57 +0000926
Steve Naroff37b5ac22009-10-15 20:50:09 +0000927 // Generate a temporary name for the AST file.
Ted Kremenek139ba862009-10-22 00:03:57 +0000928 argv.push_back("-o");
Steve Naroff37b5ac22009-10-15 20:50:09 +0000929 char astTmpFile[L_tmpnam];
Ted Kremenek74cd0692009-10-15 23:21:22 +0000930 argv.push_back(tmpnam(astTmpFile));
Ted Kremenek139ba862009-10-22 00:03:57 +0000931
932 // Process the compiler options, stripping off '-o', '-c', '-fsyntax-only'.
933 for (int i = 0; i < num_command_line_args; ++i)
934 if (const char *arg = command_line_args[i]) {
935 if (strcmp(arg, "-o") == 0) {
936 ++i; // Also skip the matching argument.
937 continue;
938 }
939 if (strcmp(arg, "-emit-ast") == 0 ||
940 strcmp(arg, "-c") == 0 ||
941 strcmp(arg, "-fsyntax-only") == 0) {
942 continue;
943 }
944
945 // Keep the argument.
946 argv.push_back(arg);
Steve Naroffe56b4ba2009-10-20 14:46:24 +0000947 }
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000948
Ted Kremenek139ba862009-10-22 00:03:57 +0000949 // Add the null terminator.
Ted Kremenek74cd0692009-10-15 23:21:22 +0000950 argv.push_back(NULL);
951
Ted Kremenekfeb15e32009-10-26 22:14:08 +0000952 // Invoke 'clang'.
953 llvm::sys::Path DevNull; // leave empty, causes redirection to /dev/null
954 // on Unix or NUL (Windows).
Ted Kremenek379afec2009-10-22 03:24:01 +0000955 std::string ErrMsg;
Ted Kremenekc46e4632009-10-19 22:27:32 +0000956 const llvm::sys::Path *Redirects[] = { &DevNull, &DevNull, &DevNull, NULL };
Ted Kremenek379afec2009-10-22 03:24:01 +0000957 llvm::sys::Program::ExecuteAndWait(ClangPath, &argv[0], /* env */ NULL,
958 /* redirects */ !CXXIdx->getDisplayDiagnostics() ? &Redirects[0] : NULL,
959 /* secondsToWait */ 0, /* memoryLimits */ 0, &ErrMsg);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000960
Ted Kremenek0854d702009-11-10 19:18:52 +0000961 if (CXXIdx->getDisplayDiagnostics() && !ErrMsg.empty()) {
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000962 llvm::errs() << "clang_createTranslationUnitFromSourceFile: " << ErrMsg
Daniel Dunbaracca7252009-11-30 20:42:49 +0000963 << '\n' << "Arguments: \n";
Ted Kremenek379afec2009-10-22 03:24:01 +0000964 for (std::vector<const char*>::iterator I = argv.begin(), E = argv.end();
Ted Kremenek779e5f42009-10-26 22:08:39 +0000965 I!=E; ++I) {
966 if (*I)
967 llvm::errs() << ' ' << *I << '\n';
968 }
969 llvm::errs() << '\n';
Ted Kremenek379afec2009-10-22 03:24:01 +0000970 }
Benjamin Kramer0829a832009-10-18 11:19:36 +0000971
Steve Naroff37b5ac22009-10-15 20:50:09 +0000972 // Finally, we create the translation unit from the ast file.
Steve Naroffe19944c2009-10-15 22:23:48 +0000973 ASTUnit *ATU = static_cast<ASTUnit *>(
Daniel Dunbaracca7252009-11-30 20:42:49 +0000974 clang_createTranslationUnit(CIdx, astTmpFile));
Steve Naroffe56b4ba2009-10-20 14:46:24 +0000975 if (ATU)
976 ATU->unlinkTemporaryFile();
Steve Naroffe19944c2009-10-15 22:23:48 +0000977 return ATU;
Steve Naroff5b7d8e22009-10-15 20:04:39 +0000978}
979
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000980void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Steve Naroff2bd6b9f2009-09-17 18:33:27 +0000981 assert(CTUnit && "Passed null CXTranslationUnit");
982 delete static_cast<ASTUnit *>(CTUnit);
983}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000984
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000985CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Steve Naroffaf08ddc2009-09-03 15:49:00 +0000986 assert(CTUnit && "Passed null CXTranslationUnit");
Steve Naroff77accc12009-09-03 18:19:54 +0000987 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit);
Ted Kremenek4b333d22010-01-12 00:36:38 +0000988 return CIndexer::createCXString(CXXUnit->getOriginalSourceFileName().c_str(),
989 true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +0000990}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +0000991
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +0000992CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000993 CXCursor Result = { CXCursor_TranslationUnit, { 0, 0, TU } };
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +0000994 return Result;
995}
996
Ted Kremenekfb480492010-01-13 21:46:36 +0000997} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +0000998
Ted Kremenekfb480492010-01-13 21:46:36 +0000999//===----------------------------------------------------------------------===//
Douglas Gregor1db19de2010-01-19 21:36:55 +00001000// CXSourceLocation and CXSourceRange Operations.
1001//===----------------------------------------------------------------------===//
1002
Douglas Gregorb9790342010-01-22 21:44:22 +00001003extern "C" {
1004CXSourceLocation clang_getNullLocation() {
1005 CXSourceLocation Result = { 0, 0 };
1006 return Result;
1007}
1008
1009unsigned clang_equalLocations(CXSourceLocation loc1, CXSourceLocation loc2) {
1010 return loc1.ptr_data == loc2.ptr_data && loc1.int_data == loc2.int_data;
1011}
1012
1013CXSourceLocation clang_getLocation(CXTranslationUnit tu,
1014 CXFile file,
1015 unsigned line,
1016 unsigned column) {
1017 if (!tu)
1018 return clang_getNullLocation();
1019
1020 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
1021 SourceLocation SLoc
1022 = CXXUnit->getSourceManager().getLocation(
1023 static_cast<const FileEntry *>(file),
1024 line, column);
1025
1026 return translateSourceLocation(CXXUnit->getASTContext(), SLoc, false);
1027}
1028
1029CXSourceRange clang_getRange(CXSourceLocation begin, CXSourceLocation end) {
1030 if (begin.ptr_data != end.ptr_data) {
1031 CXSourceRange Result = { 0, 0, 0 };
1032 return Result;
1033 }
1034
1035 CXSourceRange Result = { begin.ptr_data, begin.int_data, end.int_data };
1036 return Result;
1037}
1038
Douglas Gregor1db19de2010-01-19 21:36:55 +00001039void clang_getInstantiationLocation(CXSourceLocation location,
1040 CXFile *file,
1041 unsigned *line,
1042 unsigned *column) {
1043 CXSourceLocationPtr Ptr
1044 = CXSourceLocationPtr::getFromOpaqueValue(location.ptr_data);
1045 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
1046
1047 if (!Ptr.getPointer() || Loc.isInvalid()) {
1048 if (file)
1049 *file = 0;
1050 if (line)
1051 *line = 0;
1052 if (column)
1053 *column = 0;
1054 return;
1055 }
1056
1057 // FIXME: This is largely copy-paste from
1058 ///TextDiagnosticPrinter::HighlightRange. When it is clear that this is
1059 // what we want the two routines should be refactored.
1060 ASTContext &Context = *Ptr.getPointer();
1061 SourceManager &SM = Context.getSourceManager();
1062 SourceLocation InstLoc = SM.getInstantiationLoc(Loc);
1063
1064 if (Ptr.getInt()) {
1065 // We want the last character in this location, so we will adjust
1066 // the instantiation location accordingly.
1067
1068 // If the location is from a macro instantiation, get the end of
1069 // the instantiation range.
1070 if (Loc.isMacroID())
1071 InstLoc = SM.getInstantiationRange(Loc).second;
1072
1073 // Measure the length token we're pointing at, so we can adjust
1074 // the physical location in the file to point at the last
1075 // character.
1076 // FIXME: This won't cope with trigraphs or escaped newlines
1077 // well. For that, we actually need a preprocessor, which isn't
1078 // currently available here. Eventually, we'll switch the pointer
1079 // data of CXSourceLocation/CXSourceRange to a translation unit
1080 // (CXXUnit), so that the preprocessor will be available here. At
1081 // that point, we can use Preprocessor::getLocForEndOfToken().
1082 unsigned Length = Lexer::MeasureTokenLength(InstLoc, SM,
1083 Context.getLangOptions());
1084 if (Length > 0)
1085 InstLoc = InstLoc.getFileLocWithOffset(Length - 1);
1086 }
1087
1088 if (file)
1089 *file = (void *)SM.getFileEntryForID(SM.getFileID(InstLoc));
1090 if (line)
1091 *line = SM.getInstantiationLineNumber(InstLoc);
1092 if (column)
1093 *column = SM.getInstantiationColumnNumber(InstLoc);
1094}
1095
1096CXSourceLocation clang_getRangeStart(CXSourceRange range) {
1097 CXSourceLocation Result = { range.ptr_data, range.begin_int_data };
1098 return Result;
1099}
1100
1101CXSourceLocation clang_getRangeEnd(CXSourceRange range) {
1102 llvm::PointerIntPair<ASTContext *, 1, bool> Ptr;
1103 Ptr.setPointer(static_cast<ASTContext *>(range.ptr_data));
1104 Ptr.setInt(true);
1105 CXSourceLocation Result = { Ptr.getOpaqueValue(), range.end_int_data };
1106 return Result;
1107}
1108
Douglas Gregorb9790342010-01-22 21:44:22 +00001109} // end: extern "C"
1110
Douglas Gregor1db19de2010-01-19 21:36:55 +00001111//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00001112// CXFile Operations.
1113//===----------------------------------------------------------------------===//
1114
1115extern "C" {
Steve Naroff88145032009-10-27 14:35:18 +00001116const char *clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00001117 if (!SFile)
1118 return 0;
1119
Steve Naroff88145032009-10-27 14:35:18 +00001120 assert(SFile && "Passed null CXFile");
1121 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
1122 return FEnt->getName();
1123}
1124
1125time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00001126 if (!SFile)
1127 return 0;
1128
Steve Naroff88145032009-10-27 14:35:18 +00001129 assert(SFile && "Passed null CXFile");
1130 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
1131 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +00001132}
Douglas Gregorb9790342010-01-22 21:44:22 +00001133
1134CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
1135 if (!tu)
1136 return 0;
1137
1138 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
1139
1140 FileManager &FMgr = CXXUnit->getFileManager();
1141 const FileEntry *File = FMgr.getFile(file_name, file_name+strlen(file_name));
1142 return const_cast<FileEntry *>(File);
1143}
1144
Ted Kremenekfb480492010-01-13 21:46:36 +00001145} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +00001146
Ted Kremenekfb480492010-01-13 21:46:36 +00001147//===----------------------------------------------------------------------===//
1148// CXCursor Operations.
1149//===----------------------------------------------------------------------===//
1150
Ted Kremenekfb480492010-01-13 21:46:36 +00001151static Decl *getDeclFromExpr(Stmt *E) {
1152 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
1153 return RefExpr->getDecl();
1154 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
1155 return ME->getMemberDecl();
1156 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
1157 return RE->getDecl();
1158
1159 if (CallExpr *CE = dyn_cast<CallExpr>(E))
1160 return getDeclFromExpr(CE->getCallee());
1161 if (CastExpr *CE = dyn_cast<CastExpr>(E))
1162 return getDeclFromExpr(CE->getSubExpr());
1163 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
1164 return OME->getMethodDecl();
1165
1166 return 0;
1167}
1168
1169extern "C" {
Douglas Gregorb1373d02010-01-20 20:59:29 +00001170
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001171unsigned clang_visitChildren(CXCursor parent,
Douglas Gregorb1373d02010-01-20 20:59:29 +00001172 CXCursorVisitor visitor,
1173 CXClientData client_data) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001174 ASTUnit *CXXUnit = getCursorASTUnit(parent);
Douglas Gregorb1373d02010-01-20 20:59:29 +00001175
1176 unsigned PCHLevel = Decl::MaxPCHLevel;
1177
1178 // Set the PCHLevel to filter out unwanted decls if requested.
1179 if (CXXUnit->getOnlyLocalDecls()) {
1180 PCHLevel = 0;
1181
1182 // If the main input was an AST, bump the level.
1183 if (CXXUnit->isMainFileAST())
1184 ++PCHLevel;
1185 }
1186
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001187 CursorVisitor CursorVis(CXXUnit, visitor, client_data, PCHLevel);
Douglas Gregorb1373d02010-01-20 20:59:29 +00001188 return CursorVis.VisitChildren(parent);
1189}
1190
Douglas Gregor78205d42010-01-20 21:45:58 +00001191static CXString getDeclSpelling(Decl *D) {
1192 NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
1193 if (!ND)
1194 return CIndexer::createCXString("");
1195
1196 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
1197 return CIndexer::createCXString(OMD->getSelector().getAsString().c_str(),
1198 true);
1199
1200 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
1201 // No, this isn't the same as the code below. getIdentifier() is non-virtual
1202 // and returns different names. NamedDecl returns the class name and
1203 // ObjCCategoryImplDecl returns the category name.
1204 return CIndexer::createCXString(CIMP->getIdentifier()->getNameStart());
1205
1206 if (ND->getIdentifier())
1207 return CIndexer::createCXString(ND->getIdentifier()->getNameStart());
1208
1209 return CIndexer::createCXString("");
1210}
1211
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001212CXString clang_getCursorSpelling(CXCursor C) {
Daniel Dunbarc81d7182010-01-18 17:52:42 +00001213 assert(getCursorDecl(C) && "CXCursor has null decl");
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001214 if (clang_isTranslationUnit(C.kind))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001215 return clang_getTranslationUnitSpelling(C.data[2]);
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001216
Steve Narofff334b4e2009-09-02 18:26:48 +00001217 if (clang_isReference(C.kind)) {
1218 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00001219 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +00001220 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
1221 return CIndexer::createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00001222 }
1223 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +00001224 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
1225 return CIndexer::createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00001226 }
1227 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +00001228 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +00001229 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenek4b333d22010-01-12 00:36:38 +00001230 return CIndexer::createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00001231 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001232 case CXCursor_TypeRef: {
1233 TypeDecl *Type = getCursorTypeRef(C).first;
1234 assert(Type && "Missing type decl");
1235
1236 return CIndexer::createCXString(
1237 getCursorContext(C).getTypeDeclType(Type).getAsString().c_str(),
1238 true);
1239 }
1240
Daniel Dunbaracca7252009-11-30 20:42:49 +00001241 default:
Ted Kremenek4b333d22010-01-12 00:36:38 +00001242 return CIndexer::createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +00001243 }
1244 }
Douglas Gregor97b98722010-01-19 23:20:36 +00001245
1246 if (clang_isExpression(C.kind)) {
1247 Decl *D = getDeclFromExpr(getCursorExpr(C));
1248 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +00001249 return getDeclSpelling(D);
Douglas Gregor97b98722010-01-19 23:20:36 +00001250 return CIndexer::createCXString("");
1251 }
1252
Douglas Gregor78205d42010-01-20 21:45:58 +00001253 return getDeclSpelling(getCursorDecl(C));
Steve Narofff334b4e2009-09-02 18:26:48 +00001254}
1255
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001256const char *clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00001257 switch (Kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00001258 case CXCursor_FunctionDecl: return "FunctionDecl";
1259 case CXCursor_TypedefDecl: return "TypedefDecl";
1260 case CXCursor_EnumDecl: return "EnumDecl";
1261 case CXCursor_EnumConstantDecl: return "EnumConstantDecl";
1262 case CXCursor_StructDecl: return "StructDecl";
1263 case CXCursor_UnionDecl: return "UnionDecl";
1264 case CXCursor_ClassDecl: return "ClassDecl";
1265 case CXCursor_FieldDecl: return "FieldDecl";
1266 case CXCursor_VarDecl: return "VarDecl";
1267 case CXCursor_ParmDecl: return "ParmDecl";
1268 case CXCursor_ObjCInterfaceDecl: return "ObjCInterfaceDecl";
1269 case CXCursor_ObjCCategoryDecl: return "ObjCCategoryDecl";
1270 case CXCursor_ObjCProtocolDecl: return "ObjCProtocolDecl";
1271 case CXCursor_ObjCPropertyDecl: return "ObjCPropertyDecl";
1272 case CXCursor_ObjCIvarDecl: return "ObjCIvarDecl";
1273 case CXCursor_ObjCInstanceMethodDecl: return "ObjCInstanceMethodDecl";
1274 case CXCursor_ObjCClassMethodDecl: return "ObjCClassMethodDecl";
Douglas Gregorb6998662010-01-19 19:34:47 +00001275 case CXCursor_ObjCImplementationDecl: return "ObjCImplementationDecl";
1276 case CXCursor_ObjCCategoryImplDecl: return "ObjCCategoryImplDecl";
Douglas Gregor30122132010-01-19 22:07:56 +00001277 case CXCursor_UnexposedDecl: return "UnexposedDecl";
Daniel Dunbaracca7252009-11-30 20:42:49 +00001278 case CXCursor_ObjCSuperClassRef: return "ObjCSuperClassRef";
1279 case CXCursor_ObjCProtocolRef: return "ObjCProtocolRef";
1280 case CXCursor_ObjCClassRef: return "ObjCClassRef";
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001281 case CXCursor_TypeRef: return "TypeRef";
Douglas Gregor97b98722010-01-19 23:20:36 +00001282 case CXCursor_UnexposedExpr: return "UnexposedExpr";
1283 case CXCursor_DeclRefExpr: return "DeclRefExpr";
1284 case CXCursor_MemberRefExpr: return "MemberRefExpr";
1285 case CXCursor_CallExpr: return "CallExpr";
1286 case CXCursor_ObjCMessageExpr: return "ObjCMessageExpr";
1287 case CXCursor_UnexposedStmt: return "UnexposedStmt";
Daniel Dunbaracca7252009-11-30 20:42:49 +00001288 case CXCursor_InvalidFile: return "InvalidFile";
1289 case CXCursor_NoDeclFound: return "NoDeclFound";
1290 case CXCursor_NotImplemented: return "NotImplemented";
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001291 case CXCursor_TranslationUnit: return "TranslationUnit";
Steve Naroff89922f82009-08-31 00:59:03 +00001292 }
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00001293
1294 llvm_unreachable("Unhandled CXCursorKind");
1295 return NULL;
Steve Naroff600866c2009-08-27 19:51:58 +00001296}
Steve Naroff89922f82009-08-31 00:59:03 +00001297
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001298enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
1299 CXCursor parent,
1300 CXClientData client_data) {
1301 CXCursor *BestCursor = static_cast<CXCursor *>(client_data);
1302 *BestCursor = cursor;
1303 return CXChildVisit_Recurse;
1304}
1305
Douglas Gregorb9790342010-01-22 21:44:22 +00001306CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
1307 if (!TU)
Ted Kremenekf4629892010-01-14 01:51:23 +00001308 return clang_getNullCursor();
Ted Kremenekf4629892010-01-14 01:51:23 +00001309
Douglas Gregorb9790342010-01-22 21:44:22 +00001310 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
1311
1312 SourceLocation SLoc = translateSourceLocation(Loc);
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001313 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
1314 if (SLoc.isValid()) {
1315 SourceRange RegionOfInterest(SLoc,
1316 CXXUnit->getPreprocessor().getLocForEndOfToken(SLoc, 1));
1317
1318 // FIXME: Would be great to have a "hint" cursor, then walk from that
1319 // hint cursor upward until we find a cursor whose source range encloses
1320 // the region of interest, rather than starting from the translation unit.
1321 CXCursor Parent = clang_getTranslationUnitCursor(CXXUnit);
1322 CursorVisitor CursorVis(CXXUnit, GetCursorVisitor, &Result,
1323 Decl::MaxPCHLevel, RegionOfInterest);
1324 CursorVis.VisitChildren(Parent);
Steve Naroff77128dd2009-09-15 20:25:34 +00001325 }
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001326 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00001327}
1328
Ted Kremenek73885552009-11-17 19:28:59 +00001329CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00001330 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00001331}
1332
1333unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00001334 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00001335}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001336
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001337unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00001338 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
1339}
1340
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001341unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +00001342 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
1343}
Steve Naroff2d4d6292009-08-31 14:26:51 +00001344
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001345unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00001346 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
1347}
1348
Douglas Gregor97b98722010-01-19 23:20:36 +00001349unsigned clang_isExpression(enum CXCursorKind K) {
1350 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
1351}
1352
1353unsigned clang_isStatement(enum CXCursorKind K) {
1354 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
1355}
1356
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001357unsigned clang_isTranslationUnit(enum CXCursorKind K) {
1358 return K == CXCursor_TranslationUnit;
1359}
1360
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001361CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00001362 return C.kind;
1363}
1364
Douglas Gregor97b98722010-01-19 23:20:36 +00001365static SourceLocation getLocationFromExpr(Expr *E) {
1366 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
1367 return /*FIXME:*/Msg->getLeftLoc();
1368 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
1369 return DRE->getLocation();
1370 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
1371 return Member->getMemberLoc();
1372 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
1373 return Ivar->getLocation();
1374 return E->getLocStart();
1375}
1376
Douglas Gregor98258af2010-01-18 22:46:11 +00001377CXSourceLocation clang_getCursorLocation(CXCursor C) {
1378 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00001379 switch (C.kind) {
1380 case CXCursor_ObjCSuperClassRef: {
1381 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1382 = getCursorObjCSuperClassRef(C);
Douglas Gregor1db19de2010-01-19 21:36:55 +00001383 return translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001384 }
1385
1386 case CXCursor_ObjCProtocolRef: {
1387 std::pair<ObjCProtocolDecl *, SourceLocation> P
1388 = getCursorObjCProtocolRef(C);
Douglas Gregor1db19de2010-01-19 21:36:55 +00001389 return translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001390 }
1391
1392 case CXCursor_ObjCClassRef: {
1393 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1394 = getCursorObjCClassRef(C);
Douglas Gregor1db19de2010-01-19 21:36:55 +00001395 return translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001396 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001397
1398 case CXCursor_TypeRef: {
1399 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
1400 return translateSourceLocation(P.first->getASTContext(), P.second);
1401 }
Douglas Gregorf46034a2010-01-18 23:41:10 +00001402
Douglas Gregorf46034a2010-01-18 23:41:10 +00001403 default:
1404 // FIXME: Need a way to enumerate all non-reference cases.
1405 llvm_unreachable("Missed a reference kind");
1406 }
Douglas Gregor98258af2010-01-18 22:46:11 +00001407 }
Douglas Gregor97b98722010-01-19 23:20:36 +00001408
1409 if (clang_isExpression(C.kind))
1410 return translateSourceLocation(getCursorContext(C),
1411 getLocationFromExpr(getCursorExpr(C)));
1412
Douglas Gregor98258af2010-01-18 22:46:11 +00001413 if (!getCursorDecl(C)) {
Douglas Gregor1db19de2010-01-19 21:36:55 +00001414 CXSourceLocation empty = { 0, 0 };
Douglas Gregor98258af2010-01-18 22:46:11 +00001415 return empty;
1416 }
1417
Douglas Gregorf46034a2010-01-18 23:41:10 +00001418 Decl *D = getCursorDecl(C);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001419 SourceLocation Loc = D->getLocation();
1420 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
1421 Loc = Class->getClassLoc();
Douglas Gregor1db19de2010-01-19 21:36:55 +00001422 return translateSourceLocation(D->getASTContext(), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00001423}
Douglas Gregora7bde202010-01-19 00:34:46 +00001424
1425CXSourceRange clang_getCursorExtent(CXCursor C) {
1426 if (clang_isReference(C.kind)) {
1427 switch (C.kind) {
1428 case CXCursor_ObjCSuperClassRef: {
1429 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1430 = getCursorObjCSuperClassRef(C);
1431 return translateSourceRange(P.first->getASTContext(), P.second);
1432 }
1433
1434 case CXCursor_ObjCProtocolRef: {
1435 std::pair<ObjCProtocolDecl *, SourceLocation> P
1436 = getCursorObjCProtocolRef(C);
1437 return translateSourceRange(P.first->getASTContext(), P.second);
1438 }
1439
1440 case CXCursor_ObjCClassRef: {
1441 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1442 = getCursorObjCClassRef(C);
1443
1444 return translateSourceRange(P.first->getASTContext(), P.second);
1445 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001446
1447 case CXCursor_TypeRef: {
1448 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
1449 return translateSourceRange(P.first->getASTContext(), P.second);
1450 }
Douglas Gregora7bde202010-01-19 00:34:46 +00001451
Douglas Gregora7bde202010-01-19 00:34:46 +00001452 default:
1453 // FIXME: Need a way to enumerate all non-reference cases.
1454 llvm_unreachable("Missed a reference kind");
1455 }
1456 }
Douglas Gregor97b98722010-01-19 23:20:36 +00001457
1458 if (clang_isExpression(C.kind))
1459 return translateSourceRange(getCursorContext(C),
1460 getCursorExpr(C)->getSourceRange());
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001461
1462 if (clang_isStatement(C.kind))
1463 return translateSourceRange(getCursorContext(C),
1464 getCursorStmt(C)->getSourceRange());
Douglas Gregora7bde202010-01-19 00:34:46 +00001465
1466 if (!getCursorDecl(C)) {
Douglas Gregor1db19de2010-01-19 21:36:55 +00001467 CXSourceRange empty = { 0, 0, 0 };
Douglas Gregora7bde202010-01-19 00:34:46 +00001468 return empty;
1469 }
1470
1471 Decl *D = getCursorDecl(C);
1472 return translateSourceRange(D->getASTContext(), D->getSourceRange());
1473}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001474
1475CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001476 if (clang_isInvalid(C.kind))
1477 return clang_getNullCursor();
1478
1479 ASTUnit *CXXUnit = getCursorASTUnit(C);
Douglas Gregorb6998662010-01-19 19:34:47 +00001480 if (clang_isDeclaration(C.kind))
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001481 return C;
Douglas Gregor98258af2010-01-18 22:46:11 +00001482
Douglas Gregor97b98722010-01-19 23:20:36 +00001483 if (clang_isExpression(C.kind)) {
1484 Decl *D = getDeclFromExpr(getCursorExpr(C));
1485 if (D)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001486 return MakeCXCursor(D, CXXUnit);
Douglas Gregor97b98722010-01-19 23:20:36 +00001487 return clang_getNullCursor();
1488 }
1489
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001490 if (!clang_isReference(C.kind))
1491 return clang_getNullCursor();
1492
1493 switch (C.kind) {
1494 case CXCursor_ObjCSuperClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001495 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, CXXUnit);
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001496
1497 case CXCursor_ObjCProtocolRef: {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001498 return MakeCXCursor(getCursorObjCProtocolRef(C).first, CXXUnit);
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001499
1500 case CXCursor_ObjCClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001501 return MakeCXCursor(getCursorObjCClassRef(C).first, CXXUnit);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001502
1503 case CXCursor_TypeRef:
1504 return MakeCXCursor(getCursorTypeRef(C).first, CXXUnit);
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001505
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001506 default:
1507 // We would prefer to enumerate all non-reference cursor kinds here.
1508 llvm_unreachable("Unhandled reference cursor kind");
1509 break;
1510 }
1511 }
1512
1513 return clang_getNullCursor();
1514}
1515
Douglas Gregorb6998662010-01-19 19:34:47 +00001516CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001517 if (clang_isInvalid(C.kind))
1518 return clang_getNullCursor();
1519
1520 ASTUnit *CXXUnit = getCursorASTUnit(C);
1521
Douglas Gregorb6998662010-01-19 19:34:47 +00001522 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00001523 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00001524 C = clang_getCursorReferenced(C);
1525 WasReference = true;
1526 }
1527
1528 if (!clang_isDeclaration(C.kind))
1529 return clang_getNullCursor();
1530
1531 Decl *D = getCursorDecl(C);
1532 if (!D)
1533 return clang_getNullCursor();
1534
1535 switch (D->getKind()) {
1536 // Declaration kinds that don't really separate the notions of
1537 // declaration and definition.
1538 case Decl::Namespace:
1539 case Decl::Typedef:
1540 case Decl::TemplateTypeParm:
1541 case Decl::EnumConstant:
1542 case Decl::Field:
1543 case Decl::ObjCIvar:
1544 case Decl::ObjCAtDefsField:
1545 case Decl::ImplicitParam:
1546 case Decl::ParmVar:
1547 case Decl::NonTypeTemplateParm:
1548 case Decl::TemplateTemplateParm:
1549 case Decl::ObjCCategoryImpl:
1550 case Decl::ObjCImplementation:
1551 case Decl::LinkageSpec:
1552 case Decl::ObjCPropertyImpl:
1553 case Decl::FileScopeAsm:
1554 case Decl::StaticAssert:
1555 case Decl::Block:
1556 return C;
1557
1558 // Declaration kinds that don't make any sense here, but are
1559 // nonetheless harmless.
1560 case Decl::TranslationUnit:
1561 case Decl::Template:
1562 case Decl::ObjCContainer:
1563 break;
1564
1565 // Declaration kinds for which the definition is not resolvable.
1566 case Decl::UnresolvedUsingTypename:
1567 case Decl::UnresolvedUsingValue:
1568 break;
1569
1570 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001571 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
1572 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001573
1574 case Decl::NamespaceAlias:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001575 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001576
1577 case Decl::Enum:
1578 case Decl::Record:
1579 case Decl::CXXRecord:
1580 case Decl::ClassTemplateSpecialization:
1581 case Decl::ClassTemplatePartialSpecialization:
1582 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition(D->getASTContext()))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001583 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001584 return clang_getNullCursor();
1585
1586 case Decl::Function:
1587 case Decl::CXXMethod:
1588 case Decl::CXXConstructor:
1589 case Decl::CXXDestructor:
1590 case Decl::CXXConversion: {
1591 const FunctionDecl *Def = 0;
1592 if (cast<FunctionDecl>(D)->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001593 return MakeCXCursor(const_cast<FunctionDecl *>(Def), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001594 return clang_getNullCursor();
1595 }
1596
1597 case Decl::Var: {
1598 VarDecl *Var = cast<VarDecl>(D);
1599
1600 // Variables with initializers have definitions.
1601 const VarDecl *Def = 0;
1602 if (Var->getDefinition(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001603 return MakeCXCursor(const_cast<VarDecl *>(Def), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001604
1605 // extern and private_extern variables are not definitions.
1606 if (Var->hasExternalStorage())
1607 return clang_getNullCursor();
1608
1609 // In-line static data members do not have definitions.
1610 if (Var->isStaticDataMember() && !Var->isOutOfLine())
1611 return clang_getNullCursor();
1612
1613 // All other variables are themselves definitions.
1614 return C;
1615 }
1616
1617 case Decl::FunctionTemplate: {
1618 const FunctionDecl *Def = 0;
1619 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001620 return MakeCXCursor(Def->getDescribedFunctionTemplate(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001621 return clang_getNullCursor();
1622 }
1623
1624 case Decl::ClassTemplate: {
1625 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
1626 ->getDefinition(D->getASTContext()))
1627 return MakeCXCursor(
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001628 cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
1629 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001630 return clang_getNullCursor();
1631 }
1632
1633 case Decl::Using: {
1634 UsingDecl *Using = cast<UsingDecl>(D);
1635 CXCursor Def = clang_getNullCursor();
1636 for (UsingDecl::shadow_iterator S = Using->shadow_begin(),
1637 SEnd = Using->shadow_end();
1638 S != SEnd; ++S) {
1639 if (Def != clang_getNullCursor()) {
1640 // FIXME: We have no way to return multiple results.
1641 return clang_getNullCursor();
1642 }
1643
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001644 Def = clang_getCursorDefinition(MakeCXCursor((*S)->getTargetDecl(),
1645 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00001646 }
1647
1648 return Def;
1649 }
1650
1651 case Decl::UsingShadow:
1652 return clang_getCursorDefinition(
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001653 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
1654 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00001655
1656 case Decl::ObjCMethod: {
1657 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
1658 if (Method->isThisDeclarationADefinition())
1659 return C;
1660
1661 // Dig out the method definition in the associated
1662 // @implementation, if we have it.
1663 // FIXME: The ASTs should make finding the definition easier.
1664 if (ObjCInterfaceDecl *Class
1665 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
1666 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
1667 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
1668 Method->isInstanceMethod()))
1669 if (Def->isThisDeclarationADefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001670 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001671
1672 return clang_getNullCursor();
1673 }
1674
1675 case Decl::ObjCCategory:
1676 if (ObjCCategoryImplDecl *Impl
1677 = cast<ObjCCategoryDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001678 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001679 return clang_getNullCursor();
1680
1681 case Decl::ObjCProtocol:
1682 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
1683 return C;
1684 return clang_getNullCursor();
1685
1686 case Decl::ObjCInterface:
1687 // There are two notions of a "definition" for an Objective-C
1688 // class: the interface and its implementation. When we resolved a
1689 // reference to an Objective-C class, produce the @interface as
1690 // the definition; when we were provided with the interface,
1691 // produce the @implementation as the definition.
1692 if (WasReference) {
1693 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
1694 return C;
1695 } else if (ObjCImplementationDecl *Impl
1696 = cast<ObjCInterfaceDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001697 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001698 return clang_getNullCursor();
1699
1700 case Decl::ObjCProperty:
1701 // FIXME: We don't really know where to find the
1702 // ObjCPropertyImplDecls that implement this property.
1703 return clang_getNullCursor();
1704
1705 case Decl::ObjCCompatibleAlias:
1706 if (ObjCInterfaceDecl *Class
1707 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
1708 if (!Class->isForwardDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001709 return MakeCXCursor(Class, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001710
1711 return clang_getNullCursor();
1712
1713 case Decl::ObjCForwardProtocol: {
1714 ObjCForwardProtocolDecl *Forward = cast<ObjCForwardProtocolDecl>(D);
1715 if (Forward->protocol_size() == 1)
1716 return clang_getCursorDefinition(
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001717 MakeCXCursor(*Forward->protocol_begin(),
1718 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00001719
1720 // FIXME: Cannot return multiple definitions.
1721 return clang_getNullCursor();
1722 }
1723
1724 case Decl::ObjCClass: {
1725 ObjCClassDecl *Class = cast<ObjCClassDecl>(D);
1726 if (Class->size() == 1) {
1727 ObjCInterfaceDecl *IFace = Class->begin()->getInterface();
1728 if (!IFace->isForwardDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001729 return MakeCXCursor(IFace, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001730 return clang_getNullCursor();
1731 }
1732
1733 // FIXME: Cannot return multiple definitions.
1734 return clang_getNullCursor();
1735 }
1736
1737 case Decl::Friend:
1738 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001739 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00001740 return clang_getNullCursor();
1741
1742 case Decl::FriendTemplate:
1743 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001744 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00001745 return clang_getNullCursor();
1746 }
1747
1748 return clang_getNullCursor();
1749}
1750
1751unsigned clang_isCursorDefinition(CXCursor C) {
1752 if (!clang_isDeclaration(C.kind))
1753 return 0;
1754
1755 return clang_getCursorDefinition(C) == C;
1756}
1757
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001758void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00001759 const char **startBuf,
1760 const char **endBuf,
1761 unsigned *startLine,
1762 unsigned *startColumn,
1763 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001764 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00001765 assert(getCursorDecl(C) && "CXCursor has null decl");
1766 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00001767 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
1768 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekfb480492010-01-13 21:46:36 +00001769
Steve Naroff4ade6d62009-09-23 17:52:52 +00001770 SourceManager &SM = FD->getASTContext().getSourceManager();
1771 *startBuf = SM.getCharacterData(Body->getLBracLoc());
1772 *endBuf = SM.getCharacterData(Body->getRBracLoc());
1773 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
1774 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
1775 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
1776 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
1777}
Ted Kremenekfb480492010-01-13 21:46:36 +00001778
1779} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00001780
Ted Kremenekfb480492010-01-13 21:46:36 +00001781//===----------------------------------------------------------------------===//
1782// CXString Operations.
1783//===----------------------------------------------------------------------===//
1784
1785extern "C" {
1786const char *clang_getCString(CXString string) {
1787 return string.Spelling;
1788}
1789
1790void clang_disposeString(CXString string) {
1791 if (string.MustFreeString && string.Spelling)
1792 free((void*)string.Spelling);
1793}
1794} // end: extern "C"