blob: 6cd545f53f43e549ff47e73b749d6fc987ccc855 [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);
Steve Naroff89922f82009-08-31 00:59:03 +0000295};
Douglas Gregorb1373d02010-01-20 20:59:29 +0000296
Ted Kremenekab188932010-01-05 19:32:54 +0000297} // end anonymous namespace
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000298
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000299RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
300 assert(RegionOfInterest.isValid() && "RangeCompare called with invalid range");
301 if (R.isInvalid())
302 return RangeOverlap;
303
304 // Move the end of the input range to the end of the last token in that
305 // range.
306 R.setEnd(TU->getPreprocessor().getLocForEndOfToken(R.getEnd(), 1));
307 return RangeCompare(TU->getSourceManager(), R, RegionOfInterest);
308}
309
310RangeComparisonResult CursorVisitor::CompareRegionOfInterest(CXSourceRange CXR) {
311 return CompareRegionOfInterest(translateSourceRange(CXR));
312}
313
Douglas Gregorb1373d02010-01-20 20:59:29 +0000314/// \brief Visit the given cursor and, if requested by the visitor,
315/// its children.
316///
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000317/// \param Cursor the cursor to visit.
318///
319/// \param CheckRegionOfInterest if true, then the caller already checked that
320/// this cursor is within the region of interest.
321///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000322/// \returns true if the visitation should be aborted, false if it
323/// should continue.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000324bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
Douglas Gregorb1373d02010-01-20 20:59:29 +0000325 if (clang_isInvalid(Cursor.kind))
326 return false;
327
328 if (clang_isDeclaration(Cursor.kind)) {
329 Decl *D = getCursorDecl(Cursor);
330 assert(D && "Invalid declaration cursor");
331 if (D->getPCHLevel() > MaxPCHLevel)
332 return false;
333
334 if (D->isImplicit())
335 return false;
336 }
337
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000338 // If we have a range of interest, and this cursor doesn't intersect with it,
339 // we're done.
340 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
341 CXSourceRange Range = clang_getCursorExtent(Cursor);
342 if (translateSourceRange(Range).isInvalid() ||
343 CompareRegionOfInterest(Range))
344 return false;
345 }
346
Douglas Gregorb1373d02010-01-20 20:59:29 +0000347 switch (Visitor(Cursor, Parent, ClientData)) {
348 case CXChildVisit_Break:
349 return true;
350
351 case CXChildVisit_Continue:
352 return false;
353
354 case CXChildVisit_Recurse:
355 return VisitChildren(Cursor);
356 }
357
358 llvm_unreachable("Silly GCC, we can't get here");
359}
360
361/// \brief Visit the children of the given cursor.
362///
363/// \returns true if the visitation should be aborted, false if it
364/// should continue.
365bool CursorVisitor::VisitChildren(CXCursor Cursor) {
Douglas Gregora59e3902010-01-21 23:27:09 +0000366 if (clang_isReference(Cursor.kind)) {
367 // By definition, references have no children.
368 return false;
369 }
370
Douglas Gregorb1373d02010-01-20 20:59:29 +0000371 // Set the Parent field to Cursor, then back to its old value once we're
372 // done.
373 class SetParentRAII {
374 CXCursor &Parent;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000375 Decl *&StmtParent;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000376 CXCursor OldParent;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000377
Douglas Gregorb1373d02010-01-20 20:59:29 +0000378 public:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000379 SetParentRAII(CXCursor &Parent, Decl *&StmtParent, CXCursor NewParent)
380 : Parent(Parent), StmtParent(StmtParent), OldParent(Parent)
Douglas Gregorb1373d02010-01-20 20:59:29 +0000381 {
382 Parent = NewParent;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000383 if (clang_isDeclaration(Parent.kind))
384 StmtParent = getCursorDecl(Parent);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000385 }
386
387 ~SetParentRAII() {
388 Parent = OldParent;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000389 if (clang_isDeclaration(Parent.kind))
390 StmtParent = getCursorDecl(Parent);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000391 }
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000392 } SetParent(Parent, StmtParent, Cursor);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000393
394 if (clang_isDeclaration(Cursor.kind)) {
395 Decl *D = getCursorDecl(Cursor);
396 assert(D && "Invalid declaration cursor");
397 return Visit(D);
398 }
399
Douglas Gregora59e3902010-01-21 23:27:09 +0000400 if (clang_isStatement(Cursor.kind))
401 return Visit(getCursorStmt(Cursor));
402 if (clang_isExpression(Cursor.kind))
403 return Visit(getCursorExpr(Cursor));
404
Douglas Gregorb1373d02010-01-20 20:59:29 +0000405 if (clang_isTranslationUnit(Cursor.kind)) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000406 ASTUnit *CXXUnit = getCursorASTUnit(Cursor);
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000407 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
408 RegionOfInterest.isInvalid()) {
Douglas Gregor7b691f332010-01-20 21:13:59 +0000409 const std::vector<Decl*> &TLDs = CXXUnit->getTopLevelDecls();
410 for (std::vector<Decl*>::const_iterator it = TLDs.begin(),
411 ie = TLDs.end(); it != ie; ++it) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000412 if (Visit(MakeCXCursor(*it, CXXUnit), true))
Douglas Gregor7b691f332010-01-20 21:13:59 +0000413 return true;
414 }
415 } else {
416 return VisitDeclContext(
Douglas Gregorb1373d02010-01-20 20:59:29 +0000417 CXXUnit->getASTContext().getTranslationUnitDecl());
Douglas Gregor7b691f332010-01-20 21:13:59 +0000418 }
419
420 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000421 }
Douglas Gregora59e3902010-01-21 23:27:09 +0000422
Douglas Gregorb1373d02010-01-20 20:59:29 +0000423 // Nothing to visit at the moment.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000424 return false;
425}
426
Douglas Gregorb1373d02010-01-20 20:59:29 +0000427bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000428 for (DeclContext::decl_iterator
Douglas Gregorb1373d02010-01-20 20:59:29 +0000429 I = DC->decls_begin(), E = DC->decls_end(); I != E; ++I) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000430 if (RegionOfInterest.isValid()) {
431 SourceRange R = (*I)->getSourceRange();
432 if (R.isInvalid())
433 continue;
434
435 switch (CompareRegionOfInterest(R)) {
436 case RangeBefore:
437 // This declaration comes before the region of interest; skip it.
438 continue;
439
440 case RangeAfter:
441 // This declaration comes after the region of interest; we're done.
442 return false;
443
444 case RangeOverlap:
445 // This declaration overlaps the region of interest; visit it.
446 break;
447 }
448 }
449
450 if (Visit(MakeCXCursor(*I, TU), true))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000451 return true;
452 }
453
454 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000455}
456
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000457bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
458 llvm_unreachable("Translation units are visited directly by Visit()");
459 return false;
460}
461
462bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
463 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
464 return Visit(TSInfo->getTypeLoc());
465
466 return false;
467}
468
469bool CursorVisitor::VisitTagDecl(TagDecl *D) {
470 return VisitDeclContext(D);
471}
472
473bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
474 if (Expr *Init = D->getInitExpr())
475 return Visit(MakeCXCursor(Init, StmtParent, TU));
476 return false;
477}
478
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000479bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
480 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
481 if (Visit(TSInfo->getTypeLoc()))
482 return true;
483
484 return false;
485}
486
Douglas Gregorb1373d02010-01-20 20:59:29 +0000487bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000488 if (VisitDeclaratorDecl(ND))
489 return true;
490
Douglas Gregora59e3902010-01-21 23:27:09 +0000491 if (ND->isThisDeclarationADefinition() &&
492 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
493 return true;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000494
495 return false;
496}
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000497
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000498bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
499 if (VisitDeclaratorDecl(D))
500 return true;
501
502 if (Expr *BitWidth = D->getBitWidth())
503 return Visit(MakeCXCursor(BitWidth, StmtParent, TU));
504
505 return false;
506}
507
508bool CursorVisitor::VisitVarDecl(VarDecl *D) {
509 if (VisitDeclaratorDecl(D))
510 return true;
511
512 if (Expr *Init = D->getInit())
513 return Visit(MakeCXCursor(Init, StmtParent, TU));
514
515 return false;
516}
517
518bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
519 // FIXME: We really need a TypeLoc covering Objective-C method declarations.
520 // At the moment, we don't have information about locations in the return
521 // type.
522 for (ObjCMethodDecl::param_iterator P = ND->param_begin(),
523 PEnd = ND->param_end();
524 P != PEnd; ++P) {
525 if (Visit(MakeCXCursor(*P, TU)))
526 return true;
527 }
528
529 if (ND->isThisDeclarationADefinition() &&
530 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
531 return true;
532
533 return false;
534}
535
Douglas Gregora59e3902010-01-21 23:27:09 +0000536bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
537 return VisitDeclContext(D);
538}
539
Douglas Gregorb1373d02010-01-20 20:59:29 +0000540bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000541 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
542 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000543 return true;
544
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000545 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
546 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
547 E = ND->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000548 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000549 return true;
550
Douglas Gregora59e3902010-01-21 23:27:09 +0000551 return VisitObjCContainerDecl(ND);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000552}
553
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000554bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
555 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
556 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
557 E = PID->protocol_end(); I != E; ++I, ++PL)
558 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
559 return true;
560
561 return VisitObjCContainerDecl(PID);
562}
563
Douglas Gregorb1373d02010-01-20 20:59:29 +0000564bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000565 // Issue callbacks for super class.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000566 if (D->getSuperClass() &&
567 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000568 D->getSuperClassLoc(),
569 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000570 return true;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000571
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000572 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
573 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
574 E = D->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000575 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000576 return true;
577
Douglas Gregora59e3902010-01-21 23:27:09 +0000578 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000579}
580
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000581bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
582 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000583}
584
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000585bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
586 if (Visit(MakeCursorObjCClassRef(D->getCategoryDecl()->getClassInterface(),
587 D->getLocation(), TU)))
588 return true;
589
590 return VisitObjCImplDecl(D);
591}
592
593bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
594#if 0
595 // Issue callbacks for super class.
596 // FIXME: No source location information!
597 if (D->getSuperClass() &&
598 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
599 D->getSuperClassLoc(),
600 TU)))
601 return true;
602#endif
603
604 return VisitObjCImplDecl(D);
605}
606
607bool CursorVisitor::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D) {
608 ObjCForwardProtocolDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
609 for (ObjCForwardProtocolDecl::protocol_iterator I = D->protocol_begin(),
610 E = D->protocol_end();
611 I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000612 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000613 return true;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000614
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000615 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000616}
617
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000618bool CursorVisitor::VisitObjCClassDecl(ObjCClassDecl *D) {
619 for (ObjCClassDecl::iterator C = D->begin(), CEnd = D->end(); C != CEnd; ++C)
620 if (Visit(MakeCursorObjCClassRef(C->getInterface(), C->getLocation(), TU)))
621 return true;
622
623 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000624}
625
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000626bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
627 ASTContext &Context = TU->getASTContext();
628
629 // Some builtin types (such as Objective-C's "id", "sel", and
630 // "Class") have associated declarations. Create cursors for those.
631 QualType VisitType;
632 switch (TL.getType()->getAs<BuiltinType>()->getKind()) {
633 case BuiltinType::Void:
634 case BuiltinType::Bool:
635 case BuiltinType::Char_U:
636 case BuiltinType::UChar:
637 case BuiltinType::Char16:
638 case BuiltinType::Char32:
639 case BuiltinType::UShort:
640 case BuiltinType::UInt:
641 case BuiltinType::ULong:
642 case BuiltinType::ULongLong:
643 case BuiltinType::UInt128:
644 case BuiltinType::Char_S:
645 case BuiltinType::SChar:
646 case BuiltinType::WChar:
647 case BuiltinType::Short:
648 case BuiltinType::Int:
649 case BuiltinType::Long:
650 case BuiltinType::LongLong:
651 case BuiltinType::Int128:
652 case BuiltinType::Float:
653 case BuiltinType::Double:
654 case BuiltinType::LongDouble:
655 case BuiltinType::NullPtr:
656 case BuiltinType::Overload:
657 case BuiltinType::Dependent:
658 break;
659
660 case BuiltinType::UndeducedAuto: // FIXME: Deserves a cursor?
661 break;
662
663 case BuiltinType::ObjCId:
664 VisitType = Context.getObjCIdType();
665 break;
666
667 case BuiltinType::ObjCClass:
668 VisitType = Context.getObjCClassType();
669 break;
670
671 case BuiltinType::ObjCSel:
672 VisitType = Context.getObjCSelType();
673 break;
674 }
675
676 if (!VisitType.isNull()) {
677 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
678 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
679 TU));
680 }
681
682 return false;
683}
684
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000685bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
686 return Visit(MakeCursorTypeRef(TL.getTypedefDecl(), TL.getNameLoc(), TU));
687}
688
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000689bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
690 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
691}
692
693bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
694 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
695}
696
697bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
698 if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
699 return true;
700
701 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
702 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
703 TU)))
704 return true;
705 }
706
707 return false;
708}
709
710bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
711 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseTypeLoc()))
712 return true;
713
714 if (TL.hasProtocolsAsWritten()) {
715 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
716 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I),
717 TL.getProtocolLoc(I),
718 TU)))
719 return true;
720 }
721 }
722
723 return false;
724}
725
726bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
727 return Visit(TL.getPointeeLoc());
728}
729
730bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
731 return Visit(TL.getPointeeLoc());
732}
733
734bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
735 return Visit(TL.getPointeeLoc());
736}
737
738bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
739 return Visit(TL.getPointeeLoc());
740}
741
742bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
743 return Visit(TL.getPointeeLoc());
744}
745
746bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
747 if (Visit(TL.getResultLoc()))
748 return true;
749
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000750 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
751 if (Visit(MakeCXCursor(TL.getArg(I), TU)))
752 return true;
753
754 return false;
755}
756
757bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
758 if (Visit(TL.getElementLoc()))
759 return true;
760
761 if (Expr *Size = TL.getSizeExpr())
762 return Visit(MakeCXCursor(Size, StmtParent, TU));
763
764 return false;
765}
766
Douglas Gregor2332c112010-01-21 20:48:56 +0000767bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
768 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
769}
770
771bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
772 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
773 return Visit(TSInfo->getTypeLoc());
774
775 return false;
776}
777
Douglas Gregora59e3902010-01-21 23:27:09 +0000778bool CursorVisitor::VisitStmt(Stmt *S) {
779 for (Stmt::child_iterator Child = S->child_begin(), ChildEnd = S->child_end();
780 Child != ChildEnd; ++Child) {
781 if (Visit(MakeCXCursor(*Child, StmtParent, TU)))
782 return true;
783 }
784
785 return false;
786}
787
788bool CursorVisitor::VisitDeclStmt(DeclStmt *S) {
789 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
790 D != DEnd; ++D) {
791 if (Visit(MakeCXCursor(*D, TU)))
792 return true;
793 }
794
795 return false;
796}
797
Douglas Gregorf5bab412010-01-22 01:00:11 +0000798bool CursorVisitor::VisitIfStmt(IfStmt *S) {
799 if (VarDecl *Var = S->getConditionVariable()) {
800 if (Visit(MakeCXCursor(Var, TU)))
801 return true;
802 } else if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
803 return true;
804
805 if (S->getThen() && Visit(MakeCXCursor(S->getThen(), StmtParent, TU)))
806 return true;
807
808 if (S->getElse() && Visit(MakeCXCursor(S->getElse(), StmtParent, TU)))
809 return true;
810
811 return false;
812}
813
814bool CursorVisitor::VisitSwitchStmt(SwitchStmt *S) {
815 if (VarDecl *Var = S->getConditionVariable()) {
816 if (Visit(MakeCXCursor(Var, TU)))
817 return true;
818 } else if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
819 return true;
820
821 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
822 return true;
823
824 return false;
825}
826
Daniel Dunbar140fce22010-01-12 02:34:07 +0000827CXString CIndexer::createCXString(const char *String, bool DupString){
Benjamin Kramer62cf3222009-11-09 19:13:48 +0000828 CXString Str;
829 if (DupString) {
830 Str.Spelling = strdup(String);
831 Str.MustFreeString = 1;
832 } else {
833 Str.Spelling = String;
834 Str.MustFreeString = 0;
835 }
836 return Str;
837}
838
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000839extern "C" {
Steve Naroffe56b4ba2009-10-20 14:46:24 +0000840CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000841 int displayDiagnostics) {
Douglas Gregora030b7c2010-01-22 20:35:53 +0000842 CIndexer *CIdxr = new CIndexer();
Steve Naroffe56b4ba2009-10-20 14:46:24 +0000843 if (excludeDeclarationsFromPCH)
844 CIdxr->setOnlyLocalDecls();
845 if (displayDiagnostics)
846 CIdxr->setDisplayDiagnostics();
847 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +0000848}
849
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000850void clang_disposeIndex(CXIndex CIdx) {
Steve Naroff2bd6b9f2009-09-17 18:33:27 +0000851 assert(CIdx && "Passed null CXIndex");
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000852 delete static_cast<CIndexer *>(CIdx);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +0000853}
854
Daniel Dunbar8506dde2009-12-03 01:54:28 +0000855void clang_setUseExternalASTGeneration(CXIndex CIdx, int value) {
856 assert(CIdx && "Passed null CXIndex");
857 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
858 CXXIdx->setUseExternalASTGeneration(value);
859}
860
Steve Naroff50398192009-08-28 15:28:48 +0000861// FIXME: need to pass back error info.
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000862CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
863 const char *ast_filename) {
Steve Naroff50398192009-08-28 15:28:48 +0000864 assert(CIdx && "Passed null CXIndex");
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000865 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000866
Daniel Dunbar5262fda2009-12-03 01:45:44 +0000867 return ASTUnit::LoadFromPCHFile(ast_filename, CXXIdx->getDiags(),
868 CXXIdx->getOnlyLocalDecls(),
869 /* UseBumpAllocator = */ true);
Steve Naroff600866c2009-08-27 19:51:58 +0000870}
871
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000872CXTranslationUnit
873clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
874 const char *source_filename,
875 int num_command_line_args,
Douglas Gregor4db64a42010-01-23 00:14:00 +0000876 const char **command_line_args,
877 unsigned num_unsaved_files,
878 struct CXUnsavedFile *unsaved_files) {
Steve Naroffe56b4ba2009-10-20 14:46:24 +0000879 assert(CIdx && "Passed null CXIndex");
880 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
881
Douglas Gregor4db64a42010-01-23 00:14:00 +0000882 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
883 for (unsigned I = 0; I != num_unsaved_files; ++I) {
884 const llvm::MemoryBuffer *Buffer
885 = llvm::MemoryBuffer::getMemBuffer(unsaved_files[I].Contents,
886 unsaved_files[I].Contents + unsaved_files[I].Length,
887 unsaved_files[I].Filename);
888 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
889 Buffer));
890 }
891
Daniel Dunbar8506dde2009-12-03 01:54:28 +0000892 if (!CXXIdx->getUseExternalASTGeneration()) {
893 llvm::SmallVector<const char *, 16> Args;
894
895 // The 'source_filename' argument is optional. If the caller does not
896 // specify it then it is assumed that the source file is specified
897 // in the actual argument list.
898 if (source_filename)
899 Args.push_back(source_filename);
900 Args.insert(Args.end(), command_line_args,
901 command_line_args + num_command_line_args);
902
Daniel Dunbar94220972009-12-05 02:17:18 +0000903 unsigned NumErrors = CXXIdx->getDiags().getNumErrors();
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000904
Ted Kremenek29b72842010-01-07 22:49:05 +0000905#ifdef USE_CRASHTRACER
906 ArgsCrashTracerInfo ACTI(Args);
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000907#endif
908
Daniel Dunbar94220972009-12-05 02:17:18 +0000909 llvm::OwningPtr<ASTUnit> Unit(
910 ASTUnit::LoadFromCommandLine(Args.data(), Args.data() + Args.size(),
Daniel Dunbar869824e2009-12-13 03:46:13 +0000911 CXXIdx->getDiags(),
912 CXXIdx->getClangResourcesPath(),
Daniel Dunbar94220972009-12-05 02:17:18 +0000913 CXXIdx->getOnlyLocalDecls(),
Douglas Gregor4db64a42010-01-23 00:14:00 +0000914 /* UseBumpAllocator = */ true,
915 RemappedFiles.data(),
916 RemappedFiles.size()));
Ted Kremenek29b72842010-01-07 22:49:05 +0000917
Daniel Dunbar94220972009-12-05 02:17:18 +0000918 // FIXME: Until we have broader testing, just drop the entire AST if we
919 // encountered an error.
920 if (NumErrors != CXXIdx->getDiags().getNumErrors())
921 return 0;
922
923 return Unit.take();
Daniel Dunbar8506dde2009-12-03 01:54:28 +0000924 }
925
Ted Kremenek139ba862009-10-22 00:03:57 +0000926 // Build up the arguments for invoking 'clang'.
Ted Kremenek74cd0692009-10-15 23:21:22 +0000927 std::vector<const char *> argv;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000928
Ted Kremenek139ba862009-10-22 00:03:57 +0000929 // First add the complete path to the 'clang' executable.
930 llvm::sys::Path ClangPath = static_cast<CIndexer *>(CIdx)->getClangPath();
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000931 argv.push_back(ClangPath.c_str());
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000932
Ted Kremenek139ba862009-10-22 00:03:57 +0000933 // Add the '-emit-ast' option as our execution mode for 'clang'.
Ted Kremenek74cd0692009-10-15 23:21:22 +0000934 argv.push_back("-emit-ast");
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000935
Ted Kremenek139ba862009-10-22 00:03:57 +0000936 // The 'source_filename' argument is optional. If the caller does not
937 // specify it then it is assumed that the source file is specified
938 // in the actual argument list.
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000939 if (source_filename)
940 argv.push_back(source_filename);
Ted Kremenek139ba862009-10-22 00:03:57 +0000941
Steve Naroff37b5ac22009-10-15 20:50:09 +0000942 // Generate a temporary name for the AST file.
Ted Kremenek139ba862009-10-22 00:03:57 +0000943 argv.push_back("-o");
Steve Naroff37b5ac22009-10-15 20:50:09 +0000944 char astTmpFile[L_tmpnam];
Ted Kremenek74cd0692009-10-15 23:21:22 +0000945 argv.push_back(tmpnam(astTmpFile));
Ted Kremenek139ba862009-10-22 00:03:57 +0000946
Douglas Gregor4db64a42010-01-23 00:14:00 +0000947 // Remap any unsaved files to temporary files.
948 std::vector<llvm::sys::Path> TemporaryFiles;
949 std::vector<std::string> RemapArgs;
950 if (RemapFiles(num_unsaved_files, unsaved_files, RemapArgs, TemporaryFiles))
951 return 0;
952
953 // The pointers into the elements of RemapArgs are stable because we
954 // won't be adding anything to RemapArgs after this point.
955 for (unsigned i = 0, e = RemapArgs.size(); i != e; ++i)
956 argv.push_back(RemapArgs[i].c_str());
957
Ted Kremenek139ba862009-10-22 00:03:57 +0000958 // Process the compiler options, stripping off '-o', '-c', '-fsyntax-only'.
959 for (int i = 0; i < num_command_line_args; ++i)
960 if (const char *arg = command_line_args[i]) {
961 if (strcmp(arg, "-o") == 0) {
962 ++i; // Also skip the matching argument.
963 continue;
964 }
965 if (strcmp(arg, "-emit-ast") == 0 ||
966 strcmp(arg, "-c") == 0 ||
967 strcmp(arg, "-fsyntax-only") == 0) {
968 continue;
969 }
970
971 // Keep the argument.
972 argv.push_back(arg);
Steve Naroffe56b4ba2009-10-20 14:46:24 +0000973 }
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000974
Ted Kremenek139ba862009-10-22 00:03:57 +0000975 // Add the null terminator.
Ted Kremenek74cd0692009-10-15 23:21:22 +0000976 argv.push_back(NULL);
977
Ted Kremenekfeb15e32009-10-26 22:14:08 +0000978 // Invoke 'clang'.
979 llvm::sys::Path DevNull; // leave empty, causes redirection to /dev/null
980 // on Unix or NUL (Windows).
Ted Kremenek379afec2009-10-22 03:24:01 +0000981 std::string ErrMsg;
Ted Kremenekc46e4632009-10-19 22:27:32 +0000982 const llvm::sys::Path *Redirects[] = { &DevNull, &DevNull, &DevNull, NULL };
Ted Kremenek379afec2009-10-22 03:24:01 +0000983 llvm::sys::Program::ExecuteAndWait(ClangPath, &argv[0], /* env */ NULL,
984 /* redirects */ !CXXIdx->getDisplayDiagnostics() ? &Redirects[0] : NULL,
985 /* secondsToWait */ 0, /* memoryLimits */ 0, &ErrMsg);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000986
Ted Kremenek0854d702009-11-10 19:18:52 +0000987 if (CXXIdx->getDisplayDiagnostics() && !ErrMsg.empty()) {
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000988 llvm::errs() << "clang_createTranslationUnitFromSourceFile: " << ErrMsg
Daniel Dunbaracca7252009-11-30 20:42:49 +0000989 << '\n' << "Arguments: \n";
Ted Kremenek379afec2009-10-22 03:24:01 +0000990 for (std::vector<const char*>::iterator I = argv.begin(), E = argv.end();
Ted Kremenek779e5f42009-10-26 22:08:39 +0000991 I!=E; ++I) {
992 if (*I)
993 llvm::errs() << ' ' << *I << '\n';
994 }
995 llvm::errs() << '\n';
Ted Kremenek379afec2009-10-22 03:24:01 +0000996 }
Benjamin Kramer0829a832009-10-18 11:19:36 +0000997
Douglas Gregor4db64a42010-01-23 00:14:00 +0000998 ASTUnit *ATU = ASTUnit::LoadFromPCHFile(astTmpFile, CXXIdx->getDiags(),
999 CXXIdx->getOnlyLocalDecls(),
1000 /* UseBumpAllocator = */ true,
1001 RemappedFiles.data(),
1002 RemappedFiles.size());
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001003 if (ATU)
1004 ATU->unlinkTemporaryFile();
Douglas Gregor4db64a42010-01-23 00:14:00 +00001005
1006 for (unsigned i = 0, e = TemporaryFiles.size(); i != e; ++i)
1007 TemporaryFiles[i].eraseFromDisk();
1008
Steve Naroffe19944c2009-10-15 22:23:48 +00001009 return ATU;
Steve Naroff5b7d8e22009-10-15 20:04:39 +00001010}
1011
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001012void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00001013 assert(CTUnit && "Passed null CXTranslationUnit");
1014 delete static_cast<ASTUnit *>(CTUnit);
1015}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001016
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001017CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Steve Naroffaf08ddc2009-09-03 15:49:00 +00001018 assert(CTUnit && "Passed null CXTranslationUnit");
Steve Naroff77accc12009-09-03 18:19:54 +00001019 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit);
Ted Kremenek4b333d22010-01-12 00:36:38 +00001020 return CIndexer::createCXString(CXXUnit->getOriginalSourceFileName().c_str(),
1021 true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +00001022}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +00001023
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001024CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001025 CXCursor Result = { CXCursor_TranslationUnit, { 0, 0, TU } };
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001026 return Result;
1027}
1028
Ted Kremenekfb480492010-01-13 21:46:36 +00001029} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +00001030
Ted Kremenekfb480492010-01-13 21:46:36 +00001031//===----------------------------------------------------------------------===//
Douglas Gregor1db19de2010-01-19 21:36:55 +00001032// CXSourceLocation and CXSourceRange Operations.
1033//===----------------------------------------------------------------------===//
1034
Douglas Gregorb9790342010-01-22 21:44:22 +00001035extern "C" {
1036CXSourceLocation clang_getNullLocation() {
1037 CXSourceLocation Result = { 0, 0 };
1038 return Result;
1039}
1040
1041unsigned clang_equalLocations(CXSourceLocation loc1, CXSourceLocation loc2) {
1042 return loc1.ptr_data == loc2.ptr_data && loc1.int_data == loc2.int_data;
1043}
1044
1045CXSourceLocation clang_getLocation(CXTranslationUnit tu,
1046 CXFile file,
1047 unsigned line,
1048 unsigned column) {
1049 if (!tu)
1050 return clang_getNullLocation();
1051
1052 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
1053 SourceLocation SLoc
1054 = CXXUnit->getSourceManager().getLocation(
1055 static_cast<const FileEntry *>(file),
1056 line, column);
1057
1058 return translateSourceLocation(CXXUnit->getASTContext(), SLoc, false);
1059}
1060
1061CXSourceRange clang_getRange(CXSourceLocation begin, CXSourceLocation end) {
1062 if (begin.ptr_data != end.ptr_data) {
1063 CXSourceRange Result = { 0, 0, 0 };
1064 return Result;
1065 }
1066
1067 CXSourceRange Result = { begin.ptr_data, begin.int_data, end.int_data };
1068 return Result;
1069}
1070
Douglas Gregor1db19de2010-01-19 21:36:55 +00001071void clang_getInstantiationLocation(CXSourceLocation location,
1072 CXFile *file,
1073 unsigned *line,
1074 unsigned *column) {
1075 CXSourceLocationPtr Ptr
1076 = CXSourceLocationPtr::getFromOpaqueValue(location.ptr_data);
1077 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
1078
1079 if (!Ptr.getPointer() || Loc.isInvalid()) {
1080 if (file)
1081 *file = 0;
1082 if (line)
1083 *line = 0;
1084 if (column)
1085 *column = 0;
1086 return;
1087 }
1088
1089 // FIXME: This is largely copy-paste from
1090 ///TextDiagnosticPrinter::HighlightRange. When it is clear that this is
1091 // what we want the two routines should be refactored.
1092 ASTContext &Context = *Ptr.getPointer();
1093 SourceManager &SM = Context.getSourceManager();
1094 SourceLocation InstLoc = SM.getInstantiationLoc(Loc);
1095
1096 if (Ptr.getInt()) {
1097 // We want the last character in this location, so we will adjust
1098 // the instantiation location accordingly.
1099
1100 // If the location is from a macro instantiation, get the end of
1101 // the instantiation range.
1102 if (Loc.isMacroID())
1103 InstLoc = SM.getInstantiationRange(Loc).second;
1104
1105 // Measure the length token we're pointing at, so we can adjust
1106 // the physical location in the file to point at the last
1107 // character.
1108 // FIXME: This won't cope with trigraphs or escaped newlines
1109 // well. For that, we actually need a preprocessor, which isn't
1110 // currently available here. Eventually, we'll switch the pointer
1111 // data of CXSourceLocation/CXSourceRange to a translation unit
1112 // (CXXUnit), so that the preprocessor will be available here. At
1113 // that point, we can use Preprocessor::getLocForEndOfToken().
1114 unsigned Length = Lexer::MeasureTokenLength(InstLoc, SM,
1115 Context.getLangOptions());
1116 if (Length > 0)
1117 InstLoc = InstLoc.getFileLocWithOffset(Length - 1);
1118 }
1119
1120 if (file)
1121 *file = (void *)SM.getFileEntryForID(SM.getFileID(InstLoc));
1122 if (line)
1123 *line = SM.getInstantiationLineNumber(InstLoc);
1124 if (column)
1125 *column = SM.getInstantiationColumnNumber(InstLoc);
1126}
1127
1128CXSourceLocation clang_getRangeStart(CXSourceRange range) {
1129 CXSourceLocation Result = { range.ptr_data, range.begin_int_data };
1130 return Result;
1131}
1132
1133CXSourceLocation clang_getRangeEnd(CXSourceRange range) {
1134 llvm::PointerIntPair<ASTContext *, 1, bool> Ptr;
1135 Ptr.setPointer(static_cast<ASTContext *>(range.ptr_data));
1136 Ptr.setInt(true);
1137 CXSourceLocation Result = { Ptr.getOpaqueValue(), range.end_int_data };
1138 return Result;
1139}
1140
Douglas Gregorb9790342010-01-22 21:44:22 +00001141} // end: extern "C"
1142
Douglas Gregor1db19de2010-01-19 21:36:55 +00001143//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00001144// CXFile Operations.
1145//===----------------------------------------------------------------------===//
1146
1147extern "C" {
Steve Naroff88145032009-10-27 14:35:18 +00001148const char *clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00001149 if (!SFile)
1150 return 0;
1151
Steve Naroff88145032009-10-27 14:35:18 +00001152 assert(SFile && "Passed null CXFile");
1153 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
1154 return FEnt->getName();
1155}
1156
1157time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00001158 if (!SFile)
1159 return 0;
1160
Steve Naroff88145032009-10-27 14:35:18 +00001161 assert(SFile && "Passed null CXFile");
1162 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
1163 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +00001164}
Douglas Gregorb9790342010-01-22 21:44:22 +00001165
1166CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
1167 if (!tu)
1168 return 0;
1169
1170 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
1171
1172 FileManager &FMgr = CXXUnit->getFileManager();
1173 const FileEntry *File = FMgr.getFile(file_name, file_name+strlen(file_name));
1174 return const_cast<FileEntry *>(File);
1175}
1176
Ted Kremenekfb480492010-01-13 21:46:36 +00001177} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +00001178
Ted Kremenekfb480492010-01-13 21:46:36 +00001179//===----------------------------------------------------------------------===//
1180// CXCursor Operations.
1181//===----------------------------------------------------------------------===//
1182
Ted Kremenekfb480492010-01-13 21:46:36 +00001183static Decl *getDeclFromExpr(Stmt *E) {
1184 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
1185 return RefExpr->getDecl();
1186 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
1187 return ME->getMemberDecl();
1188 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
1189 return RE->getDecl();
1190
1191 if (CallExpr *CE = dyn_cast<CallExpr>(E))
1192 return getDeclFromExpr(CE->getCallee());
1193 if (CastExpr *CE = dyn_cast<CastExpr>(E))
1194 return getDeclFromExpr(CE->getSubExpr());
1195 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
1196 return OME->getMethodDecl();
1197
1198 return 0;
1199}
1200
1201extern "C" {
Douglas Gregorb1373d02010-01-20 20:59:29 +00001202
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001203unsigned clang_visitChildren(CXCursor parent,
Douglas Gregorb1373d02010-01-20 20:59:29 +00001204 CXCursorVisitor visitor,
1205 CXClientData client_data) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001206 ASTUnit *CXXUnit = getCursorASTUnit(parent);
Douglas Gregorb1373d02010-01-20 20:59:29 +00001207
1208 unsigned PCHLevel = Decl::MaxPCHLevel;
1209
1210 // Set the PCHLevel to filter out unwanted decls if requested.
1211 if (CXXUnit->getOnlyLocalDecls()) {
1212 PCHLevel = 0;
1213
1214 // If the main input was an AST, bump the level.
1215 if (CXXUnit->isMainFileAST())
1216 ++PCHLevel;
1217 }
1218
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001219 CursorVisitor CursorVis(CXXUnit, visitor, client_data, PCHLevel);
Douglas Gregorb1373d02010-01-20 20:59:29 +00001220 return CursorVis.VisitChildren(parent);
1221}
1222
Douglas Gregor78205d42010-01-20 21:45:58 +00001223static CXString getDeclSpelling(Decl *D) {
1224 NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
1225 if (!ND)
1226 return CIndexer::createCXString("");
1227
1228 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
1229 return CIndexer::createCXString(OMD->getSelector().getAsString().c_str(),
1230 true);
1231
1232 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
1233 // No, this isn't the same as the code below. getIdentifier() is non-virtual
1234 // and returns different names. NamedDecl returns the class name and
1235 // ObjCCategoryImplDecl returns the category name.
1236 return CIndexer::createCXString(CIMP->getIdentifier()->getNameStart());
1237
1238 if (ND->getIdentifier())
1239 return CIndexer::createCXString(ND->getIdentifier()->getNameStart());
1240
1241 return CIndexer::createCXString("");
1242}
1243
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001244CXString clang_getCursorSpelling(CXCursor C) {
Daniel Dunbarc81d7182010-01-18 17:52:42 +00001245 assert(getCursorDecl(C) && "CXCursor has null decl");
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001246 if (clang_isTranslationUnit(C.kind))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001247 return clang_getTranslationUnitSpelling(C.data[2]);
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001248
Steve Narofff334b4e2009-09-02 18:26:48 +00001249 if (clang_isReference(C.kind)) {
1250 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00001251 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +00001252 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
1253 return CIndexer::createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00001254 }
1255 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +00001256 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
1257 return CIndexer::createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00001258 }
1259 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +00001260 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +00001261 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenek4b333d22010-01-12 00:36:38 +00001262 return CIndexer::createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00001263 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001264 case CXCursor_TypeRef: {
1265 TypeDecl *Type = getCursorTypeRef(C).first;
1266 assert(Type && "Missing type decl");
1267
1268 return CIndexer::createCXString(
1269 getCursorContext(C).getTypeDeclType(Type).getAsString().c_str(),
1270 true);
1271 }
1272
Daniel Dunbaracca7252009-11-30 20:42:49 +00001273 default:
Ted Kremenek4b333d22010-01-12 00:36:38 +00001274 return CIndexer::createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +00001275 }
1276 }
Douglas Gregor97b98722010-01-19 23:20:36 +00001277
1278 if (clang_isExpression(C.kind)) {
1279 Decl *D = getDeclFromExpr(getCursorExpr(C));
1280 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +00001281 return getDeclSpelling(D);
Douglas Gregor97b98722010-01-19 23:20:36 +00001282 return CIndexer::createCXString("");
1283 }
1284
Douglas Gregor78205d42010-01-20 21:45:58 +00001285 return getDeclSpelling(getCursorDecl(C));
Steve Narofff334b4e2009-09-02 18:26:48 +00001286}
1287
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001288const char *clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00001289 switch (Kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00001290 case CXCursor_FunctionDecl: return "FunctionDecl";
1291 case CXCursor_TypedefDecl: return "TypedefDecl";
1292 case CXCursor_EnumDecl: return "EnumDecl";
1293 case CXCursor_EnumConstantDecl: return "EnumConstantDecl";
1294 case CXCursor_StructDecl: return "StructDecl";
1295 case CXCursor_UnionDecl: return "UnionDecl";
1296 case CXCursor_ClassDecl: return "ClassDecl";
1297 case CXCursor_FieldDecl: return "FieldDecl";
1298 case CXCursor_VarDecl: return "VarDecl";
1299 case CXCursor_ParmDecl: return "ParmDecl";
1300 case CXCursor_ObjCInterfaceDecl: return "ObjCInterfaceDecl";
1301 case CXCursor_ObjCCategoryDecl: return "ObjCCategoryDecl";
1302 case CXCursor_ObjCProtocolDecl: return "ObjCProtocolDecl";
1303 case CXCursor_ObjCPropertyDecl: return "ObjCPropertyDecl";
1304 case CXCursor_ObjCIvarDecl: return "ObjCIvarDecl";
1305 case CXCursor_ObjCInstanceMethodDecl: return "ObjCInstanceMethodDecl";
1306 case CXCursor_ObjCClassMethodDecl: return "ObjCClassMethodDecl";
Douglas Gregorb6998662010-01-19 19:34:47 +00001307 case CXCursor_ObjCImplementationDecl: return "ObjCImplementationDecl";
1308 case CXCursor_ObjCCategoryImplDecl: return "ObjCCategoryImplDecl";
Douglas Gregor30122132010-01-19 22:07:56 +00001309 case CXCursor_UnexposedDecl: return "UnexposedDecl";
Daniel Dunbaracca7252009-11-30 20:42:49 +00001310 case CXCursor_ObjCSuperClassRef: return "ObjCSuperClassRef";
1311 case CXCursor_ObjCProtocolRef: return "ObjCProtocolRef";
1312 case CXCursor_ObjCClassRef: return "ObjCClassRef";
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001313 case CXCursor_TypeRef: return "TypeRef";
Douglas Gregor97b98722010-01-19 23:20:36 +00001314 case CXCursor_UnexposedExpr: return "UnexposedExpr";
1315 case CXCursor_DeclRefExpr: return "DeclRefExpr";
1316 case CXCursor_MemberRefExpr: return "MemberRefExpr";
1317 case CXCursor_CallExpr: return "CallExpr";
1318 case CXCursor_ObjCMessageExpr: return "ObjCMessageExpr";
1319 case CXCursor_UnexposedStmt: return "UnexposedStmt";
Daniel Dunbaracca7252009-11-30 20:42:49 +00001320 case CXCursor_InvalidFile: return "InvalidFile";
1321 case CXCursor_NoDeclFound: return "NoDeclFound";
1322 case CXCursor_NotImplemented: return "NotImplemented";
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001323 case CXCursor_TranslationUnit: return "TranslationUnit";
Steve Naroff89922f82009-08-31 00:59:03 +00001324 }
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00001325
1326 llvm_unreachable("Unhandled CXCursorKind");
1327 return NULL;
Steve Naroff600866c2009-08-27 19:51:58 +00001328}
Steve Naroff89922f82009-08-31 00:59:03 +00001329
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001330enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
1331 CXCursor parent,
1332 CXClientData client_data) {
1333 CXCursor *BestCursor = static_cast<CXCursor *>(client_data);
1334 *BestCursor = cursor;
1335 return CXChildVisit_Recurse;
1336}
1337
Douglas Gregorb9790342010-01-22 21:44:22 +00001338CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
1339 if (!TU)
Ted Kremenekf4629892010-01-14 01:51:23 +00001340 return clang_getNullCursor();
Ted Kremenekf4629892010-01-14 01:51:23 +00001341
Douglas Gregorb9790342010-01-22 21:44:22 +00001342 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
1343
1344 SourceLocation SLoc = translateSourceLocation(Loc);
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001345 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
1346 if (SLoc.isValid()) {
1347 SourceRange RegionOfInterest(SLoc,
1348 CXXUnit->getPreprocessor().getLocForEndOfToken(SLoc, 1));
1349
1350 // FIXME: Would be great to have a "hint" cursor, then walk from that
1351 // hint cursor upward until we find a cursor whose source range encloses
1352 // the region of interest, rather than starting from the translation unit.
1353 CXCursor Parent = clang_getTranslationUnitCursor(CXXUnit);
1354 CursorVisitor CursorVis(CXXUnit, GetCursorVisitor, &Result,
1355 Decl::MaxPCHLevel, RegionOfInterest);
1356 CursorVis.VisitChildren(Parent);
Steve Naroff77128dd2009-09-15 20:25:34 +00001357 }
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001358 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00001359}
1360
Ted Kremenek73885552009-11-17 19:28:59 +00001361CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00001362 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00001363}
1364
1365unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00001366 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00001367}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001368
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001369unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00001370 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
1371}
1372
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001373unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +00001374 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
1375}
Steve Naroff2d4d6292009-08-31 14:26:51 +00001376
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001377unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00001378 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
1379}
1380
Douglas Gregor97b98722010-01-19 23:20:36 +00001381unsigned clang_isExpression(enum CXCursorKind K) {
1382 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
1383}
1384
1385unsigned clang_isStatement(enum CXCursorKind K) {
1386 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
1387}
1388
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001389unsigned clang_isTranslationUnit(enum CXCursorKind K) {
1390 return K == CXCursor_TranslationUnit;
1391}
1392
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001393CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00001394 return C.kind;
1395}
1396
Douglas Gregor97b98722010-01-19 23:20:36 +00001397static SourceLocation getLocationFromExpr(Expr *E) {
1398 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
1399 return /*FIXME:*/Msg->getLeftLoc();
1400 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
1401 return DRE->getLocation();
1402 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
1403 return Member->getMemberLoc();
1404 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
1405 return Ivar->getLocation();
1406 return E->getLocStart();
1407}
1408
Douglas Gregor98258af2010-01-18 22:46:11 +00001409CXSourceLocation clang_getCursorLocation(CXCursor C) {
1410 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00001411 switch (C.kind) {
1412 case CXCursor_ObjCSuperClassRef: {
1413 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1414 = getCursorObjCSuperClassRef(C);
Douglas Gregor1db19de2010-01-19 21:36:55 +00001415 return translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001416 }
1417
1418 case CXCursor_ObjCProtocolRef: {
1419 std::pair<ObjCProtocolDecl *, SourceLocation> P
1420 = getCursorObjCProtocolRef(C);
Douglas Gregor1db19de2010-01-19 21:36:55 +00001421 return translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001422 }
1423
1424 case CXCursor_ObjCClassRef: {
1425 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1426 = getCursorObjCClassRef(C);
Douglas Gregor1db19de2010-01-19 21:36:55 +00001427 return translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001428 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001429
1430 case CXCursor_TypeRef: {
1431 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
1432 return translateSourceLocation(P.first->getASTContext(), P.second);
1433 }
Douglas Gregorf46034a2010-01-18 23:41:10 +00001434
Douglas Gregorf46034a2010-01-18 23:41:10 +00001435 default:
1436 // FIXME: Need a way to enumerate all non-reference cases.
1437 llvm_unreachable("Missed a reference kind");
1438 }
Douglas Gregor98258af2010-01-18 22:46:11 +00001439 }
Douglas Gregor97b98722010-01-19 23:20:36 +00001440
1441 if (clang_isExpression(C.kind))
1442 return translateSourceLocation(getCursorContext(C),
1443 getLocationFromExpr(getCursorExpr(C)));
1444
Douglas Gregor98258af2010-01-18 22:46:11 +00001445 if (!getCursorDecl(C)) {
Douglas Gregor1db19de2010-01-19 21:36:55 +00001446 CXSourceLocation empty = { 0, 0 };
Douglas Gregor98258af2010-01-18 22:46:11 +00001447 return empty;
1448 }
1449
Douglas Gregorf46034a2010-01-18 23:41:10 +00001450 Decl *D = getCursorDecl(C);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001451 SourceLocation Loc = D->getLocation();
1452 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
1453 Loc = Class->getClassLoc();
Douglas Gregor1db19de2010-01-19 21:36:55 +00001454 return translateSourceLocation(D->getASTContext(), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00001455}
Douglas Gregora7bde202010-01-19 00:34:46 +00001456
1457CXSourceRange clang_getCursorExtent(CXCursor C) {
1458 if (clang_isReference(C.kind)) {
1459 switch (C.kind) {
1460 case CXCursor_ObjCSuperClassRef: {
1461 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1462 = getCursorObjCSuperClassRef(C);
1463 return translateSourceRange(P.first->getASTContext(), P.second);
1464 }
1465
1466 case CXCursor_ObjCProtocolRef: {
1467 std::pair<ObjCProtocolDecl *, SourceLocation> P
1468 = getCursorObjCProtocolRef(C);
1469 return translateSourceRange(P.first->getASTContext(), P.second);
1470 }
1471
1472 case CXCursor_ObjCClassRef: {
1473 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1474 = getCursorObjCClassRef(C);
1475
1476 return translateSourceRange(P.first->getASTContext(), P.second);
1477 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001478
1479 case CXCursor_TypeRef: {
1480 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
1481 return translateSourceRange(P.first->getASTContext(), P.second);
1482 }
Douglas Gregora7bde202010-01-19 00:34:46 +00001483
Douglas Gregora7bde202010-01-19 00:34:46 +00001484 default:
1485 // FIXME: Need a way to enumerate all non-reference cases.
1486 llvm_unreachable("Missed a reference kind");
1487 }
1488 }
Douglas Gregor97b98722010-01-19 23:20:36 +00001489
1490 if (clang_isExpression(C.kind))
1491 return translateSourceRange(getCursorContext(C),
1492 getCursorExpr(C)->getSourceRange());
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001493
1494 if (clang_isStatement(C.kind))
1495 return translateSourceRange(getCursorContext(C),
1496 getCursorStmt(C)->getSourceRange());
Douglas Gregora7bde202010-01-19 00:34:46 +00001497
1498 if (!getCursorDecl(C)) {
Douglas Gregor1db19de2010-01-19 21:36:55 +00001499 CXSourceRange empty = { 0, 0, 0 };
Douglas Gregora7bde202010-01-19 00:34:46 +00001500 return empty;
1501 }
1502
1503 Decl *D = getCursorDecl(C);
1504 return translateSourceRange(D->getASTContext(), D->getSourceRange());
1505}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001506
1507CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001508 if (clang_isInvalid(C.kind))
1509 return clang_getNullCursor();
1510
1511 ASTUnit *CXXUnit = getCursorASTUnit(C);
Douglas Gregorb6998662010-01-19 19:34:47 +00001512 if (clang_isDeclaration(C.kind))
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001513 return C;
Douglas Gregor98258af2010-01-18 22:46:11 +00001514
Douglas Gregor97b98722010-01-19 23:20:36 +00001515 if (clang_isExpression(C.kind)) {
1516 Decl *D = getDeclFromExpr(getCursorExpr(C));
1517 if (D)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001518 return MakeCXCursor(D, CXXUnit);
Douglas Gregor97b98722010-01-19 23:20:36 +00001519 return clang_getNullCursor();
1520 }
1521
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001522 if (!clang_isReference(C.kind))
1523 return clang_getNullCursor();
1524
1525 switch (C.kind) {
1526 case CXCursor_ObjCSuperClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001527 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, CXXUnit);
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001528
1529 case CXCursor_ObjCProtocolRef: {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001530 return MakeCXCursor(getCursorObjCProtocolRef(C).first, CXXUnit);
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001531
1532 case CXCursor_ObjCClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001533 return MakeCXCursor(getCursorObjCClassRef(C).first, CXXUnit);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001534
1535 case CXCursor_TypeRef:
1536 return MakeCXCursor(getCursorTypeRef(C).first, CXXUnit);
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001537
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001538 default:
1539 // We would prefer to enumerate all non-reference cursor kinds here.
1540 llvm_unreachable("Unhandled reference cursor kind");
1541 break;
1542 }
1543 }
1544
1545 return clang_getNullCursor();
1546}
1547
Douglas Gregorb6998662010-01-19 19:34:47 +00001548CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001549 if (clang_isInvalid(C.kind))
1550 return clang_getNullCursor();
1551
1552 ASTUnit *CXXUnit = getCursorASTUnit(C);
1553
Douglas Gregorb6998662010-01-19 19:34:47 +00001554 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00001555 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00001556 C = clang_getCursorReferenced(C);
1557 WasReference = true;
1558 }
1559
1560 if (!clang_isDeclaration(C.kind))
1561 return clang_getNullCursor();
1562
1563 Decl *D = getCursorDecl(C);
1564 if (!D)
1565 return clang_getNullCursor();
1566
1567 switch (D->getKind()) {
1568 // Declaration kinds that don't really separate the notions of
1569 // declaration and definition.
1570 case Decl::Namespace:
1571 case Decl::Typedef:
1572 case Decl::TemplateTypeParm:
1573 case Decl::EnumConstant:
1574 case Decl::Field:
1575 case Decl::ObjCIvar:
1576 case Decl::ObjCAtDefsField:
1577 case Decl::ImplicitParam:
1578 case Decl::ParmVar:
1579 case Decl::NonTypeTemplateParm:
1580 case Decl::TemplateTemplateParm:
1581 case Decl::ObjCCategoryImpl:
1582 case Decl::ObjCImplementation:
1583 case Decl::LinkageSpec:
1584 case Decl::ObjCPropertyImpl:
1585 case Decl::FileScopeAsm:
1586 case Decl::StaticAssert:
1587 case Decl::Block:
1588 return C;
1589
1590 // Declaration kinds that don't make any sense here, but are
1591 // nonetheless harmless.
1592 case Decl::TranslationUnit:
1593 case Decl::Template:
1594 case Decl::ObjCContainer:
1595 break;
1596
1597 // Declaration kinds for which the definition is not resolvable.
1598 case Decl::UnresolvedUsingTypename:
1599 case Decl::UnresolvedUsingValue:
1600 break;
1601
1602 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001603 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
1604 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001605
1606 case Decl::NamespaceAlias:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001607 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001608
1609 case Decl::Enum:
1610 case Decl::Record:
1611 case Decl::CXXRecord:
1612 case Decl::ClassTemplateSpecialization:
1613 case Decl::ClassTemplatePartialSpecialization:
1614 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition(D->getASTContext()))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001615 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001616 return clang_getNullCursor();
1617
1618 case Decl::Function:
1619 case Decl::CXXMethod:
1620 case Decl::CXXConstructor:
1621 case Decl::CXXDestructor:
1622 case Decl::CXXConversion: {
1623 const FunctionDecl *Def = 0;
1624 if (cast<FunctionDecl>(D)->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001625 return MakeCXCursor(const_cast<FunctionDecl *>(Def), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001626 return clang_getNullCursor();
1627 }
1628
1629 case Decl::Var: {
1630 VarDecl *Var = cast<VarDecl>(D);
1631
1632 // Variables with initializers have definitions.
1633 const VarDecl *Def = 0;
1634 if (Var->getDefinition(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001635 return MakeCXCursor(const_cast<VarDecl *>(Def), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001636
1637 // extern and private_extern variables are not definitions.
1638 if (Var->hasExternalStorage())
1639 return clang_getNullCursor();
1640
1641 // In-line static data members do not have definitions.
1642 if (Var->isStaticDataMember() && !Var->isOutOfLine())
1643 return clang_getNullCursor();
1644
1645 // All other variables are themselves definitions.
1646 return C;
1647 }
1648
1649 case Decl::FunctionTemplate: {
1650 const FunctionDecl *Def = 0;
1651 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001652 return MakeCXCursor(Def->getDescribedFunctionTemplate(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001653 return clang_getNullCursor();
1654 }
1655
1656 case Decl::ClassTemplate: {
1657 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
1658 ->getDefinition(D->getASTContext()))
1659 return MakeCXCursor(
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001660 cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
1661 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001662 return clang_getNullCursor();
1663 }
1664
1665 case Decl::Using: {
1666 UsingDecl *Using = cast<UsingDecl>(D);
1667 CXCursor Def = clang_getNullCursor();
1668 for (UsingDecl::shadow_iterator S = Using->shadow_begin(),
1669 SEnd = Using->shadow_end();
1670 S != SEnd; ++S) {
1671 if (Def != clang_getNullCursor()) {
1672 // FIXME: We have no way to return multiple results.
1673 return clang_getNullCursor();
1674 }
1675
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001676 Def = clang_getCursorDefinition(MakeCXCursor((*S)->getTargetDecl(),
1677 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00001678 }
1679
1680 return Def;
1681 }
1682
1683 case Decl::UsingShadow:
1684 return clang_getCursorDefinition(
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001685 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
1686 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00001687
1688 case Decl::ObjCMethod: {
1689 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
1690 if (Method->isThisDeclarationADefinition())
1691 return C;
1692
1693 // Dig out the method definition in the associated
1694 // @implementation, if we have it.
1695 // FIXME: The ASTs should make finding the definition easier.
1696 if (ObjCInterfaceDecl *Class
1697 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
1698 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
1699 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
1700 Method->isInstanceMethod()))
1701 if (Def->isThisDeclarationADefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001702 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001703
1704 return clang_getNullCursor();
1705 }
1706
1707 case Decl::ObjCCategory:
1708 if (ObjCCategoryImplDecl *Impl
1709 = cast<ObjCCategoryDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001710 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001711 return clang_getNullCursor();
1712
1713 case Decl::ObjCProtocol:
1714 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
1715 return C;
1716 return clang_getNullCursor();
1717
1718 case Decl::ObjCInterface:
1719 // There are two notions of a "definition" for an Objective-C
1720 // class: the interface and its implementation. When we resolved a
1721 // reference to an Objective-C class, produce the @interface as
1722 // the definition; when we were provided with the interface,
1723 // produce the @implementation as the definition.
1724 if (WasReference) {
1725 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
1726 return C;
1727 } else if (ObjCImplementationDecl *Impl
1728 = cast<ObjCInterfaceDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001729 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001730 return clang_getNullCursor();
1731
1732 case Decl::ObjCProperty:
1733 // FIXME: We don't really know where to find the
1734 // ObjCPropertyImplDecls that implement this property.
1735 return clang_getNullCursor();
1736
1737 case Decl::ObjCCompatibleAlias:
1738 if (ObjCInterfaceDecl *Class
1739 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
1740 if (!Class->isForwardDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001741 return MakeCXCursor(Class, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001742
1743 return clang_getNullCursor();
1744
1745 case Decl::ObjCForwardProtocol: {
1746 ObjCForwardProtocolDecl *Forward = cast<ObjCForwardProtocolDecl>(D);
1747 if (Forward->protocol_size() == 1)
1748 return clang_getCursorDefinition(
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001749 MakeCXCursor(*Forward->protocol_begin(),
1750 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00001751
1752 // FIXME: Cannot return multiple definitions.
1753 return clang_getNullCursor();
1754 }
1755
1756 case Decl::ObjCClass: {
1757 ObjCClassDecl *Class = cast<ObjCClassDecl>(D);
1758 if (Class->size() == 1) {
1759 ObjCInterfaceDecl *IFace = Class->begin()->getInterface();
1760 if (!IFace->isForwardDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001761 return MakeCXCursor(IFace, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001762 return clang_getNullCursor();
1763 }
1764
1765 // FIXME: Cannot return multiple definitions.
1766 return clang_getNullCursor();
1767 }
1768
1769 case Decl::Friend:
1770 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001771 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00001772 return clang_getNullCursor();
1773
1774 case Decl::FriendTemplate:
1775 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001776 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00001777 return clang_getNullCursor();
1778 }
1779
1780 return clang_getNullCursor();
1781}
1782
1783unsigned clang_isCursorDefinition(CXCursor C) {
1784 if (!clang_isDeclaration(C.kind))
1785 return 0;
1786
1787 return clang_getCursorDefinition(C) == C;
1788}
1789
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001790void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00001791 const char **startBuf,
1792 const char **endBuf,
1793 unsigned *startLine,
1794 unsigned *startColumn,
1795 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001796 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00001797 assert(getCursorDecl(C) && "CXCursor has null decl");
1798 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00001799 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
1800 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekfb480492010-01-13 21:46:36 +00001801
Steve Naroff4ade6d62009-09-23 17:52:52 +00001802 SourceManager &SM = FD->getASTContext().getSourceManager();
1803 *startBuf = SM.getCharacterData(Body->getLBracLoc());
1804 *endBuf = SM.getCharacterData(Body->getRBracLoc());
1805 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
1806 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
1807 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
1808 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
1809}
Ted Kremenekfb480492010-01-13 21:46:36 +00001810
1811} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00001812
Ted Kremenekfb480492010-01-13 21:46:36 +00001813//===----------------------------------------------------------------------===//
1814// CXString Operations.
1815//===----------------------------------------------------------------------===//
1816
1817extern "C" {
1818const char *clang_getCString(CXString string) {
1819 return string.Spelling;
1820}
1821
1822void clang_disposeString(CXString string) {
1823 if (string.MustFreeString && string.Spelling)
1824 free((void*)string.Spelling);
1825}
Ted Kremenek04bb7162010-01-22 22:44:15 +00001826
Ted Kremenekfb480492010-01-13 21:46:36 +00001827} // end: extern "C"
Ted Kremenek04bb7162010-01-22 22:44:15 +00001828
1829//===----------------------------------------------------------------------===//
1830// Misc. utility functions.
1831//===----------------------------------------------------------------------===//
1832
1833extern "C" {
1834
1835const char *clang_getClangVersion() {
1836 return getClangFullVendorVersion();
1837}
1838
1839} // end: extern "C"
1840