blob: 3447553ae3fd6eeb534c6723494039d08e694b1c [file] [log] [blame]
Ted Kremenekd2fa5662009-08-26 22:36:44 +00001//===- CIndex.cpp - Clang-C Source Indexing Library -----------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00007//
Ted Kremenekd2fa5662009-08-26 22:36:44 +00008//===----------------------------------------------------------------------===//
9//
Ted Kremenekab188932010-01-05 19:32:54 +000010// This file implements the main API hooks in the Clang-C Source Indexing
11// library.
Ted Kremenekd2fa5662009-08-26 22:36:44 +000012//
13//===----------------------------------------------------------------------===//
14
Ted Kremenekab188932010-01-05 19:32:54 +000015#include "CIndexer.h"
Ted Kremenek16c440a2010-01-15 20:35:54 +000016#include "CXCursor.h"
Ted Kremenekab188932010-01-05 19:32:54 +000017
Steve Naroff50398192009-08-28 15:28:48 +000018#include "clang/AST/DeclVisitor.h"
Steve Narofffb570422009-09-22 19:25:29 +000019#include "clang/AST/StmtVisitor.h"
Douglas Gregor7d0d40e2010-01-21 16:28:34 +000020#include "clang/AST/TypeLocVisitor.h"
Ted Kremenekd8210652010-01-06 23:43:31 +000021#include "clang/Lex/Lexer.h"
Douglas Gregor33e9abd2010-01-22 19:49:59 +000022#include "clang/Lex/Preprocessor.h"
Douglas Gregor02465752009-10-16 21:24:31 +000023#include "llvm/Support/MemoryBuffer.h"
Benjamin Kramer0829a832009-10-18 11:19:36 +000024#include "llvm/System/Program.h"
Ted Kremenekfc062212009-10-19 21:44:57 +000025
Ted Kremenekdb3d0da2010-01-05 20:55:39 +000026// Needed to define L_TMPNAM on some systems.
27#include <cstdio>
28
Steve Naroff50398192009-08-28 15:28:48 +000029using namespace clang;
Ted Kremenek16c440a2010-01-15 20:35:54 +000030using namespace clang::cxcursor;
Steve Naroff50398192009-08-28 15:28:48 +000031using namespace idx;
32
Ted Kremenek8a8da7d2010-01-06 03:42:32 +000033//===----------------------------------------------------------------------===//
34// Crash Reporting.
35//===----------------------------------------------------------------------===//
36
37#ifdef __APPLE__
Ted Kremenek29b72842010-01-07 22:49:05 +000038#ifndef NDEBUG
39#define USE_CRASHTRACER
Ted Kremenek8a8da7d2010-01-06 03:42:32 +000040#include "clang/Analysis/Support/SaveAndRestore.h"
41// Integrate with crash reporter.
42extern "C" const char *__crashreporter_info__;
Ted Kremenek29b72842010-01-07 22:49:05 +000043#define NUM_CRASH_STRINGS 16
44static unsigned crashtracer_counter = 0;
Ted Kremenek254ba7c2010-01-07 23:13:53 +000045static unsigned crashtracer_counter_id[NUM_CRASH_STRINGS] = { 0 };
Ted Kremenek29b72842010-01-07 22:49:05 +000046static const char *crashtracer_strings[NUM_CRASH_STRINGS] = { 0 };
47static const char *agg_crashtracer_strings[NUM_CRASH_STRINGS] = { 0 };
48
49static unsigned SetCrashTracerInfo(const char *str,
50 llvm::SmallString<1024> &AggStr) {
51
Ted Kremenek254ba7c2010-01-07 23:13:53 +000052 unsigned slot = 0;
Ted Kremenek29b72842010-01-07 22:49:05 +000053 while (crashtracer_strings[slot]) {
54 if (++slot == NUM_CRASH_STRINGS)
55 slot = 0;
56 }
57 crashtracer_strings[slot] = str;
Ted Kremenek254ba7c2010-01-07 23:13:53 +000058 crashtracer_counter_id[slot] = ++crashtracer_counter;
Ted Kremenek29b72842010-01-07 22:49:05 +000059
60 // We need to create an aggregate string because multiple threads
61 // may be in this method at one time. The crash reporter string
62 // will attempt to overapproximate the set of in-flight invocations
63 // of this function. Race conditions can still cause this goal
64 // to not be achieved.
65 {
66 llvm::raw_svector_ostream Out(AggStr);
67 for (unsigned i = 0; i < NUM_CRASH_STRINGS; ++i)
68 if (crashtracer_strings[i]) Out << crashtracer_strings[i] << '\n';
69 }
70 __crashreporter_info__ = agg_crashtracer_strings[slot] = AggStr.c_str();
71 return slot;
72}
73
74static void ResetCrashTracerInfo(unsigned slot) {
Ted Kremenek254ba7c2010-01-07 23:13:53 +000075 unsigned max_slot = 0;
76 unsigned max_value = 0;
77
78 crashtracer_strings[slot] = agg_crashtracer_strings[slot] = 0;
79
80 for (unsigned i = 0 ; i < NUM_CRASH_STRINGS; ++i)
81 if (agg_crashtracer_strings[i] &&
82 crashtracer_counter_id[i] > max_value) {
83 max_slot = i;
84 max_value = crashtracer_counter_id[i];
Ted Kremenek29b72842010-01-07 22:49:05 +000085 }
Ted Kremenek254ba7c2010-01-07 23:13:53 +000086
87 __crashreporter_info__ = agg_crashtracer_strings[max_slot];
Ted Kremenek29b72842010-01-07 22:49:05 +000088}
89
90namespace {
91class ArgsCrashTracerInfo {
92 llvm::SmallString<1024> CrashString;
93 llvm::SmallString<1024> AggregateString;
94 unsigned crashtracerSlot;
95public:
96 ArgsCrashTracerInfo(llvm::SmallVectorImpl<const char*> &Args)
97 : crashtracerSlot(0)
98 {
99 {
100 llvm::raw_svector_ostream Out(CrashString);
101 Out << "ClangCIndex [createTranslationUnitFromSourceFile]: clang";
102 for (llvm::SmallVectorImpl<const char*>::iterator I=Args.begin(),
103 E=Args.end(); I!=E; ++I)
104 Out << ' ' << *I;
105 }
106 crashtracerSlot = SetCrashTracerInfo(CrashString.c_str(),
107 AggregateString);
108 }
109
110 ~ArgsCrashTracerInfo() {
111 ResetCrashTracerInfo(crashtracerSlot);
112 }
113};
114}
115#endif
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000116#endif
117
Douglas Gregor1db19de2010-01-19 21:36:55 +0000118typedef llvm::PointerIntPair<ASTContext *, 1, bool> CXSourceLocationPtr;
119
Douglas Gregor98258af2010-01-18 22:46:11 +0000120/// \brief Translate a Clang source location into a CIndex source location.
Douglas Gregor1db19de2010-01-19 21:36:55 +0000121static CXSourceLocation translateSourceLocation(ASTContext &Context,
122 SourceLocation Loc,
123 bool AtEnd = false) {
124 CXSourceLocationPtr Ptr(&Context, AtEnd);
125 CXSourceLocation Result = { Ptr.getOpaqueValue(), Loc.getRawEncoding() };
126 return Result;
Douglas Gregor98258af2010-01-18 22:46:11 +0000127}
128
Douglas Gregora7bde202010-01-19 00:34:46 +0000129/// \brief Translate a Clang source range into a CIndex source range.
Douglas Gregor1db19de2010-01-19 21:36:55 +0000130static CXSourceRange translateSourceRange(ASTContext &Context, SourceRange R) {
131 CXSourceRange Result = { &Context,
132 R.getBegin().getRawEncoding(),
133 R.getEnd().getRawEncoding() };
134 return Result;
Douglas Gregora7bde202010-01-19 00:34:46 +0000135}
136
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000137static SourceRange translateSourceRange(CXSourceRange R) {
138 return SourceRange(SourceLocation::getFromRawEncoding(R.begin_int_data),
139 SourceLocation::getFromRawEncoding(R.end_int_data));
140}
141
142/// \brief The result of comparing two source ranges.
143enum RangeComparisonResult {
144 /// \brief Either the ranges overlap or one of the ranges is invalid.
145 RangeOverlap,
146
147 /// \brief The first range ends before the second range starts.
148 RangeBefore,
149
150 /// \brief The first range starts after the second range ends.
151 RangeAfter
152};
153
154/// \brief Compare two source ranges to determine their relative position in
155/// the translation unit.
156static RangeComparisonResult RangeCompare(SourceManager &SM,
157 SourceRange R1,
158 SourceRange R2) {
159 assert(R1.isValid() && "First range is invalid?");
160 assert(R2.isValid() && "Second range is invalid?");
161 if (SM.isBeforeInTranslationUnit(R1.getEnd(), R2.getBegin()))
162 return RangeBefore;
163 if (SM.isBeforeInTranslationUnit(R2.getEnd(), R1.getBegin()))
164 return RangeAfter;
165 return RangeOverlap;
166}
167
Douglas Gregor1db19de2010-01-19 21:36:55 +0000168
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000169//===----------------------------------------------------------------------===//
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000170// Cursor visitor.
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000171//===----------------------------------------------------------------------===//
172
Steve Naroff89922f82009-08-31 00:59:03 +0000173namespace {
Ted Kremenekedc8aa62010-01-16 00:36:30 +0000174
Douglas Gregorb1373d02010-01-20 20:59:29 +0000175// Cursor visitor.
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000176class CursorVisitor : public DeclVisitor<CursorVisitor, bool>,
Douglas Gregora59e3902010-01-21 23:27:09 +0000177 public TypeLocVisitor<CursorVisitor, bool>,
178 public StmtVisitor<CursorVisitor, bool>
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000179{
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000180 /// \brief The translation unit we are traversing.
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000181 ASTUnit *TU;
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000182
183 /// \brief The parent cursor whose children we are traversing.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000184 CXCursor Parent;
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000185
186 /// \brief The declaration that serves at the parent of any statement or
187 /// expression nodes.
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000188 Decl *StmtParent;
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000189
190 /// \brief The visitor function.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000191 CXCursorVisitor Visitor;
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000192
193 /// \brief The opaque client data, to be passed along to the visitor.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000194 CXClientData ClientData;
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000195
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000196 // MaxPCHLevel - the maximum PCH level of declarations that we will pass on
197 // to the visitor. Declarations with a PCH level greater than this value will
198 // be suppressed.
199 unsigned MaxPCHLevel;
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000200
201 /// \brief When valid, a source range to which the cursor should restrict
202 /// its search.
203 SourceRange RegionOfInterest;
204
Douglas Gregorb1373d02010-01-20 20:59:29 +0000205 using DeclVisitor<CursorVisitor, bool>::Visit;
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000206 using TypeLocVisitor<CursorVisitor, bool>::Visit;
Douglas Gregora59e3902010-01-21 23:27:09 +0000207 using StmtVisitor<CursorVisitor, bool>::Visit;
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000208
209 /// \brief Determine whether this particular source range comes before, comes
210 /// after, or overlaps the region of interest.
211 ///
212 /// \param R a source range retrieved from the abstract syntax tree.
213 RangeComparisonResult CompareRegionOfInterest(SourceRange R);
214
215 /// \brief Determine whether this particular source range comes before, comes
216 /// after, or overlaps the region of interest.
217 ///
218 /// \param CXR a source range retrieved from a cursor.
219 RangeComparisonResult CompareRegionOfInterest(CXSourceRange CXR);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000220
Steve Naroff89922f82009-08-31 00:59:03 +0000221public:
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000222 CursorVisitor(ASTUnit *TU, CXCursorVisitor Visitor, CXClientData ClientData,
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000223 unsigned MaxPCHLevel,
224 SourceRange RegionOfInterest = SourceRange())
225 : TU(TU), Visitor(Visitor), ClientData(ClientData),
226 MaxPCHLevel(MaxPCHLevel), RegionOfInterest(RegionOfInterest)
Douglas Gregorb1373d02010-01-20 20:59:29 +0000227 {
228 Parent.kind = CXCursor_NoDeclFound;
229 Parent.data[0] = 0;
230 Parent.data[1] = 0;
231 Parent.data[2] = 0;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000232 StmtParent = 0;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000233 }
234
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000235 bool Visit(CXCursor Cursor, bool CheckedRegionOfInterest = false);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000236 bool VisitChildren(CXCursor Parent);
237
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000238 // Declaration visitors
Douglas Gregorb1373d02010-01-20 20:59:29 +0000239 bool VisitDeclContext(DeclContext *DC);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000240 bool VisitTranslationUnitDecl(TranslationUnitDecl *D);
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000241 bool VisitTypedefDecl(TypedefDecl *D);
242 bool VisitTagDecl(TagDecl *D);
243 bool VisitEnumConstantDecl(EnumConstantDecl *D);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000244 bool VisitDeclaratorDecl(DeclaratorDecl *DD);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000245 bool VisitFunctionDecl(FunctionDecl *ND);
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000246 bool VisitFieldDecl(FieldDecl *D);
247 bool VisitVarDecl(VarDecl *);
248 bool VisitObjCMethodDecl(ObjCMethodDecl *ND);
Douglas Gregora59e3902010-01-21 23:27:09 +0000249 bool VisitObjCContainerDecl(ObjCContainerDecl *D);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000250 bool VisitObjCCategoryDecl(ObjCCategoryDecl *ND);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000251 bool VisitObjCProtocolDecl(ObjCProtocolDecl *PID);
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000252 bool VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
253 bool VisitObjCImplDecl(ObjCImplDecl *D);
254 bool VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
255 bool VisitObjCImplementationDecl(ObjCImplementationDecl *D);
256 // FIXME: ObjCPropertyDecl requires TypeSourceInfo, getter/setter locations,
257 // etc.
258 // FIXME: ObjCCompatibleAliasDecl requires aliased-class locations.
259 bool VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D);
260 bool VisitObjCClassDecl(ObjCClassDecl *D);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000261
262 // Type visitors
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000263 // FIXME: QualifiedTypeLoc doesn't provide any location information
264 bool VisitBuiltinTypeLoc(BuiltinTypeLoc TL);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000265 bool VisitTypedefTypeLoc(TypedefTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000266 bool VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL);
267 bool VisitTagTypeLoc(TagTypeLoc TL);
268 // FIXME: TemplateTypeParmTypeLoc doesn't provide any location information
269 bool VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL);
270 bool VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL);
271 bool VisitPointerTypeLoc(PointerTypeLoc TL);
272 bool VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL);
273 bool VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL);
274 bool VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL);
275 bool VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL);
276 bool VisitFunctionTypeLoc(FunctionTypeLoc TL);
277 bool VisitArrayTypeLoc(ArrayTypeLoc TL);
Douglas Gregor2332c112010-01-21 20:48:56 +0000278 // FIXME: Implement for TemplateSpecializationTypeLoc
279 // FIXME: Implement visitors here when the unimplemented TypeLocs get
280 // implemented
281 bool VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL);
282 bool VisitTypeOfTypeLoc(TypeOfTypeLoc TL);
Douglas Gregora59e3902010-01-21 23:27:09 +0000283
284 // Statement visitors
285 bool VisitStmt(Stmt *S);
286 bool VisitDeclStmt(DeclStmt *S);
Douglas Gregorf5bab412010-01-22 01:00:11 +0000287 // FIXME: LabelStmt label?
288 bool VisitIfStmt(IfStmt *S);
289 bool VisitSwitchStmt(SwitchStmt *S);
Steve Naroff89922f82009-08-31 00:59:03 +0000290};
Douglas Gregorb1373d02010-01-20 20:59:29 +0000291
Ted Kremenekab188932010-01-05 19:32:54 +0000292} // end anonymous namespace
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000293
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000294RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
295 assert(RegionOfInterest.isValid() && "RangeCompare called with invalid range");
296 if (R.isInvalid())
297 return RangeOverlap;
298
299 // Move the end of the input range to the end of the last token in that
300 // range.
301 R.setEnd(TU->getPreprocessor().getLocForEndOfToken(R.getEnd(), 1));
302 return RangeCompare(TU->getSourceManager(), R, RegionOfInterest);
303}
304
305RangeComparisonResult CursorVisitor::CompareRegionOfInterest(CXSourceRange CXR) {
306 return CompareRegionOfInterest(translateSourceRange(CXR));
307}
308
Douglas Gregorb1373d02010-01-20 20:59:29 +0000309/// \brief Visit the given cursor and, if requested by the visitor,
310/// its children.
311///
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000312/// \param Cursor the cursor to visit.
313///
314/// \param CheckRegionOfInterest if true, then the caller already checked that
315/// this cursor is within the region of interest.
316///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000317/// \returns true if the visitation should be aborted, false if it
318/// should continue.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000319bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
Douglas Gregorb1373d02010-01-20 20:59:29 +0000320 if (clang_isInvalid(Cursor.kind))
321 return false;
322
323 if (clang_isDeclaration(Cursor.kind)) {
324 Decl *D = getCursorDecl(Cursor);
325 assert(D && "Invalid declaration cursor");
326 if (D->getPCHLevel() > MaxPCHLevel)
327 return false;
328
329 if (D->isImplicit())
330 return false;
331 }
332
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000333 // If we have a range of interest, and this cursor doesn't intersect with it,
334 // we're done.
335 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
336 CXSourceRange Range = clang_getCursorExtent(Cursor);
337 if (translateSourceRange(Range).isInvalid() ||
338 CompareRegionOfInterest(Range))
339 return false;
340 }
341
Douglas Gregorb1373d02010-01-20 20:59:29 +0000342 switch (Visitor(Cursor, Parent, ClientData)) {
343 case CXChildVisit_Break:
344 return true;
345
346 case CXChildVisit_Continue:
347 return false;
348
349 case CXChildVisit_Recurse:
350 return VisitChildren(Cursor);
351 }
352
353 llvm_unreachable("Silly GCC, we can't get here");
354}
355
356/// \brief Visit the children of the given cursor.
357///
358/// \returns true if the visitation should be aborted, false if it
359/// should continue.
360bool CursorVisitor::VisitChildren(CXCursor Cursor) {
Douglas Gregora59e3902010-01-21 23:27:09 +0000361 if (clang_isReference(Cursor.kind)) {
362 // By definition, references have no children.
363 return false;
364 }
365
Douglas Gregorb1373d02010-01-20 20:59:29 +0000366 // Set the Parent field to Cursor, then back to its old value once we're
367 // done.
368 class SetParentRAII {
369 CXCursor &Parent;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000370 Decl *&StmtParent;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000371 CXCursor OldParent;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000372
Douglas Gregorb1373d02010-01-20 20:59:29 +0000373 public:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000374 SetParentRAII(CXCursor &Parent, Decl *&StmtParent, CXCursor NewParent)
375 : Parent(Parent), StmtParent(StmtParent), OldParent(Parent)
Douglas Gregorb1373d02010-01-20 20:59:29 +0000376 {
377 Parent = NewParent;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000378 if (clang_isDeclaration(Parent.kind))
379 StmtParent = getCursorDecl(Parent);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000380 }
381
382 ~SetParentRAII() {
383 Parent = OldParent;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000384 if (clang_isDeclaration(Parent.kind))
385 StmtParent = getCursorDecl(Parent);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000386 }
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000387 } SetParent(Parent, StmtParent, Cursor);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000388
389 if (clang_isDeclaration(Cursor.kind)) {
390 Decl *D = getCursorDecl(Cursor);
391 assert(D && "Invalid declaration cursor");
392 return Visit(D);
393 }
394
Douglas Gregora59e3902010-01-21 23:27:09 +0000395 if (clang_isStatement(Cursor.kind))
396 return Visit(getCursorStmt(Cursor));
397 if (clang_isExpression(Cursor.kind))
398 return Visit(getCursorExpr(Cursor));
399
Douglas Gregorb1373d02010-01-20 20:59:29 +0000400 if (clang_isTranslationUnit(Cursor.kind)) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000401 ASTUnit *CXXUnit = getCursorASTUnit(Cursor);
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000402 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
403 RegionOfInterest.isInvalid()) {
Douglas Gregor7b691f332010-01-20 21:13:59 +0000404 const std::vector<Decl*> &TLDs = CXXUnit->getTopLevelDecls();
405 for (std::vector<Decl*>::const_iterator it = TLDs.begin(),
406 ie = TLDs.end(); it != ie; ++it) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000407 if (Visit(MakeCXCursor(*it, CXXUnit), true))
Douglas Gregor7b691f332010-01-20 21:13:59 +0000408 return true;
409 }
410 } else {
411 return VisitDeclContext(
Douglas Gregorb1373d02010-01-20 20:59:29 +0000412 CXXUnit->getASTContext().getTranslationUnitDecl());
Douglas Gregor7b691f332010-01-20 21:13:59 +0000413 }
414
415 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000416 }
Douglas Gregora59e3902010-01-21 23:27:09 +0000417
Douglas Gregorb1373d02010-01-20 20:59:29 +0000418 // Nothing to visit at the moment.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000419 return false;
420}
421
Douglas Gregorb1373d02010-01-20 20:59:29 +0000422bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000423 for (DeclContext::decl_iterator
Douglas Gregorb1373d02010-01-20 20:59:29 +0000424 I = DC->decls_begin(), E = DC->decls_end(); I != E; ++I) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000425 if (RegionOfInterest.isValid()) {
426 SourceRange R = (*I)->getSourceRange();
427 if (R.isInvalid())
428 continue;
429
430 switch (CompareRegionOfInterest(R)) {
431 case RangeBefore:
432 // This declaration comes before the region of interest; skip it.
433 continue;
434
435 case RangeAfter:
436 // This declaration comes after the region of interest; we're done.
437 return false;
438
439 case RangeOverlap:
440 // This declaration overlaps the region of interest; visit it.
441 break;
442 }
443 }
444
445 if (Visit(MakeCXCursor(*I, TU), true))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000446 return true;
447 }
448
449 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000450}
451
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000452bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
453 llvm_unreachable("Translation units are visited directly by Visit()");
454 return false;
455}
456
457bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
458 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
459 return Visit(TSInfo->getTypeLoc());
460
461 return false;
462}
463
464bool CursorVisitor::VisitTagDecl(TagDecl *D) {
465 return VisitDeclContext(D);
466}
467
468bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
469 if (Expr *Init = D->getInitExpr())
470 return Visit(MakeCXCursor(Init, StmtParent, TU));
471 return false;
472}
473
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000474bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
475 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
476 if (Visit(TSInfo->getTypeLoc()))
477 return true;
478
479 return false;
480}
481
Douglas Gregorb1373d02010-01-20 20:59:29 +0000482bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000483 if (VisitDeclaratorDecl(ND))
484 return true;
485
Douglas Gregora59e3902010-01-21 23:27:09 +0000486 if (ND->isThisDeclarationADefinition() &&
487 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
488 return true;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000489
490 return false;
491}
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000492
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000493bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
494 if (VisitDeclaratorDecl(D))
495 return true;
496
497 if (Expr *BitWidth = D->getBitWidth())
498 return Visit(MakeCXCursor(BitWidth, StmtParent, TU));
499
500 return false;
501}
502
503bool CursorVisitor::VisitVarDecl(VarDecl *D) {
504 if (VisitDeclaratorDecl(D))
505 return true;
506
507 if (Expr *Init = D->getInit())
508 return Visit(MakeCXCursor(Init, StmtParent, TU));
509
510 return false;
511}
512
513bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
514 // FIXME: We really need a TypeLoc covering Objective-C method declarations.
515 // At the moment, we don't have information about locations in the return
516 // type.
517 for (ObjCMethodDecl::param_iterator P = ND->param_begin(),
518 PEnd = ND->param_end();
519 P != PEnd; ++P) {
520 if (Visit(MakeCXCursor(*P, TU)))
521 return true;
522 }
523
524 if (ND->isThisDeclarationADefinition() &&
525 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
526 return true;
527
528 return false;
529}
530
Douglas Gregora59e3902010-01-21 23:27:09 +0000531bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
532 return VisitDeclContext(D);
533}
534
Douglas Gregorb1373d02010-01-20 20:59:29 +0000535bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000536 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
537 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000538 return true;
539
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000540 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
541 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
542 E = ND->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000543 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000544 return true;
545
Douglas Gregora59e3902010-01-21 23:27:09 +0000546 return VisitObjCContainerDecl(ND);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000547}
548
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000549bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
550 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
551 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
552 E = PID->protocol_end(); I != E; ++I, ++PL)
553 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
554 return true;
555
556 return VisitObjCContainerDecl(PID);
557}
558
Douglas Gregorb1373d02010-01-20 20:59:29 +0000559bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000560 // Issue callbacks for super class.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000561 if (D->getSuperClass() &&
562 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000563 D->getSuperClassLoc(),
564 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000565 return true;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000566
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000567 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
568 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
569 E = D->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000570 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000571 return true;
572
Douglas Gregora59e3902010-01-21 23:27:09 +0000573 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000574}
575
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000576bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
577 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000578}
579
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000580bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
581 if (Visit(MakeCursorObjCClassRef(D->getCategoryDecl()->getClassInterface(),
582 D->getLocation(), TU)))
583 return true;
584
585 return VisitObjCImplDecl(D);
586}
587
588bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
589#if 0
590 // Issue callbacks for super class.
591 // FIXME: No source location information!
592 if (D->getSuperClass() &&
593 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
594 D->getSuperClassLoc(),
595 TU)))
596 return true;
597#endif
598
599 return VisitObjCImplDecl(D);
600}
601
602bool CursorVisitor::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D) {
603 ObjCForwardProtocolDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
604 for (ObjCForwardProtocolDecl::protocol_iterator I = D->protocol_begin(),
605 E = D->protocol_end();
606 I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000607 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000608 return true;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000609
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000610 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000611}
612
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000613bool CursorVisitor::VisitObjCClassDecl(ObjCClassDecl *D) {
614 for (ObjCClassDecl::iterator C = D->begin(), CEnd = D->end(); C != CEnd; ++C)
615 if (Visit(MakeCursorObjCClassRef(C->getInterface(), C->getLocation(), TU)))
616 return true;
617
618 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000619}
620
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000621bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
622 ASTContext &Context = TU->getASTContext();
623
624 // Some builtin types (such as Objective-C's "id", "sel", and
625 // "Class") have associated declarations. Create cursors for those.
626 QualType VisitType;
627 switch (TL.getType()->getAs<BuiltinType>()->getKind()) {
628 case BuiltinType::Void:
629 case BuiltinType::Bool:
630 case BuiltinType::Char_U:
631 case BuiltinType::UChar:
632 case BuiltinType::Char16:
633 case BuiltinType::Char32:
634 case BuiltinType::UShort:
635 case BuiltinType::UInt:
636 case BuiltinType::ULong:
637 case BuiltinType::ULongLong:
638 case BuiltinType::UInt128:
639 case BuiltinType::Char_S:
640 case BuiltinType::SChar:
641 case BuiltinType::WChar:
642 case BuiltinType::Short:
643 case BuiltinType::Int:
644 case BuiltinType::Long:
645 case BuiltinType::LongLong:
646 case BuiltinType::Int128:
647 case BuiltinType::Float:
648 case BuiltinType::Double:
649 case BuiltinType::LongDouble:
650 case BuiltinType::NullPtr:
651 case BuiltinType::Overload:
652 case BuiltinType::Dependent:
653 break;
654
655 case BuiltinType::UndeducedAuto: // FIXME: Deserves a cursor?
656 break;
657
658 case BuiltinType::ObjCId:
659 VisitType = Context.getObjCIdType();
660 break;
661
662 case BuiltinType::ObjCClass:
663 VisitType = Context.getObjCClassType();
664 break;
665
666 case BuiltinType::ObjCSel:
667 VisitType = Context.getObjCSelType();
668 break;
669 }
670
671 if (!VisitType.isNull()) {
672 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
673 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
674 TU));
675 }
676
677 return false;
678}
679
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000680bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
681 return Visit(MakeCursorTypeRef(TL.getTypedefDecl(), TL.getNameLoc(), TU));
682}
683
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000684bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
685 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
686}
687
688bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
689 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
690}
691
692bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
693 if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
694 return true;
695
696 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
697 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
698 TU)))
699 return true;
700 }
701
702 return false;
703}
704
705bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
706 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseTypeLoc()))
707 return true;
708
709 if (TL.hasProtocolsAsWritten()) {
710 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
711 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I),
712 TL.getProtocolLoc(I),
713 TU)))
714 return true;
715 }
716 }
717
718 return false;
719}
720
721bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
722 return Visit(TL.getPointeeLoc());
723}
724
725bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
726 return Visit(TL.getPointeeLoc());
727}
728
729bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
730 return Visit(TL.getPointeeLoc());
731}
732
733bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
734 return Visit(TL.getPointeeLoc());
735}
736
737bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
738 return Visit(TL.getPointeeLoc());
739}
740
741bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
742 if (Visit(TL.getResultLoc()))
743 return true;
744
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000745 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
746 if (Visit(MakeCXCursor(TL.getArg(I), TU)))
747 return true;
748
749 return false;
750}
751
752bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
753 if (Visit(TL.getElementLoc()))
754 return true;
755
756 if (Expr *Size = TL.getSizeExpr())
757 return Visit(MakeCXCursor(Size, StmtParent, TU));
758
759 return false;
760}
761
Douglas Gregor2332c112010-01-21 20:48:56 +0000762bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
763 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
764}
765
766bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
767 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
768 return Visit(TSInfo->getTypeLoc());
769
770 return false;
771}
772
Douglas Gregora59e3902010-01-21 23:27:09 +0000773bool CursorVisitor::VisitStmt(Stmt *S) {
774 for (Stmt::child_iterator Child = S->child_begin(), ChildEnd = S->child_end();
775 Child != ChildEnd; ++Child) {
776 if (Visit(MakeCXCursor(*Child, StmtParent, TU)))
777 return true;
778 }
779
780 return false;
781}
782
783bool CursorVisitor::VisitDeclStmt(DeclStmt *S) {
784 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
785 D != DEnd; ++D) {
786 if (Visit(MakeCXCursor(*D, TU)))
787 return true;
788 }
789
790 return false;
791}
792
Douglas Gregorf5bab412010-01-22 01:00:11 +0000793bool CursorVisitor::VisitIfStmt(IfStmt *S) {
794 if (VarDecl *Var = S->getConditionVariable()) {
795 if (Visit(MakeCXCursor(Var, TU)))
796 return true;
797 } else if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
798 return true;
799
800 if (S->getThen() && Visit(MakeCXCursor(S->getThen(), StmtParent, TU)))
801 return true;
802
803 if (S->getElse() && Visit(MakeCXCursor(S->getElse(), StmtParent, TU)))
804 return true;
805
806 return false;
807}
808
809bool CursorVisitor::VisitSwitchStmt(SwitchStmt *S) {
810 if (VarDecl *Var = S->getConditionVariable()) {
811 if (Visit(MakeCXCursor(Var, TU)))
812 return true;
813 } else if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
814 return true;
815
816 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
817 return true;
818
819 return false;
820}
821
Daniel Dunbar140fce22010-01-12 02:34:07 +0000822CXString CIndexer::createCXString(const char *String, bool DupString){
Benjamin Kramer62cf3222009-11-09 19:13:48 +0000823 CXString Str;
824 if (DupString) {
825 Str.Spelling = strdup(String);
826 Str.MustFreeString = 1;
827 } else {
828 Str.Spelling = String;
829 Str.MustFreeString = 0;
830 }
831 return Str;
832}
833
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000834extern "C" {
Steve Naroffe56b4ba2009-10-20 14:46:24 +0000835CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000836 int displayDiagnostics) {
Steve Naroffe56b4ba2009-10-20 14:46:24 +0000837 CIndexer *CIdxr = new CIndexer(new Program());
838 if (excludeDeclarationsFromPCH)
839 CIdxr->setOnlyLocalDecls();
840 if (displayDiagnostics)
841 CIdxr->setDisplayDiagnostics();
842 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +0000843}
844
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000845void clang_disposeIndex(CXIndex CIdx) {
Steve Naroff2bd6b9f2009-09-17 18:33:27 +0000846 assert(CIdx && "Passed null CXIndex");
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000847 delete static_cast<CIndexer *>(CIdx);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +0000848}
849
Daniel Dunbar8506dde2009-12-03 01:54:28 +0000850void clang_setUseExternalASTGeneration(CXIndex CIdx, int value) {
851 assert(CIdx && "Passed null CXIndex");
852 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
853 CXXIdx->setUseExternalASTGeneration(value);
854}
855
Steve Naroff50398192009-08-28 15:28:48 +0000856// FIXME: need to pass back error info.
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000857CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
858 const char *ast_filename) {
Steve Naroff50398192009-08-28 15:28:48 +0000859 assert(CIdx && "Passed null CXIndex");
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000860 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000861
Daniel Dunbar5262fda2009-12-03 01:45:44 +0000862 return ASTUnit::LoadFromPCHFile(ast_filename, CXXIdx->getDiags(),
863 CXXIdx->getOnlyLocalDecls(),
864 /* UseBumpAllocator = */ true);
Steve Naroff600866c2009-08-27 19:51:58 +0000865}
866
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000867CXTranslationUnit
868clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
869 const char *source_filename,
870 int num_command_line_args,
871 const char **command_line_args) {
Steve Naroffe56b4ba2009-10-20 14:46:24 +0000872 assert(CIdx && "Passed null CXIndex");
873 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
874
Daniel Dunbar8506dde2009-12-03 01:54:28 +0000875 if (!CXXIdx->getUseExternalASTGeneration()) {
876 llvm::SmallVector<const char *, 16> Args;
877
878 // The 'source_filename' argument is optional. If the caller does not
879 // specify it then it is assumed that the source file is specified
880 // in the actual argument list.
881 if (source_filename)
882 Args.push_back(source_filename);
883 Args.insert(Args.end(), command_line_args,
884 command_line_args + num_command_line_args);
885
Daniel Dunbar94220972009-12-05 02:17:18 +0000886 unsigned NumErrors = CXXIdx->getDiags().getNumErrors();
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000887
Ted Kremenek29b72842010-01-07 22:49:05 +0000888#ifdef USE_CRASHTRACER
889 ArgsCrashTracerInfo ACTI(Args);
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000890#endif
891
Daniel Dunbar94220972009-12-05 02:17:18 +0000892 llvm::OwningPtr<ASTUnit> Unit(
893 ASTUnit::LoadFromCommandLine(Args.data(), Args.data() + Args.size(),
Daniel Dunbar869824e2009-12-13 03:46:13 +0000894 CXXIdx->getDiags(),
895 CXXIdx->getClangResourcesPath(),
Daniel Dunbar94220972009-12-05 02:17:18 +0000896 CXXIdx->getOnlyLocalDecls(),
897 /* UseBumpAllocator = */ true));
Ted Kremenek29b72842010-01-07 22:49:05 +0000898
Daniel Dunbar94220972009-12-05 02:17:18 +0000899 // FIXME: Until we have broader testing, just drop the entire AST if we
900 // encountered an error.
901 if (NumErrors != CXXIdx->getDiags().getNumErrors())
902 return 0;
903
904 return Unit.take();
Daniel Dunbar8506dde2009-12-03 01:54:28 +0000905 }
906
Ted Kremenek139ba862009-10-22 00:03:57 +0000907 // Build up the arguments for invoking 'clang'.
Ted Kremenek74cd0692009-10-15 23:21:22 +0000908 std::vector<const char *> argv;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000909
Ted Kremenek139ba862009-10-22 00:03:57 +0000910 // First add the complete path to the 'clang' executable.
911 llvm::sys::Path ClangPath = static_cast<CIndexer *>(CIdx)->getClangPath();
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000912 argv.push_back(ClangPath.c_str());
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000913
Ted Kremenek139ba862009-10-22 00:03:57 +0000914 // Add the '-emit-ast' option as our execution mode for 'clang'.
Ted Kremenek74cd0692009-10-15 23:21:22 +0000915 argv.push_back("-emit-ast");
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000916
Ted Kremenek139ba862009-10-22 00:03:57 +0000917 // The 'source_filename' argument is optional. If the caller does not
918 // specify it then it is assumed that the source file is specified
919 // in the actual argument list.
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000920 if (source_filename)
921 argv.push_back(source_filename);
Ted Kremenek139ba862009-10-22 00:03:57 +0000922
Steve Naroff37b5ac22009-10-15 20:50:09 +0000923 // Generate a temporary name for the AST file.
Ted Kremenek139ba862009-10-22 00:03:57 +0000924 argv.push_back("-o");
Steve Naroff37b5ac22009-10-15 20:50:09 +0000925 char astTmpFile[L_tmpnam];
Ted Kremenek74cd0692009-10-15 23:21:22 +0000926 argv.push_back(tmpnam(astTmpFile));
Ted Kremenek139ba862009-10-22 00:03:57 +0000927
928 // Process the compiler options, stripping off '-o', '-c', '-fsyntax-only'.
929 for (int i = 0; i < num_command_line_args; ++i)
930 if (const char *arg = command_line_args[i]) {
931 if (strcmp(arg, "-o") == 0) {
932 ++i; // Also skip the matching argument.
933 continue;
934 }
935 if (strcmp(arg, "-emit-ast") == 0 ||
936 strcmp(arg, "-c") == 0 ||
937 strcmp(arg, "-fsyntax-only") == 0) {
938 continue;
939 }
940
941 // Keep the argument.
942 argv.push_back(arg);
Steve Naroffe56b4ba2009-10-20 14:46:24 +0000943 }
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000944
Ted Kremenek139ba862009-10-22 00:03:57 +0000945 // Add the null terminator.
Ted Kremenek74cd0692009-10-15 23:21:22 +0000946 argv.push_back(NULL);
947
Ted Kremenekfeb15e32009-10-26 22:14:08 +0000948 // Invoke 'clang'.
949 llvm::sys::Path DevNull; // leave empty, causes redirection to /dev/null
950 // on Unix or NUL (Windows).
Ted Kremenek379afec2009-10-22 03:24:01 +0000951 std::string ErrMsg;
Ted Kremenekc46e4632009-10-19 22:27:32 +0000952 const llvm::sys::Path *Redirects[] = { &DevNull, &DevNull, &DevNull, NULL };
Ted Kremenek379afec2009-10-22 03:24:01 +0000953 llvm::sys::Program::ExecuteAndWait(ClangPath, &argv[0], /* env */ NULL,
954 /* redirects */ !CXXIdx->getDisplayDiagnostics() ? &Redirects[0] : NULL,
955 /* secondsToWait */ 0, /* memoryLimits */ 0, &ErrMsg);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000956
Ted Kremenek0854d702009-11-10 19:18:52 +0000957 if (CXXIdx->getDisplayDiagnostics() && !ErrMsg.empty()) {
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000958 llvm::errs() << "clang_createTranslationUnitFromSourceFile: " << ErrMsg
Daniel Dunbaracca7252009-11-30 20:42:49 +0000959 << '\n' << "Arguments: \n";
Ted Kremenek379afec2009-10-22 03:24:01 +0000960 for (std::vector<const char*>::iterator I = argv.begin(), E = argv.end();
Ted Kremenek779e5f42009-10-26 22:08:39 +0000961 I!=E; ++I) {
962 if (*I)
963 llvm::errs() << ' ' << *I << '\n';
964 }
965 llvm::errs() << '\n';
Ted Kremenek379afec2009-10-22 03:24:01 +0000966 }
Benjamin Kramer0829a832009-10-18 11:19:36 +0000967
Steve Naroff37b5ac22009-10-15 20:50:09 +0000968 // Finally, we create the translation unit from the ast file.
Steve Naroffe19944c2009-10-15 22:23:48 +0000969 ASTUnit *ATU = static_cast<ASTUnit *>(
Daniel Dunbaracca7252009-11-30 20:42:49 +0000970 clang_createTranslationUnit(CIdx, astTmpFile));
Steve Naroffe56b4ba2009-10-20 14:46:24 +0000971 if (ATU)
972 ATU->unlinkTemporaryFile();
Steve Naroffe19944c2009-10-15 22:23:48 +0000973 return ATU;
Steve Naroff5b7d8e22009-10-15 20:04:39 +0000974}
975
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000976void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Steve Naroff2bd6b9f2009-09-17 18:33:27 +0000977 assert(CTUnit && "Passed null CXTranslationUnit");
978 delete static_cast<ASTUnit *>(CTUnit);
979}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000980
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000981CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Steve Naroffaf08ddc2009-09-03 15:49:00 +0000982 assert(CTUnit && "Passed null CXTranslationUnit");
Steve Naroff77accc12009-09-03 18:19:54 +0000983 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit);
Ted Kremenek4b333d22010-01-12 00:36:38 +0000984 return CIndexer::createCXString(CXXUnit->getOriginalSourceFileName().c_str(),
985 true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +0000986}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +0000987
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +0000988CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000989 CXCursor Result = { CXCursor_TranslationUnit, { 0, 0, TU } };
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +0000990 return Result;
991}
992
Ted Kremenekfb480492010-01-13 21:46:36 +0000993} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +0000994
Ted Kremenekfb480492010-01-13 21:46:36 +0000995//===----------------------------------------------------------------------===//
Douglas Gregor1db19de2010-01-19 21:36:55 +0000996// CXSourceLocation and CXSourceRange Operations.
997//===----------------------------------------------------------------------===//
998
999void clang_getInstantiationLocation(CXSourceLocation location,
1000 CXFile *file,
1001 unsigned *line,
1002 unsigned *column) {
1003 CXSourceLocationPtr Ptr
1004 = CXSourceLocationPtr::getFromOpaqueValue(location.ptr_data);
1005 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
1006
1007 if (!Ptr.getPointer() || Loc.isInvalid()) {
1008 if (file)
1009 *file = 0;
1010 if (line)
1011 *line = 0;
1012 if (column)
1013 *column = 0;
1014 return;
1015 }
1016
1017 // FIXME: This is largely copy-paste from
1018 ///TextDiagnosticPrinter::HighlightRange. When it is clear that this is
1019 // what we want the two routines should be refactored.
1020 ASTContext &Context = *Ptr.getPointer();
1021 SourceManager &SM = Context.getSourceManager();
1022 SourceLocation InstLoc = SM.getInstantiationLoc(Loc);
1023
1024 if (Ptr.getInt()) {
1025 // We want the last character in this location, so we will adjust
1026 // the instantiation location accordingly.
1027
1028 // If the location is from a macro instantiation, get the end of
1029 // the instantiation range.
1030 if (Loc.isMacroID())
1031 InstLoc = SM.getInstantiationRange(Loc).second;
1032
1033 // Measure the length token we're pointing at, so we can adjust
1034 // the physical location in the file to point at the last
1035 // character.
1036 // FIXME: This won't cope with trigraphs or escaped newlines
1037 // well. For that, we actually need a preprocessor, which isn't
1038 // currently available here. Eventually, we'll switch the pointer
1039 // data of CXSourceLocation/CXSourceRange to a translation unit
1040 // (CXXUnit), so that the preprocessor will be available here. At
1041 // that point, we can use Preprocessor::getLocForEndOfToken().
1042 unsigned Length = Lexer::MeasureTokenLength(InstLoc, SM,
1043 Context.getLangOptions());
1044 if (Length > 0)
1045 InstLoc = InstLoc.getFileLocWithOffset(Length - 1);
1046 }
1047
1048 if (file)
1049 *file = (void *)SM.getFileEntryForID(SM.getFileID(InstLoc));
1050 if (line)
1051 *line = SM.getInstantiationLineNumber(InstLoc);
1052 if (column)
1053 *column = SM.getInstantiationColumnNumber(InstLoc);
1054}
1055
1056CXSourceLocation clang_getRangeStart(CXSourceRange range) {
1057 CXSourceLocation Result = { range.ptr_data, range.begin_int_data };
1058 return Result;
1059}
1060
1061CXSourceLocation clang_getRangeEnd(CXSourceRange range) {
1062 llvm::PointerIntPair<ASTContext *, 1, bool> Ptr;
1063 Ptr.setPointer(static_cast<ASTContext *>(range.ptr_data));
1064 Ptr.setInt(true);
1065 CXSourceLocation Result = { Ptr.getOpaqueValue(), range.end_int_data };
1066 return Result;
1067}
1068
1069//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00001070// CXFile Operations.
1071//===----------------------------------------------------------------------===//
1072
1073extern "C" {
Steve Naroff88145032009-10-27 14:35:18 +00001074const char *clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00001075 if (!SFile)
1076 return 0;
1077
Steve Naroff88145032009-10-27 14:35:18 +00001078 assert(SFile && "Passed null CXFile");
1079 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
1080 return FEnt->getName();
1081}
1082
1083time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00001084 if (!SFile)
1085 return 0;
1086
Steve Naroff88145032009-10-27 14:35:18 +00001087 assert(SFile && "Passed null CXFile");
1088 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
1089 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +00001090}
Ted Kremenekfb480492010-01-13 21:46:36 +00001091} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +00001092
Ted Kremenekfb480492010-01-13 21:46:36 +00001093//===----------------------------------------------------------------------===//
1094// CXCursor Operations.
1095//===----------------------------------------------------------------------===//
1096
Ted Kremenekfb480492010-01-13 21:46:36 +00001097static Decl *getDeclFromExpr(Stmt *E) {
1098 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
1099 return RefExpr->getDecl();
1100 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
1101 return ME->getMemberDecl();
1102 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
1103 return RE->getDecl();
1104
1105 if (CallExpr *CE = dyn_cast<CallExpr>(E))
1106 return getDeclFromExpr(CE->getCallee());
1107 if (CastExpr *CE = dyn_cast<CastExpr>(E))
1108 return getDeclFromExpr(CE->getSubExpr());
1109 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
1110 return OME->getMethodDecl();
1111
1112 return 0;
1113}
1114
1115extern "C" {
Douglas Gregorb1373d02010-01-20 20:59:29 +00001116
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001117unsigned clang_visitChildren(CXCursor parent,
Douglas Gregorb1373d02010-01-20 20:59:29 +00001118 CXCursorVisitor visitor,
1119 CXClientData client_data) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001120 ASTUnit *CXXUnit = getCursorASTUnit(parent);
Douglas Gregorb1373d02010-01-20 20:59:29 +00001121
1122 unsigned PCHLevel = Decl::MaxPCHLevel;
1123
1124 // Set the PCHLevel to filter out unwanted decls if requested.
1125 if (CXXUnit->getOnlyLocalDecls()) {
1126 PCHLevel = 0;
1127
1128 // If the main input was an AST, bump the level.
1129 if (CXXUnit->isMainFileAST())
1130 ++PCHLevel;
1131 }
1132
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001133 CursorVisitor CursorVis(CXXUnit, visitor, client_data, PCHLevel);
Douglas Gregorb1373d02010-01-20 20:59:29 +00001134 return CursorVis.VisitChildren(parent);
1135}
1136
Douglas Gregor78205d42010-01-20 21:45:58 +00001137static CXString getDeclSpelling(Decl *D) {
1138 NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
1139 if (!ND)
1140 return CIndexer::createCXString("");
1141
1142 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
1143 return CIndexer::createCXString(OMD->getSelector().getAsString().c_str(),
1144 true);
1145
1146 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
1147 // No, this isn't the same as the code below. getIdentifier() is non-virtual
1148 // and returns different names. NamedDecl returns the class name and
1149 // ObjCCategoryImplDecl returns the category name.
1150 return CIndexer::createCXString(CIMP->getIdentifier()->getNameStart());
1151
1152 if (ND->getIdentifier())
1153 return CIndexer::createCXString(ND->getIdentifier()->getNameStart());
1154
1155 return CIndexer::createCXString("");
1156}
1157
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001158CXString clang_getCursorSpelling(CXCursor C) {
Daniel Dunbarc81d7182010-01-18 17:52:42 +00001159 assert(getCursorDecl(C) && "CXCursor has null decl");
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001160 if (clang_isTranslationUnit(C.kind))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001161 return clang_getTranslationUnitSpelling(C.data[2]);
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001162
Steve Narofff334b4e2009-09-02 18:26:48 +00001163 if (clang_isReference(C.kind)) {
1164 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00001165 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +00001166 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
1167 return CIndexer::createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00001168 }
1169 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +00001170 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
1171 return CIndexer::createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00001172 }
1173 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +00001174 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +00001175 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenek4b333d22010-01-12 00:36:38 +00001176 return CIndexer::createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00001177 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001178 case CXCursor_TypeRef: {
1179 TypeDecl *Type = getCursorTypeRef(C).first;
1180 assert(Type && "Missing type decl");
1181
1182 return CIndexer::createCXString(
1183 getCursorContext(C).getTypeDeclType(Type).getAsString().c_str(),
1184 true);
1185 }
1186
Daniel Dunbaracca7252009-11-30 20:42:49 +00001187 default:
Ted Kremenek4b333d22010-01-12 00:36:38 +00001188 return CIndexer::createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +00001189 }
1190 }
Douglas Gregor97b98722010-01-19 23:20:36 +00001191
1192 if (clang_isExpression(C.kind)) {
1193 Decl *D = getDeclFromExpr(getCursorExpr(C));
1194 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +00001195 return getDeclSpelling(D);
Douglas Gregor97b98722010-01-19 23:20:36 +00001196 return CIndexer::createCXString("");
1197 }
1198
Douglas Gregor78205d42010-01-20 21:45:58 +00001199 return getDeclSpelling(getCursorDecl(C));
Steve Narofff334b4e2009-09-02 18:26:48 +00001200}
1201
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001202const char *clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00001203 switch (Kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00001204 case CXCursor_FunctionDecl: return "FunctionDecl";
1205 case CXCursor_TypedefDecl: return "TypedefDecl";
1206 case CXCursor_EnumDecl: return "EnumDecl";
1207 case CXCursor_EnumConstantDecl: return "EnumConstantDecl";
1208 case CXCursor_StructDecl: return "StructDecl";
1209 case CXCursor_UnionDecl: return "UnionDecl";
1210 case CXCursor_ClassDecl: return "ClassDecl";
1211 case CXCursor_FieldDecl: return "FieldDecl";
1212 case CXCursor_VarDecl: return "VarDecl";
1213 case CXCursor_ParmDecl: return "ParmDecl";
1214 case CXCursor_ObjCInterfaceDecl: return "ObjCInterfaceDecl";
1215 case CXCursor_ObjCCategoryDecl: return "ObjCCategoryDecl";
1216 case CXCursor_ObjCProtocolDecl: return "ObjCProtocolDecl";
1217 case CXCursor_ObjCPropertyDecl: return "ObjCPropertyDecl";
1218 case CXCursor_ObjCIvarDecl: return "ObjCIvarDecl";
1219 case CXCursor_ObjCInstanceMethodDecl: return "ObjCInstanceMethodDecl";
1220 case CXCursor_ObjCClassMethodDecl: return "ObjCClassMethodDecl";
Douglas Gregorb6998662010-01-19 19:34:47 +00001221 case CXCursor_ObjCImplementationDecl: return "ObjCImplementationDecl";
1222 case CXCursor_ObjCCategoryImplDecl: return "ObjCCategoryImplDecl";
Douglas Gregor30122132010-01-19 22:07:56 +00001223 case CXCursor_UnexposedDecl: return "UnexposedDecl";
Daniel Dunbaracca7252009-11-30 20:42:49 +00001224 case CXCursor_ObjCSuperClassRef: return "ObjCSuperClassRef";
1225 case CXCursor_ObjCProtocolRef: return "ObjCProtocolRef";
1226 case CXCursor_ObjCClassRef: return "ObjCClassRef";
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001227 case CXCursor_TypeRef: return "TypeRef";
Douglas Gregor97b98722010-01-19 23:20:36 +00001228 case CXCursor_UnexposedExpr: return "UnexposedExpr";
1229 case CXCursor_DeclRefExpr: return "DeclRefExpr";
1230 case CXCursor_MemberRefExpr: return "MemberRefExpr";
1231 case CXCursor_CallExpr: return "CallExpr";
1232 case CXCursor_ObjCMessageExpr: return "ObjCMessageExpr";
1233 case CXCursor_UnexposedStmt: return "UnexposedStmt";
Daniel Dunbaracca7252009-11-30 20:42:49 +00001234 case CXCursor_InvalidFile: return "InvalidFile";
1235 case CXCursor_NoDeclFound: return "NoDeclFound";
1236 case CXCursor_NotImplemented: return "NotImplemented";
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001237 case CXCursor_TranslationUnit: return "TranslationUnit";
Steve Naroff89922f82009-08-31 00:59:03 +00001238 }
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00001239
1240 llvm_unreachable("Unhandled CXCursorKind");
1241 return NULL;
Steve Naroff600866c2009-08-27 19:51:58 +00001242}
Steve Naroff89922f82009-08-31 00:59:03 +00001243
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001244enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
1245 CXCursor parent,
1246 CXClientData client_data) {
1247 CXCursor *BestCursor = static_cast<CXCursor *>(client_data);
1248 *BestCursor = cursor;
1249 return CXChildVisit_Recurse;
1250}
1251
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001252CXCursor clang_getCursor(CXTranslationUnit CTUnit, const char *source_name,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001253 unsigned line, unsigned column) {
Steve Naroff9efa7672009-09-04 15:44:05 +00001254 assert(CTUnit && "Passed null CXTranslationUnit");
1255 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001256
Steve Naroff9efa7672009-09-04 15:44:05 +00001257 FileManager &FMgr = CXXUnit->getFileManager();
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001258 const FileEntry *File = FMgr.getFile(source_name,
1259 source_name+strlen(source_name));
Ted Kremenekf4629892010-01-14 01:51:23 +00001260 if (!File)
1261 return clang_getNullCursor();
1262
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001263 SourceLocation SLoc =
Steve Naroff9efa7672009-09-04 15:44:05 +00001264 CXXUnit->getSourceManager().getLocation(File, line, column);
Ted Kremenekf4629892010-01-14 01:51:23 +00001265
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001266 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
1267 if (SLoc.isValid()) {
1268 SourceRange RegionOfInterest(SLoc,
1269 CXXUnit->getPreprocessor().getLocForEndOfToken(SLoc, 1));
1270
1271 // FIXME: Would be great to have a "hint" cursor, then walk from that
1272 // hint cursor upward until we find a cursor whose source range encloses
1273 // the region of interest, rather than starting from the translation unit.
1274 CXCursor Parent = clang_getTranslationUnitCursor(CXXUnit);
1275 CursorVisitor CursorVis(CXXUnit, GetCursorVisitor, &Result,
1276 Decl::MaxPCHLevel, RegionOfInterest);
1277 CursorVis.VisitChildren(Parent);
Steve Naroff77128dd2009-09-15 20:25:34 +00001278 }
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001279 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00001280}
1281
Ted Kremenek73885552009-11-17 19:28:59 +00001282CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00001283 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00001284}
1285
1286unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00001287 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00001288}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001289
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001290unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00001291 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
1292}
1293
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001294unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +00001295 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
1296}
Steve Naroff2d4d6292009-08-31 14:26:51 +00001297
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001298unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00001299 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
1300}
1301
Douglas Gregor97b98722010-01-19 23:20:36 +00001302unsigned clang_isExpression(enum CXCursorKind K) {
1303 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
1304}
1305
1306unsigned clang_isStatement(enum CXCursorKind K) {
1307 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
1308}
1309
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001310unsigned clang_isTranslationUnit(enum CXCursorKind K) {
1311 return K == CXCursor_TranslationUnit;
1312}
1313
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001314CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00001315 return C.kind;
1316}
1317
Douglas Gregor97b98722010-01-19 23:20:36 +00001318static SourceLocation getLocationFromExpr(Expr *E) {
1319 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
1320 return /*FIXME:*/Msg->getLeftLoc();
1321 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
1322 return DRE->getLocation();
1323 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
1324 return Member->getMemberLoc();
1325 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
1326 return Ivar->getLocation();
1327 return E->getLocStart();
1328}
1329
Douglas Gregor98258af2010-01-18 22:46:11 +00001330CXSourceLocation clang_getCursorLocation(CXCursor C) {
1331 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00001332 switch (C.kind) {
1333 case CXCursor_ObjCSuperClassRef: {
1334 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1335 = getCursorObjCSuperClassRef(C);
Douglas Gregor1db19de2010-01-19 21:36:55 +00001336 return translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001337 }
1338
1339 case CXCursor_ObjCProtocolRef: {
1340 std::pair<ObjCProtocolDecl *, SourceLocation> P
1341 = getCursorObjCProtocolRef(C);
Douglas Gregor1db19de2010-01-19 21:36:55 +00001342 return translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001343 }
1344
1345 case CXCursor_ObjCClassRef: {
1346 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1347 = getCursorObjCClassRef(C);
Douglas Gregor1db19de2010-01-19 21:36:55 +00001348 return translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001349 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001350
1351 case CXCursor_TypeRef: {
1352 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
1353 return translateSourceLocation(P.first->getASTContext(), P.second);
1354 }
Douglas Gregorf46034a2010-01-18 23:41:10 +00001355
Douglas Gregorf46034a2010-01-18 23:41:10 +00001356 default:
1357 // FIXME: Need a way to enumerate all non-reference cases.
1358 llvm_unreachable("Missed a reference kind");
1359 }
Douglas Gregor98258af2010-01-18 22:46:11 +00001360 }
Douglas Gregor97b98722010-01-19 23:20:36 +00001361
1362 if (clang_isExpression(C.kind))
1363 return translateSourceLocation(getCursorContext(C),
1364 getLocationFromExpr(getCursorExpr(C)));
1365
Douglas Gregor98258af2010-01-18 22:46:11 +00001366 if (!getCursorDecl(C)) {
Douglas Gregor1db19de2010-01-19 21:36:55 +00001367 CXSourceLocation empty = { 0, 0 };
Douglas Gregor98258af2010-01-18 22:46:11 +00001368 return empty;
1369 }
1370
Douglas Gregorf46034a2010-01-18 23:41:10 +00001371 Decl *D = getCursorDecl(C);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001372 SourceLocation Loc = D->getLocation();
1373 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
1374 Loc = Class->getClassLoc();
Douglas Gregor1db19de2010-01-19 21:36:55 +00001375 return translateSourceLocation(D->getASTContext(), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00001376}
Douglas Gregora7bde202010-01-19 00:34:46 +00001377
1378CXSourceRange clang_getCursorExtent(CXCursor C) {
1379 if (clang_isReference(C.kind)) {
1380 switch (C.kind) {
1381 case CXCursor_ObjCSuperClassRef: {
1382 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1383 = getCursorObjCSuperClassRef(C);
1384 return translateSourceRange(P.first->getASTContext(), P.second);
1385 }
1386
1387 case CXCursor_ObjCProtocolRef: {
1388 std::pair<ObjCProtocolDecl *, SourceLocation> P
1389 = getCursorObjCProtocolRef(C);
1390 return translateSourceRange(P.first->getASTContext(), P.second);
1391 }
1392
1393 case CXCursor_ObjCClassRef: {
1394 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1395 = getCursorObjCClassRef(C);
1396
1397 return translateSourceRange(P.first->getASTContext(), P.second);
1398 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001399
1400 case CXCursor_TypeRef: {
1401 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
1402 return translateSourceRange(P.first->getASTContext(), P.second);
1403 }
Douglas Gregora7bde202010-01-19 00:34:46 +00001404
Douglas Gregora7bde202010-01-19 00:34:46 +00001405 default:
1406 // FIXME: Need a way to enumerate all non-reference cases.
1407 llvm_unreachable("Missed a reference kind");
1408 }
1409 }
Douglas Gregor97b98722010-01-19 23:20:36 +00001410
1411 if (clang_isExpression(C.kind))
1412 return translateSourceRange(getCursorContext(C),
1413 getCursorExpr(C)->getSourceRange());
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001414
1415 if (clang_isStatement(C.kind))
1416 return translateSourceRange(getCursorContext(C),
1417 getCursorStmt(C)->getSourceRange());
Douglas Gregora7bde202010-01-19 00:34:46 +00001418
1419 if (!getCursorDecl(C)) {
Douglas Gregor1db19de2010-01-19 21:36:55 +00001420 CXSourceRange empty = { 0, 0, 0 };
Douglas Gregora7bde202010-01-19 00:34:46 +00001421 return empty;
1422 }
1423
1424 Decl *D = getCursorDecl(C);
1425 return translateSourceRange(D->getASTContext(), D->getSourceRange());
1426}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001427
1428CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001429 if (clang_isInvalid(C.kind))
1430 return clang_getNullCursor();
1431
1432 ASTUnit *CXXUnit = getCursorASTUnit(C);
Douglas Gregorb6998662010-01-19 19:34:47 +00001433 if (clang_isDeclaration(C.kind))
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001434 return C;
Douglas Gregor98258af2010-01-18 22:46:11 +00001435
Douglas Gregor97b98722010-01-19 23:20:36 +00001436 if (clang_isExpression(C.kind)) {
1437 Decl *D = getDeclFromExpr(getCursorExpr(C));
1438 if (D)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001439 return MakeCXCursor(D, CXXUnit);
Douglas Gregor97b98722010-01-19 23:20:36 +00001440 return clang_getNullCursor();
1441 }
1442
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001443 if (!clang_isReference(C.kind))
1444 return clang_getNullCursor();
1445
1446 switch (C.kind) {
1447 case CXCursor_ObjCSuperClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001448 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, CXXUnit);
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001449
1450 case CXCursor_ObjCProtocolRef: {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001451 return MakeCXCursor(getCursorObjCProtocolRef(C).first, CXXUnit);
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001452
1453 case CXCursor_ObjCClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001454 return MakeCXCursor(getCursorObjCClassRef(C).first, CXXUnit);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001455
1456 case CXCursor_TypeRef:
1457 return MakeCXCursor(getCursorTypeRef(C).first, CXXUnit);
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001458
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001459 default:
1460 // We would prefer to enumerate all non-reference cursor kinds here.
1461 llvm_unreachable("Unhandled reference cursor kind");
1462 break;
1463 }
1464 }
1465
1466 return clang_getNullCursor();
1467}
1468
Douglas Gregorb6998662010-01-19 19:34:47 +00001469CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001470 if (clang_isInvalid(C.kind))
1471 return clang_getNullCursor();
1472
1473 ASTUnit *CXXUnit = getCursorASTUnit(C);
1474
Douglas Gregorb6998662010-01-19 19:34:47 +00001475 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00001476 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00001477 C = clang_getCursorReferenced(C);
1478 WasReference = true;
1479 }
1480
1481 if (!clang_isDeclaration(C.kind))
1482 return clang_getNullCursor();
1483
1484 Decl *D = getCursorDecl(C);
1485 if (!D)
1486 return clang_getNullCursor();
1487
1488 switch (D->getKind()) {
1489 // Declaration kinds that don't really separate the notions of
1490 // declaration and definition.
1491 case Decl::Namespace:
1492 case Decl::Typedef:
1493 case Decl::TemplateTypeParm:
1494 case Decl::EnumConstant:
1495 case Decl::Field:
1496 case Decl::ObjCIvar:
1497 case Decl::ObjCAtDefsField:
1498 case Decl::ImplicitParam:
1499 case Decl::ParmVar:
1500 case Decl::NonTypeTemplateParm:
1501 case Decl::TemplateTemplateParm:
1502 case Decl::ObjCCategoryImpl:
1503 case Decl::ObjCImplementation:
1504 case Decl::LinkageSpec:
1505 case Decl::ObjCPropertyImpl:
1506 case Decl::FileScopeAsm:
1507 case Decl::StaticAssert:
1508 case Decl::Block:
1509 return C;
1510
1511 // Declaration kinds that don't make any sense here, but are
1512 // nonetheless harmless.
1513 case Decl::TranslationUnit:
1514 case Decl::Template:
1515 case Decl::ObjCContainer:
1516 break;
1517
1518 // Declaration kinds for which the definition is not resolvable.
1519 case Decl::UnresolvedUsingTypename:
1520 case Decl::UnresolvedUsingValue:
1521 break;
1522
1523 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001524 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
1525 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001526
1527 case Decl::NamespaceAlias:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001528 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001529
1530 case Decl::Enum:
1531 case Decl::Record:
1532 case Decl::CXXRecord:
1533 case Decl::ClassTemplateSpecialization:
1534 case Decl::ClassTemplatePartialSpecialization:
1535 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition(D->getASTContext()))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001536 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001537 return clang_getNullCursor();
1538
1539 case Decl::Function:
1540 case Decl::CXXMethod:
1541 case Decl::CXXConstructor:
1542 case Decl::CXXDestructor:
1543 case Decl::CXXConversion: {
1544 const FunctionDecl *Def = 0;
1545 if (cast<FunctionDecl>(D)->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001546 return MakeCXCursor(const_cast<FunctionDecl *>(Def), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001547 return clang_getNullCursor();
1548 }
1549
1550 case Decl::Var: {
1551 VarDecl *Var = cast<VarDecl>(D);
1552
1553 // Variables with initializers have definitions.
1554 const VarDecl *Def = 0;
1555 if (Var->getDefinition(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001556 return MakeCXCursor(const_cast<VarDecl *>(Def), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001557
1558 // extern and private_extern variables are not definitions.
1559 if (Var->hasExternalStorage())
1560 return clang_getNullCursor();
1561
1562 // In-line static data members do not have definitions.
1563 if (Var->isStaticDataMember() && !Var->isOutOfLine())
1564 return clang_getNullCursor();
1565
1566 // All other variables are themselves definitions.
1567 return C;
1568 }
1569
1570 case Decl::FunctionTemplate: {
1571 const FunctionDecl *Def = 0;
1572 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001573 return MakeCXCursor(Def->getDescribedFunctionTemplate(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001574 return clang_getNullCursor();
1575 }
1576
1577 case Decl::ClassTemplate: {
1578 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
1579 ->getDefinition(D->getASTContext()))
1580 return MakeCXCursor(
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001581 cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
1582 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001583 return clang_getNullCursor();
1584 }
1585
1586 case Decl::Using: {
1587 UsingDecl *Using = cast<UsingDecl>(D);
1588 CXCursor Def = clang_getNullCursor();
1589 for (UsingDecl::shadow_iterator S = Using->shadow_begin(),
1590 SEnd = Using->shadow_end();
1591 S != SEnd; ++S) {
1592 if (Def != clang_getNullCursor()) {
1593 // FIXME: We have no way to return multiple results.
1594 return clang_getNullCursor();
1595 }
1596
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001597 Def = clang_getCursorDefinition(MakeCXCursor((*S)->getTargetDecl(),
1598 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00001599 }
1600
1601 return Def;
1602 }
1603
1604 case Decl::UsingShadow:
1605 return clang_getCursorDefinition(
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001606 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
1607 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00001608
1609 case Decl::ObjCMethod: {
1610 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
1611 if (Method->isThisDeclarationADefinition())
1612 return C;
1613
1614 // Dig out the method definition in the associated
1615 // @implementation, if we have it.
1616 // FIXME: The ASTs should make finding the definition easier.
1617 if (ObjCInterfaceDecl *Class
1618 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
1619 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
1620 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
1621 Method->isInstanceMethod()))
1622 if (Def->isThisDeclarationADefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001623 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001624
1625 return clang_getNullCursor();
1626 }
1627
1628 case Decl::ObjCCategory:
1629 if (ObjCCategoryImplDecl *Impl
1630 = cast<ObjCCategoryDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001631 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001632 return clang_getNullCursor();
1633
1634 case Decl::ObjCProtocol:
1635 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
1636 return C;
1637 return clang_getNullCursor();
1638
1639 case Decl::ObjCInterface:
1640 // There are two notions of a "definition" for an Objective-C
1641 // class: the interface and its implementation. When we resolved a
1642 // reference to an Objective-C class, produce the @interface as
1643 // the definition; when we were provided with the interface,
1644 // produce the @implementation as the definition.
1645 if (WasReference) {
1646 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
1647 return C;
1648 } else if (ObjCImplementationDecl *Impl
1649 = cast<ObjCInterfaceDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001650 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001651 return clang_getNullCursor();
1652
1653 case Decl::ObjCProperty:
1654 // FIXME: We don't really know where to find the
1655 // ObjCPropertyImplDecls that implement this property.
1656 return clang_getNullCursor();
1657
1658 case Decl::ObjCCompatibleAlias:
1659 if (ObjCInterfaceDecl *Class
1660 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
1661 if (!Class->isForwardDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001662 return MakeCXCursor(Class, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001663
1664 return clang_getNullCursor();
1665
1666 case Decl::ObjCForwardProtocol: {
1667 ObjCForwardProtocolDecl *Forward = cast<ObjCForwardProtocolDecl>(D);
1668 if (Forward->protocol_size() == 1)
1669 return clang_getCursorDefinition(
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001670 MakeCXCursor(*Forward->protocol_begin(),
1671 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00001672
1673 // FIXME: Cannot return multiple definitions.
1674 return clang_getNullCursor();
1675 }
1676
1677 case Decl::ObjCClass: {
1678 ObjCClassDecl *Class = cast<ObjCClassDecl>(D);
1679 if (Class->size() == 1) {
1680 ObjCInterfaceDecl *IFace = Class->begin()->getInterface();
1681 if (!IFace->isForwardDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001682 return MakeCXCursor(IFace, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001683 return clang_getNullCursor();
1684 }
1685
1686 // FIXME: Cannot return multiple definitions.
1687 return clang_getNullCursor();
1688 }
1689
1690 case Decl::Friend:
1691 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001692 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00001693 return clang_getNullCursor();
1694
1695 case Decl::FriendTemplate:
1696 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001697 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00001698 return clang_getNullCursor();
1699 }
1700
1701 return clang_getNullCursor();
1702}
1703
1704unsigned clang_isCursorDefinition(CXCursor C) {
1705 if (!clang_isDeclaration(C.kind))
1706 return 0;
1707
1708 return clang_getCursorDefinition(C) == C;
1709}
1710
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001711void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00001712 const char **startBuf,
1713 const char **endBuf,
1714 unsigned *startLine,
1715 unsigned *startColumn,
1716 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001717 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00001718 assert(getCursorDecl(C) && "CXCursor has null decl");
1719 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00001720 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
1721 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekfb480492010-01-13 21:46:36 +00001722
Steve Naroff4ade6d62009-09-23 17:52:52 +00001723 SourceManager &SM = FD->getASTContext().getSourceManager();
1724 *startBuf = SM.getCharacterData(Body->getLBracLoc());
1725 *endBuf = SM.getCharacterData(Body->getRBracLoc());
1726 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
1727 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
1728 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
1729 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
1730}
Ted Kremenekfb480492010-01-13 21:46:36 +00001731
1732} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00001733
Ted Kremenekfb480492010-01-13 21:46:36 +00001734//===----------------------------------------------------------------------===//
1735// CXString Operations.
1736//===----------------------------------------------------------------------===//
1737
1738extern "C" {
1739const char *clang_getCString(CXString string) {
1740 return string.Spelling;
1741}
1742
1743void clang_disposeString(CXString string) {
1744 if (string.MustFreeString && string.Spelling)
1745 free((void*)string.Spelling);
1746}
1747} // end: extern "C"