blob: 4436709f80cdd4dc71f2eca15e9a3462db03a19b [file] [log] [blame]
Ted Kremenekd2fa5662009-08-26 22:36:44 +00001//===- CIndex.cpp - Clang-C Source Indexing Library -----------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00007//
Ted Kremenekd2fa5662009-08-26 22:36:44 +00008//===----------------------------------------------------------------------===//
9//
Ted Kremenekab188932010-01-05 19:32:54 +000010// This file implements the main API hooks in the Clang-C Source Indexing
11// library.
Ted Kremenekd2fa5662009-08-26 22:36:44 +000012//
13//===----------------------------------------------------------------------===//
14
Ted Kremenekab188932010-01-05 19:32:54 +000015#include "CIndexer.h"
Ted Kremenek16c440a2010-01-15 20:35:54 +000016#include "CXCursor.h"
Ted Kremenekab188932010-01-05 19:32:54 +000017
Ted Kremenek04bb7162010-01-22 22:44:15 +000018#include "clang/Basic/Version.h"
Steve Naroff50398192009-08-28 15:28:48 +000019#include "clang/AST/DeclVisitor.h"
Steve Narofffb570422009-09-22 19:25:29 +000020#include "clang/AST/StmtVisitor.h"
Douglas Gregor7d0d40e2010-01-21 16:28:34 +000021#include "clang/AST/TypeLocVisitor.h"
Ted Kremenekd8210652010-01-06 23:43:31 +000022#include "clang/Lex/Lexer.h"
Douglas Gregor33e9abd2010-01-22 19:49:59 +000023#include "clang/Lex/Preprocessor.h"
Douglas Gregor02465752009-10-16 21:24:31 +000024#include "llvm/Support/MemoryBuffer.h"
Benjamin Kramer0829a832009-10-18 11:19:36 +000025#include "llvm/System/Program.h"
Ted Kremenekfc062212009-10-19 21:44:57 +000026
Ted Kremenekdb3d0da2010-01-05 20:55:39 +000027// Needed to define L_TMPNAM on some systems.
28#include <cstdio>
29
Steve Naroff50398192009-08-28 15:28:48 +000030using namespace clang;
Ted Kremenek16c440a2010-01-15 20:35:54 +000031using namespace clang::cxcursor;
Steve Naroff50398192009-08-28 15:28:48 +000032using namespace idx;
33
Ted Kremenek8a8da7d2010-01-06 03:42:32 +000034//===----------------------------------------------------------------------===//
35// Crash Reporting.
36//===----------------------------------------------------------------------===//
37
38#ifdef __APPLE__
Ted Kremenek29b72842010-01-07 22:49:05 +000039#ifndef NDEBUG
40#define USE_CRASHTRACER
Ted Kremenek8a8da7d2010-01-06 03:42:32 +000041#include "clang/Analysis/Support/SaveAndRestore.h"
42// Integrate with crash reporter.
43extern "C" const char *__crashreporter_info__;
Ted Kremenek29b72842010-01-07 22:49:05 +000044#define NUM_CRASH_STRINGS 16
45static unsigned crashtracer_counter = 0;
Ted Kremenek254ba7c2010-01-07 23:13:53 +000046static unsigned crashtracer_counter_id[NUM_CRASH_STRINGS] = { 0 };
Ted Kremenek29b72842010-01-07 22:49:05 +000047static const char *crashtracer_strings[NUM_CRASH_STRINGS] = { 0 };
48static const char *agg_crashtracer_strings[NUM_CRASH_STRINGS] = { 0 };
49
50static unsigned SetCrashTracerInfo(const char *str,
51 llvm::SmallString<1024> &AggStr) {
52
Ted Kremenek254ba7c2010-01-07 23:13:53 +000053 unsigned slot = 0;
Ted Kremenek29b72842010-01-07 22:49:05 +000054 while (crashtracer_strings[slot]) {
55 if (++slot == NUM_CRASH_STRINGS)
56 slot = 0;
57 }
58 crashtracer_strings[slot] = str;
Ted Kremenek254ba7c2010-01-07 23:13:53 +000059 crashtracer_counter_id[slot] = ++crashtracer_counter;
Ted Kremenek29b72842010-01-07 22:49:05 +000060
61 // We need to create an aggregate string because multiple threads
62 // may be in this method at one time. The crash reporter string
63 // will attempt to overapproximate the set of in-flight invocations
64 // of this function. Race conditions can still cause this goal
65 // to not be achieved.
66 {
67 llvm::raw_svector_ostream Out(AggStr);
68 for (unsigned i = 0; i < NUM_CRASH_STRINGS; ++i)
69 if (crashtracer_strings[i]) Out << crashtracer_strings[i] << '\n';
70 }
71 __crashreporter_info__ = agg_crashtracer_strings[slot] = AggStr.c_str();
72 return slot;
73}
74
75static void ResetCrashTracerInfo(unsigned slot) {
Ted Kremenek254ba7c2010-01-07 23:13:53 +000076 unsigned max_slot = 0;
77 unsigned max_value = 0;
78
79 crashtracer_strings[slot] = agg_crashtracer_strings[slot] = 0;
80
81 for (unsigned i = 0 ; i < NUM_CRASH_STRINGS; ++i)
82 if (agg_crashtracer_strings[i] &&
83 crashtracer_counter_id[i] > max_value) {
84 max_slot = i;
85 max_value = crashtracer_counter_id[i];
Ted Kremenek29b72842010-01-07 22:49:05 +000086 }
Ted Kremenek254ba7c2010-01-07 23:13:53 +000087
88 __crashreporter_info__ = agg_crashtracer_strings[max_slot];
Ted Kremenek29b72842010-01-07 22:49:05 +000089}
90
91namespace {
92class ArgsCrashTracerInfo {
93 llvm::SmallString<1024> CrashString;
94 llvm::SmallString<1024> AggregateString;
95 unsigned crashtracerSlot;
96public:
97 ArgsCrashTracerInfo(llvm::SmallVectorImpl<const char*> &Args)
98 : crashtracerSlot(0)
99 {
100 {
101 llvm::raw_svector_ostream Out(CrashString);
102 Out << "ClangCIndex [createTranslationUnitFromSourceFile]: clang";
103 for (llvm::SmallVectorImpl<const char*>::iterator I=Args.begin(),
104 E=Args.end(); I!=E; ++I)
105 Out << ' ' << *I;
106 }
107 crashtracerSlot = SetCrashTracerInfo(CrashString.c_str(),
108 AggregateString);
109 }
110
111 ~ArgsCrashTracerInfo() {
112 ResetCrashTracerInfo(crashtracerSlot);
113 }
114};
115}
116#endif
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000117#endif
118
Douglas Gregor1db19de2010-01-19 21:36:55 +0000119typedef llvm::PointerIntPair<ASTContext *, 1, bool> CXSourceLocationPtr;
120
Douglas Gregor98258af2010-01-18 22:46:11 +0000121/// \brief Translate a Clang source location into a CIndex source location.
Douglas Gregor1db19de2010-01-19 21:36:55 +0000122static CXSourceLocation translateSourceLocation(ASTContext &Context,
123 SourceLocation Loc,
124 bool AtEnd = false) {
125 CXSourceLocationPtr Ptr(&Context, AtEnd);
126 CXSourceLocation Result = { Ptr.getOpaqueValue(), Loc.getRawEncoding() };
127 return Result;
Douglas Gregor98258af2010-01-18 22:46:11 +0000128}
129
Douglas Gregora7bde202010-01-19 00:34:46 +0000130/// \brief Translate a Clang source range into a CIndex source range.
Douglas Gregor1db19de2010-01-19 21:36:55 +0000131static CXSourceRange translateSourceRange(ASTContext &Context, SourceRange R) {
132 CXSourceRange Result = { &Context,
133 R.getBegin().getRawEncoding(),
134 R.getEnd().getRawEncoding() };
135 return Result;
Douglas Gregora7bde202010-01-19 00:34:46 +0000136}
137
Douglas Gregorb9790342010-01-22 21:44:22 +0000138static SourceLocation translateSourceLocation(CXSourceLocation L) {
139 return SourceLocation::getFromRawEncoding(L.int_data);
140}
141
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000142static SourceRange translateSourceRange(CXSourceRange R) {
143 return SourceRange(SourceLocation::getFromRawEncoding(R.begin_int_data),
144 SourceLocation::getFromRawEncoding(R.end_int_data));
145}
146
147/// \brief The result of comparing two source ranges.
148enum RangeComparisonResult {
149 /// \brief Either the ranges overlap or one of the ranges is invalid.
150 RangeOverlap,
151
152 /// \brief The first range ends before the second range starts.
153 RangeBefore,
154
155 /// \brief The first range starts after the second range ends.
156 RangeAfter
157};
158
159/// \brief Compare two source ranges to determine their relative position in
160/// the translation unit.
161static RangeComparisonResult RangeCompare(SourceManager &SM,
162 SourceRange R1,
163 SourceRange R2) {
164 assert(R1.isValid() && "First range is invalid?");
165 assert(R2.isValid() && "Second range is invalid?");
166 if (SM.isBeforeInTranslationUnit(R1.getEnd(), R2.getBegin()))
167 return RangeBefore;
168 if (SM.isBeforeInTranslationUnit(R2.getEnd(), R1.getBegin()))
169 return RangeAfter;
170 return RangeOverlap;
171}
172
Douglas Gregor1db19de2010-01-19 21:36:55 +0000173
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000174//===----------------------------------------------------------------------===//
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000175// Cursor visitor.
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000176//===----------------------------------------------------------------------===//
177
Steve Naroff89922f82009-08-31 00:59:03 +0000178namespace {
Ted Kremenekedc8aa62010-01-16 00:36:30 +0000179
Douglas Gregorb1373d02010-01-20 20:59:29 +0000180// Cursor visitor.
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000181class CursorVisitor : public DeclVisitor<CursorVisitor, bool>,
Douglas Gregora59e3902010-01-21 23:27:09 +0000182 public TypeLocVisitor<CursorVisitor, bool>,
183 public StmtVisitor<CursorVisitor, bool>
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000184{
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000185 /// \brief The translation unit we are traversing.
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000186 ASTUnit *TU;
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000187
188 /// \brief The parent cursor whose children we are traversing.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000189 CXCursor Parent;
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000190
191 /// \brief The declaration that serves at the parent of any statement or
192 /// expression nodes.
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000193 Decl *StmtParent;
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000194
195 /// \brief The visitor function.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000196 CXCursorVisitor Visitor;
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000197
198 /// \brief The opaque client data, to be passed along to the visitor.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000199 CXClientData ClientData;
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000200
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000201 // MaxPCHLevel - the maximum PCH level of declarations that we will pass on
202 // to the visitor. Declarations with a PCH level greater than this value will
203 // be suppressed.
204 unsigned MaxPCHLevel;
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000205
206 /// \brief When valid, a source range to which the cursor should restrict
207 /// its search.
208 SourceRange RegionOfInterest;
209
Douglas Gregorb1373d02010-01-20 20:59:29 +0000210 using DeclVisitor<CursorVisitor, bool>::Visit;
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000211 using TypeLocVisitor<CursorVisitor, bool>::Visit;
Douglas Gregora59e3902010-01-21 23:27:09 +0000212 using StmtVisitor<CursorVisitor, bool>::Visit;
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000213
214 /// \brief Determine whether this particular source range comes before, comes
215 /// after, or overlaps the region of interest.
216 ///
217 /// \param R a source range retrieved from the abstract syntax tree.
218 RangeComparisonResult CompareRegionOfInterest(SourceRange R);
219
220 /// \brief Determine whether this particular source range comes before, comes
221 /// after, or overlaps the region of interest.
222 ///
223 /// \param CXR a source range retrieved from a cursor.
224 RangeComparisonResult CompareRegionOfInterest(CXSourceRange CXR);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000225
Steve Naroff89922f82009-08-31 00:59:03 +0000226public:
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000227 CursorVisitor(ASTUnit *TU, CXCursorVisitor Visitor, CXClientData ClientData,
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000228 unsigned MaxPCHLevel,
229 SourceRange RegionOfInterest = SourceRange())
230 : TU(TU), Visitor(Visitor), ClientData(ClientData),
231 MaxPCHLevel(MaxPCHLevel), RegionOfInterest(RegionOfInterest)
Douglas Gregorb1373d02010-01-20 20:59:29 +0000232 {
233 Parent.kind = CXCursor_NoDeclFound;
234 Parent.data[0] = 0;
235 Parent.data[1] = 0;
236 Parent.data[2] = 0;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000237 StmtParent = 0;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000238 }
239
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000240 bool Visit(CXCursor Cursor, bool CheckedRegionOfInterest = false);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000241 bool VisitChildren(CXCursor Parent);
242
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000243 // Declaration visitors
Douglas Gregorb1373d02010-01-20 20:59:29 +0000244 bool VisitDeclContext(DeclContext *DC);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000245 bool VisitTranslationUnitDecl(TranslationUnitDecl *D);
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000246 bool VisitTypedefDecl(TypedefDecl *D);
247 bool VisitTagDecl(TagDecl *D);
248 bool VisitEnumConstantDecl(EnumConstantDecl *D);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000249 bool VisitDeclaratorDecl(DeclaratorDecl *DD);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000250 bool VisitFunctionDecl(FunctionDecl *ND);
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000251 bool VisitFieldDecl(FieldDecl *D);
252 bool VisitVarDecl(VarDecl *);
253 bool VisitObjCMethodDecl(ObjCMethodDecl *ND);
Douglas Gregora59e3902010-01-21 23:27:09 +0000254 bool VisitObjCContainerDecl(ObjCContainerDecl *D);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000255 bool VisitObjCCategoryDecl(ObjCCategoryDecl *ND);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000256 bool VisitObjCProtocolDecl(ObjCProtocolDecl *PID);
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000257 bool VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
258 bool VisitObjCImplDecl(ObjCImplDecl *D);
259 bool VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
260 bool VisitObjCImplementationDecl(ObjCImplementationDecl *D);
261 // FIXME: ObjCPropertyDecl requires TypeSourceInfo, getter/setter locations,
262 // etc.
263 // FIXME: ObjCCompatibleAliasDecl requires aliased-class locations.
264 bool VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D);
265 bool VisitObjCClassDecl(ObjCClassDecl *D);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000266
267 // Type visitors
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000268 // FIXME: QualifiedTypeLoc doesn't provide any location information
269 bool VisitBuiltinTypeLoc(BuiltinTypeLoc TL);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000270 bool VisitTypedefTypeLoc(TypedefTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000271 bool VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL);
272 bool VisitTagTypeLoc(TagTypeLoc TL);
273 // FIXME: TemplateTypeParmTypeLoc doesn't provide any location information
274 bool VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL);
275 bool VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL);
276 bool VisitPointerTypeLoc(PointerTypeLoc TL);
277 bool VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL);
278 bool VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL);
279 bool VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL);
280 bool VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL);
281 bool VisitFunctionTypeLoc(FunctionTypeLoc TL);
282 bool VisitArrayTypeLoc(ArrayTypeLoc TL);
Douglas Gregor2332c112010-01-21 20:48:56 +0000283 // FIXME: Implement for TemplateSpecializationTypeLoc
284 // FIXME: Implement visitors here when the unimplemented TypeLocs get
285 // implemented
286 bool VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL);
287 bool VisitTypeOfTypeLoc(TypeOfTypeLoc TL);
Douglas Gregora59e3902010-01-21 23:27:09 +0000288
289 // Statement visitors
290 bool VisitStmt(Stmt *S);
291 bool VisitDeclStmt(DeclStmt *S);
Douglas Gregorf5bab412010-01-22 01:00:11 +0000292 // FIXME: LabelStmt label?
293 bool VisitIfStmt(IfStmt *S);
294 bool VisitSwitchStmt(SwitchStmt *S);
Douglas Gregor336fd812010-01-23 00:40:08 +0000295
296 // Expression visitors
297 bool VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E);
298 bool VisitExplicitCastExpr(ExplicitCastExpr *E);
299 bool VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
Steve Naroff89922f82009-08-31 00:59:03 +0000300};
Douglas Gregorb1373d02010-01-20 20:59:29 +0000301
Ted Kremenekab188932010-01-05 19:32:54 +0000302} // end anonymous namespace
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000303
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000304RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
305 assert(RegionOfInterest.isValid() && "RangeCompare called with invalid range");
306 if (R.isInvalid())
307 return RangeOverlap;
308
309 // Move the end of the input range to the end of the last token in that
310 // range.
311 R.setEnd(TU->getPreprocessor().getLocForEndOfToken(R.getEnd(), 1));
312 return RangeCompare(TU->getSourceManager(), R, RegionOfInterest);
313}
314
315RangeComparisonResult CursorVisitor::CompareRegionOfInterest(CXSourceRange CXR) {
316 return CompareRegionOfInterest(translateSourceRange(CXR));
317}
318
Douglas Gregorb1373d02010-01-20 20:59:29 +0000319/// \brief Visit the given cursor and, if requested by the visitor,
320/// its children.
321///
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000322/// \param Cursor the cursor to visit.
323///
324/// \param CheckRegionOfInterest if true, then the caller already checked that
325/// this cursor is within the region of interest.
326///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000327/// \returns true if the visitation should be aborted, false if it
328/// should continue.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000329bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
Douglas Gregorb1373d02010-01-20 20:59:29 +0000330 if (clang_isInvalid(Cursor.kind))
331 return false;
332
333 if (clang_isDeclaration(Cursor.kind)) {
334 Decl *D = getCursorDecl(Cursor);
335 assert(D && "Invalid declaration cursor");
336 if (D->getPCHLevel() > MaxPCHLevel)
337 return false;
338
339 if (D->isImplicit())
340 return false;
341 }
342
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000343 // If we have a range of interest, and this cursor doesn't intersect with it,
344 // we're done.
345 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
346 CXSourceRange Range = clang_getCursorExtent(Cursor);
347 if (translateSourceRange(Range).isInvalid() ||
348 CompareRegionOfInterest(Range))
349 return false;
350 }
351
Douglas Gregorb1373d02010-01-20 20:59:29 +0000352 switch (Visitor(Cursor, Parent, ClientData)) {
353 case CXChildVisit_Break:
354 return true;
355
356 case CXChildVisit_Continue:
357 return false;
358
359 case CXChildVisit_Recurse:
360 return VisitChildren(Cursor);
361 }
362
363 llvm_unreachable("Silly GCC, we can't get here");
364}
365
366/// \brief Visit the children of the given cursor.
367///
368/// \returns true if the visitation should be aborted, false if it
369/// should continue.
370bool CursorVisitor::VisitChildren(CXCursor Cursor) {
Douglas Gregora59e3902010-01-21 23:27:09 +0000371 if (clang_isReference(Cursor.kind)) {
372 // By definition, references have no children.
373 return false;
374 }
375
Douglas Gregorb1373d02010-01-20 20:59:29 +0000376 // Set the Parent field to Cursor, then back to its old value once we're
377 // done.
378 class SetParentRAII {
379 CXCursor &Parent;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000380 Decl *&StmtParent;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000381 CXCursor OldParent;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000382
Douglas Gregorb1373d02010-01-20 20:59:29 +0000383 public:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000384 SetParentRAII(CXCursor &Parent, Decl *&StmtParent, CXCursor NewParent)
385 : Parent(Parent), StmtParent(StmtParent), OldParent(Parent)
Douglas Gregorb1373d02010-01-20 20:59:29 +0000386 {
387 Parent = NewParent;
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 }
391
392 ~SetParentRAII() {
393 Parent = OldParent;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000394 if (clang_isDeclaration(Parent.kind))
395 StmtParent = getCursorDecl(Parent);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000396 }
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000397 } SetParent(Parent, StmtParent, Cursor);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000398
399 if (clang_isDeclaration(Cursor.kind)) {
400 Decl *D = getCursorDecl(Cursor);
401 assert(D && "Invalid declaration cursor");
402 return Visit(D);
403 }
404
Douglas Gregora59e3902010-01-21 23:27:09 +0000405 if (clang_isStatement(Cursor.kind))
406 return Visit(getCursorStmt(Cursor));
407 if (clang_isExpression(Cursor.kind))
408 return Visit(getCursorExpr(Cursor));
409
Douglas Gregorb1373d02010-01-20 20:59:29 +0000410 if (clang_isTranslationUnit(Cursor.kind)) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000411 ASTUnit *CXXUnit = getCursorASTUnit(Cursor);
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000412 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
413 RegionOfInterest.isInvalid()) {
Douglas Gregor7b691f332010-01-20 21:13:59 +0000414 const std::vector<Decl*> &TLDs = CXXUnit->getTopLevelDecls();
415 for (std::vector<Decl*>::const_iterator it = TLDs.begin(),
416 ie = TLDs.end(); it != ie; ++it) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000417 if (Visit(MakeCXCursor(*it, CXXUnit), true))
Douglas Gregor7b691f332010-01-20 21:13:59 +0000418 return true;
419 }
420 } else {
421 return VisitDeclContext(
Douglas Gregorb1373d02010-01-20 20:59:29 +0000422 CXXUnit->getASTContext().getTranslationUnitDecl());
Douglas Gregor7b691f332010-01-20 21:13:59 +0000423 }
424
425 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000426 }
Douglas Gregora59e3902010-01-21 23:27:09 +0000427
Douglas Gregorb1373d02010-01-20 20:59:29 +0000428 // Nothing to visit at the moment.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000429 return false;
430}
431
Douglas Gregorb1373d02010-01-20 20:59:29 +0000432bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000433 for (DeclContext::decl_iterator
Douglas Gregorb1373d02010-01-20 20:59:29 +0000434 I = DC->decls_begin(), E = DC->decls_end(); I != E; ++I) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000435 if (RegionOfInterest.isValid()) {
436 SourceRange R = (*I)->getSourceRange();
437 if (R.isInvalid())
438 continue;
439
440 switch (CompareRegionOfInterest(R)) {
441 case RangeBefore:
442 // This declaration comes before the region of interest; skip it.
443 continue;
444
445 case RangeAfter:
446 // This declaration comes after the region of interest; we're done.
447 return false;
448
449 case RangeOverlap:
450 // This declaration overlaps the region of interest; visit it.
451 break;
452 }
453 }
454
455 if (Visit(MakeCXCursor(*I, TU), true))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000456 return true;
457 }
458
459 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000460}
461
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000462bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
463 llvm_unreachable("Translation units are visited directly by Visit()");
464 return false;
465}
466
467bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
468 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
469 return Visit(TSInfo->getTypeLoc());
470
471 return false;
472}
473
474bool CursorVisitor::VisitTagDecl(TagDecl *D) {
475 return VisitDeclContext(D);
476}
477
478bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
479 if (Expr *Init = D->getInitExpr())
480 return Visit(MakeCXCursor(Init, StmtParent, TU));
481 return false;
482}
483
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000484bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
485 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
486 if (Visit(TSInfo->getTypeLoc()))
487 return true;
488
489 return false;
490}
491
Douglas Gregorb1373d02010-01-20 20:59:29 +0000492bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000493 if (VisitDeclaratorDecl(ND))
494 return true;
495
Douglas Gregora59e3902010-01-21 23:27:09 +0000496 if (ND->isThisDeclarationADefinition() &&
497 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
498 return true;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000499
500 return false;
501}
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000502
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000503bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
504 if (VisitDeclaratorDecl(D))
505 return true;
506
507 if (Expr *BitWidth = D->getBitWidth())
508 return Visit(MakeCXCursor(BitWidth, StmtParent, TU));
509
510 return false;
511}
512
513bool CursorVisitor::VisitVarDecl(VarDecl *D) {
514 if (VisitDeclaratorDecl(D))
515 return true;
516
517 if (Expr *Init = D->getInit())
518 return Visit(MakeCXCursor(Init, StmtParent, TU));
519
520 return false;
521}
522
523bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
524 // FIXME: We really need a TypeLoc covering Objective-C method declarations.
525 // At the moment, we don't have information about locations in the return
526 // type.
527 for (ObjCMethodDecl::param_iterator P = ND->param_begin(),
528 PEnd = ND->param_end();
529 P != PEnd; ++P) {
530 if (Visit(MakeCXCursor(*P, TU)))
531 return true;
532 }
533
534 if (ND->isThisDeclarationADefinition() &&
535 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
536 return true;
537
538 return false;
539}
540
Douglas Gregora59e3902010-01-21 23:27:09 +0000541bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
542 return VisitDeclContext(D);
543}
544
Douglas Gregorb1373d02010-01-20 20:59:29 +0000545bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000546 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
547 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000548 return true;
549
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000550 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
551 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
552 E = ND->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000553 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000554 return true;
555
Douglas Gregora59e3902010-01-21 23:27:09 +0000556 return VisitObjCContainerDecl(ND);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000557}
558
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000559bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
560 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
561 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
562 E = PID->protocol_end(); I != E; ++I, ++PL)
563 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
564 return true;
565
566 return VisitObjCContainerDecl(PID);
567}
568
Douglas Gregorb1373d02010-01-20 20:59:29 +0000569bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000570 // Issue callbacks for super class.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000571 if (D->getSuperClass() &&
572 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000573 D->getSuperClassLoc(),
574 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000575 return true;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000576
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000577 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
578 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
579 E = D->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000580 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000581 return true;
582
Douglas Gregora59e3902010-01-21 23:27:09 +0000583 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000584}
585
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000586bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
587 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000588}
589
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000590bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
591 if (Visit(MakeCursorObjCClassRef(D->getCategoryDecl()->getClassInterface(),
592 D->getLocation(), TU)))
593 return true;
594
595 return VisitObjCImplDecl(D);
596}
597
598bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
599#if 0
600 // Issue callbacks for super class.
601 // FIXME: No source location information!
602 if (D->getSuperClass() &&
603 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
604 D->getSuperClassLoc(),
605 TU)))
606 return true;
607#endif
608
609 return VisitObjCImplDecl(D);
610}
611
612bool CursorVisitor::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D) {
613 ObjCForwardProtocolDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
614 for (ObjCForwardProtocolDecl::protocol_iterator I = D->protocol_begin(),
615 E = D->protocol_end();
616 I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000617 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000618 return true;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000619
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000620 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000621}
622
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000623bool CursorVisitor::VisitObjCClassDecl(ObjCClassDecl *D) {
624 for (ObjCClassDecl::iterator C = D->begin(), CEnd = D->end(); C != CEnd; ++C)
625 if (Visit(MakeCursorObjCClassRef(C->getInterface(), C->getLocation(), TU)))
626 return true;
627
628 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000629}
630
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000631bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
632 ASTContext &Context = TU->getASTContext();
633
634 // Some builtin types (such as Objective-C's "id", "sel", and
635 // "Class") have associated declarations. Create cursors for those.
636 QualType VisitType;
637 switch (TL.getType()->getAs<BuiltinType>()->getKind()) {
638 case BuiltinType::Void:
639 case BuiltinType::Bool:
640 case BuiltinType::Char_U:
641 case BuiltinType::UChar:
642 case BuiltinType::Char16:
643 case BuiltinType::Char32:
644 case BuiltinType::UShort:
645 case BuiltinType::UInt:
646 case BuiltinType::ULong:
647 case BuiltinType::ULongLong:
648 case BuiltinType::UInt128:
649 case BuiltinType::Char_S:
650 case BuiltinType::SChar:
651 case BuiltinType::WChar:
652 case BuiltinType::Short:
653 case BuiltinType::Int:
654 case BuiltinType::Long:
655 case BuiltinType::LongLong:
656 case BuiltinType::Int128:
657 case BuiltinType::Float:
658 case BuiltinType::Double:
659 case BuiltinType::LongDouble:
660 case BuiltinType::NullPtr:
661 case BuiltinType::Overload:
662 case BuiltinType::Dependent:
663 break;
664
665 case BuiltinType::UndeducedAuto: // FIXME: Deserves a cursor?
666 break;
667
668 case BuiltinType::ObjCId:
669 VisitType = Context.getObjCIdType();
670 break;
671
672 case BuiltinType::ObjCClass:
673 VisitType = Context.getObjCClassType();
674 break;
675
676 case BuiltinType::ObjCSel:
677 VisitType = Context.getObjCSelType();
678 break;
679 }
680
681 if (!VisitType.isNull()) {
682 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
683 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
684 TU));
685 }
686
687 return false;
688}
689
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000690bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
691 return Visit(MakeCursorTypeRef(TL.getTypedefDecl(), TL.getNameLoc(), TU));
692}
693
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000694bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
695 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
696}
697
698bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
699 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
700}
701
702bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
703 if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
704 return true;
705
706 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
707 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
708 TU)))
709 return true;
710 }
711
712 return false;
713}
714
715bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
716 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseTypeLoc()))
717 return true;
718
719 if (TL.hasProtocolsAsWritten()) {
720 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
721 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I),
722 TL.getProtocolLoc(I),
723 TU)))
724 return true;
725 }
726 }
727
728 return false;
729}
730
731bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
732 return Visit(TL.getPointeeLoc());
733}
734
735bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
736 return Visit(TL.getPointeeLoc());
737}
738
739bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
740 return Visit(TL.getPointeeLoc());
741}
742
743bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
744 return Visit(TL.getPointeeLoc());
745}
746
747bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
748 return Visit(TL.getPointeeLoc());
749}
750
751bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
752 if (Visit(TL.getResultLoc()))
753 return true;
754
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000755 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
756 if (Visit(MakeCXCursor(TL.getArg(I), TU)))
757 return true;
758
759 return false;
760}
761
762bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
763 if (Visit(TL.getElementLoc()))
764 return true;
765
766 if (Expr *Size = TL.getSizeExpr())
767 return Visit(MakeCXCursor(Size, StmtParent, TU));
768
769 return false;
770}
771
Douglas Gregor2332c112010-01-21 20:48:56 +0000772bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
773 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
774}
775
776bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
777 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
778 return Visit(TSInfo->getTypeLoc());
779
780 return false;
781}
782
Douglas Gregora59e3902010-01-21 23:27:09 +0000783bool CursorVisitor::VisitStmt(Stmt *S) {
784 for (Stmt::child_iterator Child = S->child_begin(), ChildEnd = S->child_end();
785 Child != ChildEnd; ++Child) {
Daniel Dunbar54d67ca2010-01-25 00:40:30 +0000786 if (*Child && Visit(MakeCXCursor(*Child, StmtParent, TU)))
Douglas Gregora59e3902010-01-21 23:27:09 +0000787 return true;
788 }
789
790 return false;
791}
792
793bool CursorVisitor::VisitDeclStmt(DeclStmt *S) {
794 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
795 D != DEnd; ++D) {
796 if (Visit(MakeCXCursor(*D, TU)))
797 return true;
798 }
799
800 return false;
801}
802
Douglas Gregorf5bab412010-01-22 01:00:11 +0000803bool CursorVisitor::VisitIfStmt(IfStmt *S) {
804 if (VarDecl *Var = S->getConditionVariable()) {
805 if (Visit(MakeCXCursor(Var, TU)))
806 return true;
807 } else if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
808 return true;
809
810 if (S->getThen() && Visit(MakeCXCursor(S->getThen(), StmtParent, TU)))
811 return true;
812
813 if (S->getElse() && Visit(MakeCXCursor(S->getElse(), StmtParent, TU)))
814 return true;
815
816 return false;
817}
818
819bool CursorVisitor::VisitSwitchStmt(SwitchStmt *S) {
820 if (VarDecl *Var = S->getConditionVariable()) {
821 if (Visit(MakeCXCursor(Var, TU)))
822 return true;
823 } else if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
824 return true;
825
826 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
827 return true;
828
829 return false;
830}
831
Douglas Gregor336fd812010-01-23 00:40:08 +0000832bool CursorVisitor::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E) {
833 if (E->isArgumentType()) {
834 if (TypeSourceInfo *TSInfo = E->getArgumentTypeInfo())
835 return Visit(TSInfo->getTypeLoc());
836
837 return false;
838 }
839
840 return VisitExpr(E);
841}
842
843bool CursorVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
844 if (TypeSourceInfo *TSInfo = E->getTypeInfoAsWritten())
845 if (Visit(TSInfo->getTypeLoc()))
846 return true;
847
848 return VisitCastExpr(E);
849}
850
851bool CursorVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
852 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
853 if (Visit(TSInfo->getTypeLoc()))
854 return true;
855
856 return VisitExpr(E);
857}
858
Daniel Dunbar140fce22010-01-12 02:34:07 +0000859CXString CIndexer::createCXString(const char *String, bool DupString){
Benjamin Kramer62cf3222009-11-09 19:13:48 +0000860 CXString Str;
861 if (DupString) {
862 Str.Spelling = strdup(String);
863 Str.MustFreeString = 1;
864 } else {
865 Str.Spelling = String;
866 Str.MustFreeString = 0;
867 }
868 return Str;
869}
870
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000871extern "C" {
Steve Naroffe56b4ba2009-10-20 14:46:24 +0000872CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000873 int displayDiagnostics) {
Douglas Gregora030b7c2010-01-22 20:35:53 +0000874 CIndexer *CIdxr = new CIndexer();
Steve Naroffe56b4ba2009-10-20 14:46:24 +0000875 if (excludeDeclarationsFromPCH)
876 CIdxr->setOnlyLocalDecls();
877 if (displayDiagnostics)
878 CIdxr->setDisplayDiagnostics();
879 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +0000880}
881
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000882void clang_disposeIndex(CXIndex CIdx) {
Steve Naroff2bd6b9f2009-09-17 18:33:27 +0000883 assert(CIdx && "Passed null CXIndex");
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000884 delete static_cast<CIndexer *>(CIdx);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +0000885}
886
Daniel Dunbar8506dde2009-12-03 01:54:28 +0000887void clang_setUseExternalASTGeneration(CXIndex CIdx, int value) {
888 assert(CIdx && "Passed null CXIndex");
889 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
890 CXXIdx->setUseExternalASTGeneration(value);
891}
892
Steve Naroff50398192009-08-28 15:28:48 +0000893// FIXME: need to pass back error info.
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000894CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
895 const char *ast_filename) {
Steve Naroff50398192009-08-28 15:28:48 +0000896 assert(CIdx && "Passed null CXIndex");
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000897 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000898
Daniel Dunbar5262fda2009-12-03 01:45:44 +0000899 return ASTUnit::LoadFromPCHFile(ast_filename, CXXIdx->getDiags(),
900 CXXIdx->getOnlyLocalDecls(),
901 /* UseBumpAllocator = */ true);
Steve Naroff600866c2009-08-27 19:51:58 +0000902}
903
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000904CXTranslationUnit
905clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
906 const char *source_filename,
907 int num_command_line_args,
Douglas Gregor4db64a42010-01-23 00:14:00 +0000908 const char **command_line_args,
909 unsigned num_unsaved_files,
910 struct CXUnsavedFile *unsaved_files) {
Steve Naroffe56b4ba2009-10-20 14:46:24 +0000911 assert(CIdx && "Passed null CXIndex");
912 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
913
Douglas Gregor4db64a42010-01-23 00:14:00 +0000914 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
915 for (unsigned I = 0; I != num_unsaved_files; ++I) {
916 const llvm::MemoryBuffer *Buffer
917 = llvm::MemoryBuffer::getMemBuffer(unsaved_files[I].Contents,
918 unsaved_files[I].Contents + unsaved_files[I].Length,
919 unsaved_files[I].Filename);
920 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
921 Buffer));
922 }
923
Daniel Dunbar8506dde2009-12-03 01:54:28 +0000924 if (!CXXIdx->getUseExternalASTGeneration()) {
925 llvm::SmallVector<const char *, 16> Args;
926
927 // The 'source_filename' argument is optional. If the caller does not
928 // specify it then it is assumed that the source file is specified
929 // in the actual argument list.
930 if (source_filename)
931 Args.push_back(source_filename);
932 Args.insert(Args.end(), command_line_args,
933 command_line_args + num_command_line_args);
934
Daniel Dunbar94220972009-12-05 02:17:18 +0000935 unsigned NumErrors = CXXIdx->getDiags().getNumErrors();
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000936
Ted Kremenek29b72842010-01-07 22:49:05 +0000937#ifdef USE_CRASHTRACER
938 ArgsCrashTracerInfo ACTI(Args);
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000939#endif
940
Daniel Dunbar94220972009-12-05 02:17:18 +0000941 llvm::OwningPtr<ASTUnit> Unit(
942 ASTUnit::LoadFromCommandLine(Args.data(), Args.data() + Args.size(),
Daniel Dunbar869824e2009-12-13 03:46:13 +0000943 CXXIdx->getDiags(),
944 CXXIdx->getClangResourcesPath(),
Daniel Dunbar94220972009-12-05 02:17:18 +0000945 CXXIdx->getOnlyLocalDecls(),
Douglas Gregor4db64a42010-01-23 00:14:00 +0000946 /* UseBumpAllocator = */ true,
947 RemappedFiles.data(),
948 RemappedFiles.size()));
Ted Kremenek29b72842010-01-07 22:49:05 +0000949
Daniel Dunbar94220972009-12-05 02:17:18 +0000950 // FIXME: Until we have broader testing, just drop the entire AST if we
951 // encountered an error.
952 if (NumErrors != CXXIdx->getDiags().getNumErrors())
953 return 0;
954
955 return Unit.take();
Daniel Dunbar8506dde2009-12-03 01:54:28 +0000956 }
957
Ted Kremenek139ba862009-10-22 00:03:57 +0000958 // Build up the arguments for invoking 'clang'.
Ted Kremenek74cd0692009-10-15 23:21:22 +0000959 std::vector<const char *> argv;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000960
Ted Kremenek139ba862009-10-22 00:03:57 +0000961 // First add the complete path to the 'clang' executable.
962 llvm::sys::Path ClangPath = static_cast<CIndexer *>(CIdx)->getClangPath();
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000963 argv.push_back(ClangPath.c_str());
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000964
Ted Kremenek139ba862009-10-22 00:03:57 +0000965 // Add the '-emit-ast' option as our execution mode for 'clang'.
Ted Kremenek74cd0692009-10-15 23:21:22 +0000966 argv.push_back("-emit-ast");
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000967
Ted Kremenek139ba862009-10-22 00:03:57 +0000968 // The 'source_filename' argument is optional. If the caller does not
969 // specify it then it is assumed that the source file is specified
970 // in the actual argument list.
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000971 if (source_filename)
972 argv.push_back(source_filename);
Ted Kremenek139ba862009-10-22 00:03:57 +0000973
Steve Naroff37b5ac22009-10-15 20:50:09 +0000974 // Generate a temporary name for the AST file.
Ted Kremenek139ba862009-10-22 00:03:57 +0000975 argv.push_back("-o");
Steve Naroff37b5ac22009-10-15 20:50:09 +0000976 char astTmpFile[L_tmpnam];
Ted Kremenek74cd0692009-10-15 23:21:22 +0000977 argv.push_back(tmpnam(astTmpFile));
Ted Kremenek139ba862009-10-22 00:03:57 +0000978
Douglas Gregor4db64a42010-01-23 00:14:00 +0000979 // Remap any unsaved files to temporary files.
980 std::vector<llvm::sys::Path> TemporaryFiles;
981 std::vector<std::string> RemapArgs;
982 if (RemapFiles(num_unsaved_files, unsaved_files, RemapArgs, TemporaryFiles))
983 return 0;
984
985 // The pointers into the elements of RemapArgs are stable because we
986 // won't be adding anything to RemapArgs after this point.
987 for (unsigned i = 0, e = RemapArgs.size(); i != e; ++i)
988 argv.push_back(RemapArgs[i].c_str());
989
Ted Kremenek139ba862009-10-22 00:03:57 +0000990 // Process the compiler options, stripping off '-o', '-c', '-fsyntax-only'.
991 for (int i = 0; i < num_command_line_args; ++i)
992 if (const char *arg = command_line_args[i]) {
993 if (strcmp(arg, "-o") == 0) {
994 ++i; // Also skip the matching argument.
995 continue;
996 }
997 if (strcmp(arg, "-emit-ast") == 0 ||
998 strcmp(arg, "-c") == 0 ||
999 strcmp(arg, "-fsyntax-only") == 0) {
1000 continue;
1001 }
1002
1003 // Keep the argument.
1004 argv.push_back(arg);
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001005 }
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001006
Ted Kremenek139ba862009-10-22 00:03:57 +00001007 // Add the null terminator.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001008 argv.push_back(NULL);
1009
Ted Kremenekfeb15e32009-10-26 22:14:08 +00001010 // Invoke 'clang'.
1011 llvm::sys::Path DevNull; // leave empty, causes redirection to /dev/null
1012 // on Unix or NUL (Windows).
Ted Kremenek379afec2009-10-22 03:24:01 +00001013 std::string ErrMsg;
Ted Kremenekc46e4632009-10-19 22:27:32 +00001014 const llvm::sys::Path *Redirects[] = { &DevNull, &DevNull, &DevNull, NULL };
Ted Kremenek379afec2009-10-22 03:24:01 +00001015 llvm::sys::Program::ExecuteAndWait(ClangPath, &argv[0], /* env */ NULL,
1016 /* redirects */ !CXXIdx->getDisplayDiagnostics() ? &Redirects[0] : NULL,
1017 /* secondsToWait */ 0, /* memoryLimits */ 0, &ErrMsg);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001018
Ted Kremenek0854d702009-11-10 19:18:52 +00001019 if (CXXIdx->getDisplayDiagnostics() && !ErrMsg.empty()) {
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001020 llvm::errs() << "clang_createTranslationUnitFromSourceFile: " << ErrMsg
Daniel Dunbaracca7252009-11-30 20:42:49 +00001021 << '\n' << "Arguments: \n";
Ted Kremenek379afec2009-10-22 03:24:01 +00001022 for (std::vector<const char*>::iterator I = argv.begin(), E = argv.end();
Ted Kremenek779e5f42009-10-26 22:08:39 +00001023 I!=E; ++I) {
1024 if (*I)
1025 llvm::errs() << ' ' << *I << '\n';
1026 }
1027 llvm::errs() << '\n';
Ted Kremenek379afec2009-10-22 03:24:01 +00001028 }
Benjamin Kramer0829a832009-10-18 11:19:36 +00001029
Douglas Gregor4db64a42010-01-23 00:14:00 +00001030 ASTUnit *ATU = ASTUnit::LoadFromPCHFile(astTmpFile, CXXIdx->getDiags(),
1031 CXXIdx->getOnlyLocalDecls(),
1032 /* UseBumpAllocator = */ true,
1033 RemappedFiles.data(),
1034 RemappedFiles.size());
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001035 if (ATU)
1036 ATU->unlinkTemporaryFile();
Douglas Gregor4db64a42010-01-23 00:14:00 +00001037
1038 for (unsigned i = 0, e = TemporaryFiles.size(); i != e; ++i)
1039 TemporaryFiles[i].eraseFromDisk();
1040
Steve Naroffe19944c2009-10-15 22:23:48 +00001041 return ATU;
Steve Naroff5b7d8e22009-10-15 20:04:39 +00001042}
1043
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001044void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00001045 assert(CTUnit && "Passed null CXTranslationUnit");
1046 delete static_cast<ASTUnit *>(CTUnit);
1047}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001048
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001049CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Steve Naroffaf08ddc2009-09-03 15:49:00 +00001050 assert(CTUnit && "Passed null CXTranslationUnit");
Steve Naroff77accc12009-09-03 18:19:54 +00001051 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit);
Ted Kremenek4b333d22010-01-12 00:36:38 +00001052 return CIndexer::createCXString(CXXUnit->getOriginalSourceFileName().c_str(),
1053 true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +00001054}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +00001055
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001056CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001057 CXCursor Result = { CXCursor_TranslationUnit, { 0, 0, TU } };
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001058 return Result;
1059}
1060
Ted Kremenekfb480492010-01-13 21:46:36 +00001061} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +00001062
Ted Kremenekfb480492010-01-13 21:46:36 +00001063//===----------------------------------------------------------------------===//
Douglas Gregor1db19de2010-01-19 21:36:55 +00001064// CXSourceLocation and CXSourceRange Operations.
1065//===----------------------------------------------------------------------===//
1066
Douglas Gregorb9790342010-01-22 21:44:22 +00001067extern "C" {
1068CXSourceLocation clang_getNullLocation() {
1069 CXSourceLocation Result = { 0, 0 };
1070 return Result;
1071}
1072
1073unsigned clang_equalLocations(CXSourceLocation loc1, CXSourceLocation loc2) {
1074 return loc1.ptr_data == loc2.ptr_data && loc1.int_data == loc2.int_data;
1075}
1076
1077CXSourceLocation clang_getLocation(CXTranslationUnit tu,
1078 CXFile file,
1079 unsigned line,
1080 unsigned column) {
1081 if (!tu)
1082 return clang_getNullLocation();
1083
1084 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
1085 SourceLocation SLoc
1086 = CXXUnit->getSourceManager().getLocation(
1087 static_cast<const FileEntry *>(file),
1088 line, column);
1089
1090 return translateSourceLocation(CXXUnit->getASTContext(), SLoc, false);
1091}
1092
1093CXSourceRange clang_getRange(CXSourceLocation begin, CXSourceLocation end) {
1094 if (begin.ptr_data != end.ptr_data) {
1095 CXSourceRange Result = { 0, 0, 0 };
1096 return Result;
1097 }
1098
1099 CXSourceRange Result = { begin.ptr_data, begin.int_data, end.int_data };
1100 return Result;
1101}
1102
Douglas Gregor1db19de2010-01-19 21:36:55 +00001103void clang_getInstantiationLocation(CXSourceLocation location,
1104 CXFile *file,
1105 unsigned *line,
1106 unsigned *column) {
1107 CXSourceLocationPtr Ptr
1108 = CXSourceLocationPtr::getFromOpaqueValue(location.ptr_data);
1109 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
1110
1111 if (!Ptr.getPointer() || Loc.isInvalid()) {
1112 if (file)
1113 *file = 0;
1114 if (line)
1115 *line = 0;
1116 if (column)
1117 *column = 0;
1118 return;
1119 }
1120
1121 // FIXME: This is largely copy-paste from
1122 ///TextDiagnosticPrinter::HighlightRange. When it is clear that this is
1123 // what we want the two routines should be refactored.
1124 ASTContext &Context = *Ptr.getPointer();
1125 SourceManager &SM = Context.getSourceManager();
1126 SourceLocation InstLoc = SM.getInstantiationLoc(Loc);
1127
1128 if (Ptr.getInt()) {
1129 // We want the last character in this location, so we will adjust
1130 // the instantiation location accordingly.
1131
1132 // If the location is from a macro instantiation, get the end of
1133 // the instantiation range.
1134 if (Loc.isMacroID())
1135 InstLoc = SM.getInstantiationRange(Loc).second;
1136
1137 // Measure the length token we're pointing at, so we can adjust
1138 // the physical location in the file to point at the last
1139 // character.
1140 // FIXME: This won't cope with trigraphs or escaped newlines
1141 // well. For that, we actually need a preprocessor, which isn't
1142 // currently available here. Eventually, we'll switch the pointer
1143 // data of CXSourceLocation/CXSourceRange to a translation unit
1144 // (CXXUnit), so that the preprocessor will be available here. At
1145 // that point, we can use Preprocessor::getLocForEndOfToken().
1146 unsigned Length = Lexer::MeasureTokenLength(InstLoc, SM,
1147 Context.getLangOptions());
1148 if (Length > 0)
1149 InstLoc = InstLoc.getFileLocWithOffset(Length - 1);
1150 }
1151
1152 if (file)
1153 *file = (void *)SM.getFileEntryForID(SM.getFileID(InstLoc));
1154 if (line)
1155 *line = SM.getInstantiationLineNumber(InstLoc);
1156 if (column)
1157 *column = SM.getInstantiationColumnNumber(InstLoc);
1158}
1159
1160CXSourceLocation clang_getRangeStart(CXSourceRange range) {
1161 CXSourceLocation Result = { range.ptr_data, range.begin_int_data };
1162 return Result;
1163}
1164
1165CXSourceLocation clang_getRangeEnd(CXSourceRange range) {
1166 llvm::PointerIntPair<ASTContext *, 1, bool> Ptr;
1167 Ptr.setPointer(static_cast<ASTContext *>(range.ptr_data));
1168 Ptr.setInt(true);
1169 CXSourceLocation Result = { Ptr.getOpaqueValue(), range.end_int_data };
1170 return Result;
1171}
1172
Douglas Gregorb9790342010-01-22 21:44:22 +00001173} // end: extern "C"
1174
Douglas Gregor1db19de2010-01-19 21:36:55 +00001175//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00001176// CXFile Operations.
1177//===----------------------------------------------------------------------===//
1178
1179extern "C" {
Steve Naroff88145032009-10-27 14:35:18 +00001180const char *clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00001181 if (!SFile)
1182 return 0;
1183
Steve Naroff88145032009-10-27 14:35:18 +00001184 assert(SFile && "Passed null CXFile");
1185 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
1186 return FEnt->getName();
1187}
1188
1189time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00001190 if (!SFile)
1191 return 0;
1192
Steve Naroff88145032009-10-27 14:35:18 +00001193 assert(SFile && "Passed null CXFile");
1194 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
1195 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +00001196}
Douglas Gregorb9790342010-01-22 21:44:22 +00001197
1198CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
1199 if (!tu)
1200 return 0;
1201
1202 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
1203
1204 FileManager &FMgr = CXXUnit->getFileManager();
1205 const FileEntry *File = FMgr.getFile(file_name, file_name+strlen(file_name));
1206 return const_cast<FileEntry *>(File);
1207}
1208
Ted Kremenekfb480492010-01-13 21:46:36 +00001209} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +00001210
Ted Kremenekfb480492010-01-13 21:46:36 +00001211//===----------------------------------------------------------------------===//
1212// CXCursor Operations.
1213//===----------------------------------------------------------------------===//
1214
Ted Kremenekfb480492010-01-13 21:46:36 +00001215static Decl *getDeclFromExpr(Stmt *E) {
1216 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
1217 return RefExpr->getDecl();
1218 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
1219 return ME->getMemberDecl();
1220 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
1221 return RE->getDecl();
1222
1223 if (CallExpr *CE = dyn_cast<CallExpr>(E))
1224 return getDeclFromExpr(CE->getCallee());
1225 if (CastExpr *CE = dyn_cast<CastExpr>(E))
1226 return getDeclFromExpr(CE->getSubExpr());
1227 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
1228 return OME->getMethodDecl();
1229
1230 return 0;
1231}
1232
1233extern "C" {
Douglas Gregorb1373d02010-01-20 20:59:29 +00001234
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001235unsigned clang_visitChildren(CXCursor parent,
Douglas Gregorb1373d02010-01-20 20:59:29 +00001236 CXCursorVisitor visitor,
1237 CXClientData client_data) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001238 ASTUnit *CXXUnit = getCursorASTUnit(parent);
Douglas Gregorb1373d02010-01-20 20:59:29 +00001239
1240 unsigned PCHLevel = Decl::MaxPCHLevel;
1241
1242 // Set the PCHLevel to filter out unwanted decls if requested.
1243 if (CXXUnit->getOnlyLocalDecls()) {
1244 PCHLevel = 0;
1245
1246 // If the main input was an AST, bump the level.
1247 if (CXXUnit->isMainFileAST())
1248 ++PCHLevel;
1249 }
1250
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001251 CursorVisitor CursorVis(CXXUnit, visitor, client_data, PCHLevel);
Douglas Gregorb1373d02010-01-20 20:59:29 +00001252 return CursorVis.VisitChildren(parent);
1253}
1254
Douglas Gregor78205d42010-01-20 21:45:58 +00001255static CXString getDeclSpelling(Decl *D) {
1256 NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
1257 if (!ND)
1258 return CIndexer::createCXString("");
1259
1260 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
1261 return CIndexer::createCXString(OMD->getSelector().getAsString().c_str(),
1262 true);
1263
1264 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
1265 // No, this isn't the same as the code below. getIdentifier() is non-virtual
1266 // and returns different names. NamedDecl returns the class name and
1267 // ObjCCategoryImplDecl returns the category name.
1268 return CIndexer::createCXString(CIMP->getIdentifier()->getNameStart());
1269
1270 if (ND->getIdentifier())
1271 return CIndexer::createCXString(ND->getIdentifier()->getNameStart());
1272
1273 return CIndexer::createCXString("");
1274}
1275
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001276CXString clang_getCursorSpelling(CXCursor C) {
Daniel Dunbarc81d7182010-01-18 17:52:42 +00001277 assert(getCursorDecl(C) && "CXCursor has null decl");
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001278 if (clang_isTranslationUnit(C.kind))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001279 return clang_getTranslationUnitSpelling(C.data[2]);
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001280
Steve Narofff334b4e2009-09-02 18:26:48 +00001281 if (clang_isReference(C.kind)) {
1282 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00001283 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +00001284 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
1285 return CIndexer::createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00001286 }
1287 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +00001288 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
1289 return CIndexer::createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00001290 }
1291 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +00001292 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +00001293 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenek4b333d22010-01-12 00:36:38 +00001294 return CIndexer::createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00001295 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001296 case CXCursor_TypeRef: {
1297 TypeDecl *Type = getCursorTypeRef(C).first;
1298 assert(Type && "Missing type decl");
1299
1300 return CIndexer::createCXString(
1301 getCursorContext(C).getTypeDeclType(Type).getAsString().c_str(),
1302 true);
1303 }
1304
Daniel Dunbaracca7252009-11-30 20:42:49 +00001305 default:
Ted Kremenek4b333d22010-01-12 00:36:38 +00001306 return CIndexer::createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +00001307 }
1308 }
Douglas Gregor97b98722010-01-19 23:20:36 +00001309
1310 if (clang_isExpression(C.kind)) {
1311 Decl *D = getDeclFromExpr(getCursorExpr(C));
1312 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +00001313 return getDeclSpelling(D);
Douglas Gregor97b98722010-01-19 23:20:36 +00001314 return CIndexer::createCXString("");
1315 }
1316
Douglas Gregor78205d42010-01-20 21:45:58 +00001317 return getDeclSpelling(getCursorDecl(C));
Steve Narofff334b4e2009-09-02 18:26:48 +00001318}
1319
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001320const char *clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00001321 switch (Kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00001322 case CXCursor_FunctionDecl: return "FunctionDecl";
1323 case CXCursor_TypedefDecl: return "TypedefDecl";
1324 case CXCursor_EnumDecl: return "EnumDecl";
1325 case CXCursor_EnumConstantDecl: return "EnumConstantDecl";
1326 case CXCursor_StructDecl: return "StructDecl";
1327 case CXCursor_UnionDecl: return "UnionDecl";
1328 case CXCursor_ClassDecl: return "ClassDecl";
1329 case CXCursor_FieldDecl: return "FieldDecl";
1330 case CXCursor_VarDecl: return "VarDecl";
1331 case CXCursor_ParmDecl: return "ParmDecl";
1332 case CXCursor_ObjCInterfaceDecl: return "ObjCInterfaceDecl";
1333 case CXCursor_ObjCCategoryDecl: return "ObjCCategoryDecl";
1334 case CXCursor_ObjCProtocolDecl: return "ObjCProtocolDecl";
1335 case CXCursor_ObjCPropertyDecl: return "ObjCPropertyDecl";
1336 case CXCursor_ObjCIvarDecl: return "ObjCIvarDecl";
1337 case CXCursor_ObjCInstanceMethodDecl: return "ObjCInstanceMethodDecl";
1338 case CXCursor_ObjCClassMethodDecl: return "ObjCClassMethodDecl";
Douglas Gregorb6998662010-01-19 19:34:47 +00001339 case CXCursor_ObjCImplementationDecl: return "ObjCImplementationDecl";
1340 case CXCursor_ObjCCategoryImplDecl: return "ObjCCategoryImplDecl";
Douglas Gregor30122132010-01-19 22:07:56 +00001341 case CXCursor_UnexposedDecl: return "UnexposedDecl";
Daniel Dunbaracca7252009-11-30 20:42:49 +00001342 case CXCursor_ObjCSuperClassRef: return "ObjCSuperClassRef";
1343 case CXCursor_ObjCProtocolRef: return "ObjCProtocolRef";
1344 case CXCursor_ObjCClassRef: return "ObjCClassRef";
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001345 case CXCursor_TypeRef: return "TypeRef";
Douglas Gregor97b98722010-01-19 23:20:36 +00001346 case CXCursor_UnexposedExpr: return "UnexposedExpr";
1347 case CXCursor_DeclRefExpr: return "DeclRefExpr";
1348 case CXCursor_MemberRefExpr: return "MemberRefExpr";
1349 case CXCursor_CallExpr: return "CallExpr";
1350 case CXCursor_ObjCMessageExpr: return "ObjCMessageExpr";
1351 case CXCursor_UnexposedStmt: return "UnexposedStmt";
Daniel Dunbaracca7252009-11-30 20:42:49 +00001352 case CXCursor_InvalidFile: return "InvalidFile";
1353 case CXCursor_NoDeclFound: return "NoDeclFound";
1354 case CXCursor_NotImplemented: return "NotImplemented";
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001355 case CXCursor_TranslationUnit: return "TranslationUnit";
Steve Naroff89922f82009-08-31 00:59:03 +00001356 }
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00001357
1358 llvm_unreachable("Unhandled CXCursorKind");
1359 return NULL;
Steve Naroff600866c2009-08-27 19:51:58 +00001360}
Steve Naroff89922f82009-08-31 00:59:03 +00001361
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001362enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
1363 CXCursor parent,
1364 CXClientData client_data) {
1365 CXCursor *BestCursor = static_cast<CXCursor *>(client_data);
1366 *BestCursor = cursor;
1367 return CXChildVisit_Recurse;
1368}
1369
Douglas Gregorb9790342010-01-22 21:44:22 +00001370CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
1371 if (!TU)
Ted Kremenekf4629892010-01-14 01:51:23 +00001372 return clang_getNullCursor();
Ted Kremenekf4629892010-01-14 01:51:23 +00001373
Douglas Gregorb9790342010-01-22 21:44:22 +00001374 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
1375
1376 SourceLocation SLoc = translateSourceLocation(Loc);
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001377 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
1378 if (SLoc.isValid()) {
1379 SourceRange RegionOfInterest(SLoc,
1380 CXXUnit->getPreprocessor().getLocForEndOfToken(SLoc, 1));
1381
1382 // FIXME: Would be great to have a "hint" cursor, then walk from that
1383 // hint cursor upward until we find a cursor whose source range encloses
1384 // the region of interest, rather than starting from the translation unit.
1385 CXCursor Parent = clang_getTranslationUnitCursor(CXXUnit);
1386 CursorVisitor CursorVis(CXXUnit, GetCursorVisitor, &Result,
1387 Decl::MaxPCHLevel, RegionOfInterest);
1388 CursorVis.VisitChildren(Parent);
Steve Naroff77128dd2009-09-15 20:25:34 +00001389 }
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001390 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00001391}
1392
Ted Kremenek73885552009-11-17 19:28:59 +00001393CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00001394 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00001395}
1396
1397unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00001398 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00001399}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001400
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001401unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00001402 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
1403}
1404
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001405unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +00001406 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
1407}
Steve Naroff2d4d6292009-08-31 14:26:51 +00001408
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001409unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00001410 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
1411}
1412
Douglas Gregor97b98722010-01-19 23:20:36 +00001413unsigned clang_isExpression(enum CXCursorKind K) {
1414 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
1415}
1416
1417unsigned clang_isStatement(enum CXCursorKind K) {
1418 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
1419}
1420
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001421unsigned clang_isTranslationUnit(enum CXCursorKind K) {
1422 return K == CXCursor_TranslationUnit;
1423}
1424
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001425CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00001426 return C.kind;
1427}
1428
Douglas Gregor97b98722010-01-19 23:20:36 +00001429static SourceLocation getLocationFromExpr(Expr *E) {
1430 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
1431 return /*FIXME:*/Msg->getLeftLoc();
1432 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
1433 return DRE->getLocation();
1434 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
1435 return Member->getMemberLoc();
1436 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
1437 return Ivar->getLocation();
1438 return E->getLocStart();
1439}
1440
Douglas Gregor98258af2010-01-18 22:46:11 +00001441CXSourceLocation clang_getCursorLocation(CXCursor C) {
1442 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00001443 switch (C.kind) {
1444 case CXCursor_ObjCSuperClassRef: {
1445 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1446 = getCursorObjCSuperClassRef(C);
Douglas Gregor1db19de2010-01-19 21:36:55 +00001447 return translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001448 }
1449
1450 case CXCursor_ObjCProtocolRef: {
1451 std::pair<ObjCProtocolDecl *, SourceLocation> P
1452 = getCursorObjCProtocolRef(C);
Douglas Gregor1db19de2010-01-19 21:36:55 +00001453 return translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001454 }
1455
1456 case CXCursor_ObjCClassRef: {
1457 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1458 = getCursorObjCClassRef(C);
Douglas Gregor1db19de2010-01-19 21:36:55 +00001459 return translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001460 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001461
1462 case CXCursor_TypeRef: {
1463 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
1464 return translateSourceLocation(P.first->getASTContext(), P.second);
1465 }
Douglas Gregorf46034a2010-01-18 23:41:10 +00001466
Douglas Gregorf46034a2010-01-18 23:41:10 +00001467 default:
1468 // FIXME: Need a way to enumerate all non-reference cases.
1469 llvm_unreachable("Missed a reference kind");
1470 }
Douglas Gregor98258af2010-01-18 22:46:11 +00001471 }
Douglas Gregor97b98722010-01-19 23:20:36 +00001472
1473 if (clang_isExpression(C.kind))
1474 return translateSourceLocation(getCursorContext(C),
1475 getLocationFromExpr(getCursorExpr(C)));
1476
Douglas Gregor98258af2010-01-18 22:46:11 +00001477 if (!getCursorDecl(C)) {
Douglas Gregor1db19de2010-01-19 21:36:55 +00001478 CXSourceLocation empty = { 0, 0 };
Douglas Gregor98258af2010-01-18 22:46:11 +00001479 return empty;
1480 }
1481
Douglas Gregorf46034a2010-01-18 23:41:10 +00001482 Decl *D = getCursorDecl(C);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001483 SourceLocation Loc = D->getLocation();
1484 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
1485 Loc = Class->getClassLoc();
Douglas Gregor1db19de2010-01-19 21:36:55 +00001486 return translateSourceLocation(D->getASTContext(), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00001487}
Douglas Gregora7bde202010-01-19 00:34:46 +00001488
1489CXSourceRange clang_getCursorExtent(CXCursor C) {
1490 if (clang_isReference(C.kind)) {
1491 switch (C.kind) {
1492 case CXCursor_ObjCSuperClassRef: {
1493 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1494 = getCursorObjCSuperClassRef(C);
1495 return translateSourceRange(P.first->getASTContext(), P.second);
1496 }
1497
1498 case CXCursor_ObjCProtocolRef: {
1499 std::pair<ObjCProtocolDecl *, SourceLocation> P
1500 = getCursorObjCProtocolRef(C);
1501 return translateSourceRange(P.first->getASTContext(), P.second);
1502 }
1503
1504 case CXCursor_ObjCClassRef: {
1505 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1506 = getCursorObjCClassRef(C);
1507
1508 return translateSourceRange(P.first->getASTContext(), P.second);
1509 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001510
1511 case CXCursor_TypeRef: {
1512 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
1513 return translateSourceRange(P.first->getASTContext(), P.second);
1514 }
Douglas Gregora7bde202010-01-19 00:34:46 +00001515
Douglas Gregora7bde202010-01-19 00:34:46 +00001516 default:
1517 // FIXME: Need a way to enumerate all non-reference cases.
1518 llvm_unreachable("Missed a reference kind");
1519 }
1520 }
Douglas Gregor97b98722010-01-19 23:20:36 +00001521
1522 if (clang_isExpression(C.kind))
1523 return translateSourceRange(getCursorContext(C),
1524 getCursorExpr(C)->getSourceRange());
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001525
1526 if (clang_isStatement(C.kind))
1527 return translateSourceRange(getCursorContext(C),
1528 getCursorStmt(C)->getSourceRange());
Douglas Gregora7bde202010-01-19 00:34:46 +00001529
1530 if (!getCursorDecl(C)) {
Douglas Gregor1db19de2010-01-19 21:36:55 +00001531 CXSourceRange empty = { 0, 0, 0 };
Douglas Gregora7bde202010-01-19 00:34:46 +00001532 return empty;
1533 }
1534
1535 Decl *D = getCursorDecl(C);
1536 return translateSourceRange(D->getASTContext(), D->getSourceRange());
1537}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001538
1539CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001540 if (clang_isInvalid(C.kind))
1541 return clang_getNullCursor();
1542
1543 ASTUnit *CXXUnit = getCursorASTUnit(C);
Douglas Gregorb6998662010-01-19 19:34:47 +00001544 if (clang_isDeclaration(C.kind))
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001545 return C;
Douglas Gregor98258af2010-01-18 22:46:11 +00001546
Douglas Gregor97b98722010-01-19 23:20:36 +00001547 if (clang_isExpression(C.kind)) {
1548 Decl *D = getDeclFromExpr(getCursorExpr(C));
1549 if (D)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001550 return MakeCXCursor(D, CXXUnit);
Douglas Gregor97b98722010-01-19 23:20:36 +00001551 return clang_getNullCursor();
1552 }
1553
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001554 if (!clang_isReference(C.kind))
1555 return clang_getNullCursor();
1556
1557 switch (C.kind) {
1558 case CXCursor_ObjCSuperClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001559 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, CXXUnit);
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001560
1561 case CXCursor_ObjCProtocolRef: {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001562 return MakeCXCursor(getCursorObjCProtocolRef(C).first, CXXUnit);
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001563
1564 case CXCursor_ObjCClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001565 return MakeCXCursor(getCursorObjCClassRef(C).first, CXXUnit);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001566
1567 case CXCursor_TypeRef:
1568 return MakeCXCursor(getCursorTypeRef(C).first, CXXUnit);
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001569
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001570 default:
1571 // We would prefer to enumerate all non-reference cursor kinds here.
1572 llvm_unreachable("Unhandled reference cursor kind");
1573 break;
1574 }
1575 }
1576
1577 return clang_getNullCursor();
1578}
1579
Douglas Gregorb6998662010-01-19 19:34:47 +00001580CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001581 if (clang_isInvalid(C.kind))
1582 return clang_getNullCursor();
1583
1584 ASTUnit *CXXUnit = getCursorASTUnit(C);
1585
Douglas Gregorb6998662010-01-19 19:34:47 +00001586 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00001587 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00001588 C = clang_getCursorReferenced(C);
1589 WasReference = true;
1590 }
1591
1592 if (!clang_isDeclaration(C.kind))
1593 return clang_getNullCursor();
1594
1595 Decl *D = getCursorDecl(C);
1596 if (!D)
1597 return clang_getNullCursor();
1598
1599 switch (D->getKind()) {
1600 // Declaration kinds that don't really separate the notions of
1601 // declaration and definition.
1602 case Decl::Namespace:
1603 case Decl::Typedef:
1604 case Decl::TemplateTypeParm:
1605 case Decl::EnumConstant:
1606 case Decl::Field:
1607 case Decl::ObjCIvar:
1608 case Decl::ObjCAtDefsField:
1609 case Decl::ImplicitParam:
1610 case Decl::ParmVar:
1611 case Decl::NonTypeTemplateParm:
1612 case Decl::TemplateTemplateParm:
1613 case Decl::ObjCCategoryImpl:
1614 case Decl::ObjCImplementation:
1615 case Decl::LinkageSpec:
1616 case Decl::ObjCPropertyImpl:
1617 case Decl::FileScopeAsm:
1618 case Decl::StaticAssert:
1619 case Decl::Block:
1620 return C;
1621
1622 // Declaration kinds that don't make any sense here, but are
1623 // nonetheless harmless.
1624 case Decl::TranslationUnit:
1625 case Decl::Template:
1626 case Decl::ObjCContainer:
1627 break;
1628
1629 // Declaration kinds for which the definition is not resolvable.
1630 case Decl::UnresolvedUsingTypename:
1631 case Decl::UnresolvedUsingValue:
1632 break;
1633
1634 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001635 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
1636 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001637
1638 case Decl::NamespaceAlias:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001639 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001640
1641 case Decl::Enum:
1642 case Decl::Record:
1643 case Decl::CXXRecord:
1644 case Decl::ClassTemplateSpecialization:
1645 case Decl::ClassTemplatePartialSpecialization:
1646 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition(D->getASTContext()))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001647 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001648 return clang_getNullCursor();
1649
1650 case Decl::Function:
1651 case Decl::CXXMethod:
1652 case Decl::CXXConstructor:
1653 case Decl::CXXDestructor:
1654 case Decl::CXXConversion: {
1655 const FunctionDecl *Def = 0;
1656 if (cast<FunctionDecl>(D)->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001657 return MakeCXCursor(const_cast<FunctionDecl *>(Def), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001658 return clang_getNullCursor();
1659 }
1660
1661 case Decl::Var: {
1662 VarDecl *Var = cast<VarDecl>(D);
1663
1664 // Variables with initializers have definitions.
1665 const VarDecl *Def = 0;
1666 if (Var->getDefinition(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001667 return MakeCXCursor(const_cast<VarDecl *>(Def), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001668
1669 // extern and private_extern variables are not definitions.
1670 if (Var->hasExternalStorage())
1671 return clang_getNullCursor();
1672
1673 // In-line static data members do not have definitions.
1674 if (Var->isStaticDataMember() && !Var->isOutOfLine())
1675 return clang_getNullCursor();
1676
1677 // All other variables are themselves definitions.
1678 return C;
1679 }
1680
1681 case Decl::FunctionTemplate: {
1682 const FunctionDecl *Def = 0;
1683 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001684 return MakeCXCursor(Def->getDescribedFunctionTemplate(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001685 return clang_getNullCursor();
1686 }
1687
1688 case Decl::ClassTemplate: {
1689 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
1690 ->getDefinition(D->getASTContext()))
1691 return MakeCXCursor(
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001692 cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
1693 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001694 return clang_getNullCursor();
1695 }
1696
1697 case Decl::Using: {
1698 UsingDecl *Using = cast<UsingDecl>(D);
1699 CXCursor Def = clang_getNullCursor();
1700 for (UsingDecl::shadow_iterator S = Using->shadow_begin(),
1701 SEnd = Using->shadow_end();
1702 S != SEnd; ++S) {
1703 if (Def != clang_getNullCursor()) {
1704 // FIXME: We have no way to return multiple results.
1705 return clang_getNullCursor();
1706 }
1707
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001708 Def = clang_getCursorDefinition(MakeCXCursor((*S)->getTargetDecl(),
1709 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00001710 }
1711
1712 return Def;
1713 }
1714
1715 case Decl::UsingShadow:
1716 return clang_getCursorDefinition(
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001717 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
1718 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00001719
1720 case Decl::ObjCMethod: {
1721 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
1722 if (Method->isThisDeclarationADefinition())
1723 return C;
1724
1725 // Dig out the method definition in the associated
1726 // @implementation, if we have it.
1727 // FIXME: The ASTs should make finding the definition easier.
1728 if (ObjCInterfaceDecl *Class
1729 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
1730 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
1731 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
1732 Method->isInstanceMethod()))
1733 if (Def->isThisDeclarationADefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001734 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001735
1736 return clang_getNullCursor();
1737 }
1738
1739 case Decl::ObjCCategory:
1740 if (ObjCCategoryImplDecl *Impl
1741 = cast<ObjCCategoryDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001742 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001743 return clang_getNullCursor();
1744
1745 case Decl::ObjCProtocol:
1746 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
1747 return C;
1748 return clang_getNullCursor();
1749
1750 case Decl::ObjCInterface:
1751 // There are two notions of a "definition" for an Objective-C
1752 // class: the interface and its implementation. When we resolved a
1753 // reference to an Objective-C class, produce the @interface as
1754 // the definition; when we were provided with the interface,
1755 // produce the @implementation as the definition.
1756 if (WasReference) {
1757 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
1758 return C;
1759 } else if (ObjCImplementationDecl *Impl
1760 = cast<ObjCInterfaceDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001761 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001762 return clang_getNullCursor();
1763
1764 case Decl::ObjCProperty:
1765 // FIXME: We don't really know where to find the
1766 // ObjCPropertyImplDecls that implement this property.
1767 return clang_getNullCursor();
1768
1769 case Decl::ObjCCompatibleAlias:
1770 if (ObjCInterfaceDecl *Class
1771 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
1772 if (!Class->isForwardDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001773 return MakeCXCursor(Class, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001774
1775 return clang_getNullCursor();
1776
1777 case Decl::ObjCForwardProtocol: {
1778 ObjCForwardProtocolDecl *Forward = cast<ObjCForwardProtocolDecl>(D);
1779 if (Forward->protocol_size() == 1)
1780 return clang_getCursorDefinition(
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001781 MakeCXCursor(*Forward->protocol_begin(),
1782 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00001783
1784 // FIXME: Cannot return multiple definitions.
1785 return clang_getNullCursor();
1786 }
1787
1788 case Decl::ObjCClass: {
1789 ObjCClassDecl *Class = cast<ObjCClassDecl>(D);
1790 if (Class->size() == 1) {
1791 ObjCInterfaceDecl *IFace = Class->begin()->getInterface();
1792 if (!IFace->isForwardDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001793 return MakeCXCursor(IFace, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001794 return clang_getNullCursor();
1795 }
1796
1797 // FIXME: Cannot return multiple definitions.
1798 return clang_getNullCursor();
1799 }
1800
1801 case Decl::Friend:
1802 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001803 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00001804 return clang_getNullCursor();
1805
1806 case Decl::FriendTemplate:
1807 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001808 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00001809 return clang_getNullCursor();
1810 }
1811
1812 return clang_getNullCursor();
1813}
1814
1815unsigned clang_isCursorDefinition(CXCursor C) {
1816 if (!clang_isDeclaration(C.kind))
1817 return 0;
1818
1819 return clang_getCursorDefinition(C) == C;
1820}
1821
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001822void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00001823 const char **startBuf,
1824 const char **endBuf,
1825 unsigned *startLine,
1826 unsigned *startColumn,
1827 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001828 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00001829 assert(getCursorDecl(C) && "CXCursor has null decl");
1830 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00001831 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
1832 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekfb480492010-01-13 21:46:36 +00001833
Steve Naroff4ade6d62009-09-23 17:52:52 +00001834 SourceManager &SM = FD->getASTContext().getSourceManager();
1835 *startBuf = SM.getCharacterData(Body->getLBracLoc());
1836 *endBuf = SM.getCharacterData(Body->getRBracLoc());
1837 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
1838 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
1839 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
1840 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
1841}
Ted Kremenekfb480492010-01-13 21:46:36 +00001842
1843} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00001844
Ted Kremenekfb480492010-01-13 21:46:36 +00001845//===----------------------------------------------------------------------===//
1846// CXString Operations.
1847//===----------------------------------------------------------------------===//
1848
1849extern "C" {
1850const char *clang_getCString(CXString string) {
1851 return string.Spelling;
1852}
1853
1854void clang_disposeString(CXString string) {
1855 if (string.MustFreeString && string.Spelling)
1856 free((void*)string.Spelling);
1857}
Ted Kremenek04bb7162010-01-22 22:44:15 +00001858
Ted Kremenekfb480492010-01-13 21:46:36 +00001859} // end: extern "C"
Ted Kremenek04bb7162010-01-22 22:44:15 +00001860
1861//===----------------------------------------------------------------------===//
1862// Misc. utility functions.
1863//===----------------------------------------------------------------------===//
1864
1865extern "C" {
1866
1867const char *clang_getClangVersion() {
Ted Kremeneka18f1b82010-01-23 02:11:34 +00001868 return getClangFullVersion();
Ted Kremenek04bb7162010-01-22 22:44:15 +00001869}
1870
1871} // end: extern "C"
1872