blob: 55061cba7106be78768abec4fc8c726a255a8b30 [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 Kremeneka297de22010-01-25 22:34:44 +000017#include "CXSourceLocation.h"
Ted Kremenekab188932010-01-05 19:32:54 +000018
Ted Kremenek04bb7162010-01-22 22:44:15 +000019#include "clang/Basic/Version.h"
Steve Naroff50398192009-08-28 15:28:48 +000020#include "clang/AST/DeclVisitor.h"
Steve Narofffb570422009-09-22 19:25:29 +000021#include "clang/AST/StmtVisitor.h"
Douglas Gregor7d0d40e2010-01-21 16:28:34 +000022#include "clang/AST/TypeLocVisitor.h"
Ted Kremenekd8210652010-01-06 23:43:31 +000023#include "clang/Lex/Lexer.h"
Douglas Gregor33e9abd2010-01-22 19:49:59 +000024#include "clang/Lex/Preprocessor.h"
Douglas Gregor02465752009-10-16 21:24:31 +000025#include "llvm/Support/MemoryBuffer.h"
Benjamin Kramer0829a832009-10-18 11:19:36 +000026#include "llvm/System/Program.h"
Ted Kremenekfc062212009-10-19 21:44:57 +000027
Ted Kremenekdb3d0da2010-01-05 20:55:39 +000028// Needed to define L_TMPNAM on some systems.
29#include <cstdio>
30
Steve Naroff50398192009-08-28 15:28:48 +000031using namespace clang;
Ted Kremenek16c440a2010-01-15 20:35:54 +000032using namespace clang::cxcursor;
Steve Naroff50398192009-08-28 15:28:48 +000033using namespace idx;
34
Ted Kremenek8a8da7d2010-01-06 03:42:32 +000035//===----------------------------------------------------------------------===//
36// Crash Reporting.
37//===----------------------------------------------------------------------===//
38
39#ifdef __APPLE__
Ted Kremenek29b72842010-01-07 22:49:05 +000040#ifndef NDEBUG
41#define USE_CRASHTRACER
Ted Kremenek8a8da7d2010-01-06 03:42:32 +000042#include "clang/Analysis/Support/SaveAndRestore.h"
43// Integrate with crash reporter.
44extern "C" const char *__crashreporter_info__;
Ted Kremenek29b72842010-01-07 22:49:05 +000045#define NUM_CRASH_STRINGS 16
46static unsigned crashtracer_counter = 0;
Ted Kremenek254ba7c2010-01-07 23:13:53 +000047static unsigned crashtracer_counter_id[NUM_CRASH_STRINGS] = { 0 };
Ted Kremenek29b72842010-01-07 22:49:05 +000048static const char *crashtracer_strings[NUM_CRASH_STRINGS] = { 0 };
49static const char *agg_crashtracer_strings[NUM_CRASH_STRINGS] = { 0 };
50
51static unsigned SetCrashTracerInfo(const char *str,
52 llvm::SmallString<1024> &AggStr) {
53
Ted Kremenek254ba7c2010-01-07 23:13:53 +000054 unsigned slot = 0;
Ted Kremenek29b72842010-01-07 22:49:05 +000055 while (crashtracer_strings[slot]) {
56 if (++slot == NUM_CRASH_STRINGS)
57 slot = 0;
58 }
59 crashtracer_strings[slot] = str;
Ted Kremenek254ba7c2010-01-07 23:13:53 +000060 crashtracer_counter_id[slot] = ++crashtracer_counter;
Ted Kremenek29b72842010-01-07 22:49:05 +000061
62 // We need to create an aggregate string because multiple threads
63 // may be in this method at one time. The crash reporter string
64 // will attempt to overapproximate the set of in-flight invocations
65 // of this function. Race conditions can still cause this goal
66 // to not be achieved.
67 {
68 llvm::raw_svector_ostream Out(AggStr);
69 for (unsigned i = 0; i < NUM_CRASH_STRINGS; ++i)
70 if (crashtracer_strings[i]) Out << crashtracer_strings[i] << '\n';
71 }
72 __crashreporter_info__ = agg_crashtracer_strings[slot] = AggStr.c_str();
73 return slot;
74}
75
76static void ResetCrashTracerInfo(unsigned slot) {
Ted Kremenek254ba7c2010-01-07 23:13:53 +000077 unsigned max_slot = 0;
78 unsigned max_value = 0;
79
80 crashtracer_strings[slot] = agg_crashtracer_strings[slot] = 0;
81
82 for (unsigned i = 0 ; i < NUM_CRASH_STRINGS; ++i)
83 if (agg_crashtracer_strings[i] &&
84 crashtracer_counter_id[i] > max_value) {
85 max_slot = i;
86 max_value = crashtracer_counter_id[i];
Ted Kremenek29b72842010-01-07 22:49:05 +000087 }
Ted Kremenek254ba7c2010-01-07 23:13:53 +000088
89 __crashreporter_info__ = agg_crashtracer_strings[max_slot];
Ted Kremenek29b72842010-01-07 22:49:05 +000090}
91
92namespace {
93class ArgsCrashTracerInfo {
94 llvm::SmallString<1024> CrashString;
95 llvm::SmallString<1024> AggregateString;
96 unsigned crashtracerSlot;
97public:
98 ArgsCrashTracerInfo(llvm::SmallVectorImpl<const char*> &Args)
99 : crashtracerSlot(0)
100 {
101 {
102 llvm::raw_svector_ostream Out(CrashString);
103 Out << "ClangCIndex [createTranslationUnitFromSourceFile]: clang";
104 for (llvm::SmallVectorImpl<const char*>::iterator I=Args.begin(),
105 E=Args.end(); I!=E; ++I)
106 Out << ' ' << *I;
107 }
108 crashtracerSlot = SetCrashTracerInfo(CrashString.c_str(),
109 AggregateString);
110 }
111
112 ~ArgsCrashTracerInfo() {
113 ResetCrashTracerInfo(crashtracerSlot);
114 }
115};
116}
117#endif
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000118#endif
119
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000120/// \brief The result of comparing two source ranges.
121enum RangeComparisonResult {
122 /// \brief Either the ranges overlap or one of the ranges is invalid.
123 RangeOverlap,
124
125 /// \brief The first range ends before the second range starts.
126 RangeBefore,
127
128 /// \brief The first range starts after the second range ends.
129 RangeAfter
130};
131
132/// \brief Compare two source ranges to determine their relative position in
133/// the translation unit.
134static RangeComparisonResult RangeCompare(SourceManager &SM,
135 SourceRange R1,
136 SourceRange R2) {
137 assert(R1.isValid() && "First range is invalid?");
138 assert(R2.isValid() && "Second range is invalid?");
139 if (SM.isBeforeInTranslationUnit(R1.getEnd(), R2.getBegin()))
140 return RangeBefore;
141 if (SM.isBeforeInTranslationUnit(R2.getEnd(), R1.getBegin()))
142 return RangeAfter;
143 return RangeOverlap;
144}
145
Douglas Gregor1db19de2010-01-19 21:36:55 +0000146
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000147//===----------------------------------------------------------------------===//
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000148// Cursor visitor.
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000149//===----------------------------------------------------------------------===//
150
Steve Naroff89922f82009-08-31 00:59:03 +0000151namespace {
Ted Kremenekedc8aa62010-01-16 00:36:30 +0000152
Douglas Gregorb1373d02010-01-20 20:59:29 +0000153// Cursor visitor.
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000154class CursorVisitor : public DeclVisitor<CursorVisitor, bool>,
Douglas Gregora59e3902010-01-21 23:27:09 +0000155 public TypeLocVisitor<CursorVisitor, bool>,
156 public StmtVisitor<CursorVisitor, bool>
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000157{
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000158 /// \brief The translation unit we are traversing.
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000159 ASTUnit *TU;
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000160
161 /// \brief The parent cursor whose children we are traversing.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000162 CXCursor Parent;
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000163
164 /// \brief The declaration that serves at the parent of any statement or
165 /// expression nodes.
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000166 Decl *StmtParent;
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000167
168 /// \brief The visitor function.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000169 CXCursorVisitor Visitor;
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000170
171 /// \brief The opaque client data, to be passed along to the visitor.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000172 CXClientData ClientData;
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000173
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000174 // MaxPCHLevel - the maximum PCH level of declarations that we will pass on
175 // to the visitor. Declarations with a PCH level greater than this value will
176 // be suppressed.
177 unsigned MaxPCHLevel;
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000178
179 /// \brief When valid, a source range to which the cursor should restrict
180 /// its search.
181 SourceRange RegionOfInterest;
182
Douglas Gregorb1373d02010-01-20 20:59:29 +0000183 using DeclVisitor<CursorVisitor, bool>::Visit;
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000184 using TypeLocVisitor<CursorVisitor, bool>::Visit;
Douglas Gregora59e3902010-01-21 23:27:09 +0000185 using StmtVisitor<CursorVisitor, bool>::Visit;
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000186
187 /// \brief Determine whether this particular source range comes before, comes
188 /// after, or overlaps the region of interest.
189 ///
190 /// \param R a source range retrieved from the abstract syntax tree.
191 RangeComparisonResult CompareRegionOfInterest(SourceRange R);
192
193 /// \brief Determine whether this particular source range comes before, comes
194 /// after, or overlaps the region of interest.
195 ///
196 /// \param CXR a source range retrieved from a cursor.
197 RangeComparisonResult CompareRegionOfInterest(CXSourceRange CXR);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000198
Steve Naroff89922f82009-08-31 00:59:03 +0000199public:
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000200 CursorVisitor(ASTUnit *TU, CXCursorVisitor Visitor, CXClientData ClientData,
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000201 unsigned MaxPCHLevel,
202 SourceRange RegionOfInterest = SourceRange())
203 : TU(TU), Visitor(Visitor), ClientData(ClientData),
204 MaxPCHLevel(MaxPCHLevel), RegionOfInterest(RegionOfInterest)
Douglas Gregorb1373d02010-01-20 20:59:29 +0000205 {
206 Parent.kind = CXCursor_NoDeclFound;
207 Parent.data[0] = 0;
208 Parent.data[1] = 0;
209 Parent.data[2] = 0;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000210 StmtParent = 0;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000211 }
212
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000213 bool Visit(CXCursor Cursor, bool CheckedRegionOfInterest = false);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000214 bool VisitChildren(CXCursor Parent);
215
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000216 // Declaration visitors
Douglas Gregorb1373d02010-01-20 20:59:29 +0000217 bool VisitDeclContext(DeclContext *DC);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000218 bool VisitTranslationUnitDecl(TranslationUnitDecl *D);
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000219 bool VisitTypedefDecl(TypedefDecl *D);
220 bool VisitTagDecl(TagDecl *D);
221 bool VisitEnumConstantDecl(EnumConstantDecl *D);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000222 bool VisitDeclaratorDecl(DeclaratorDecl *DD);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000223 bool VisitFunctionDecl(FunctionDecl *ND);
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000224 bool VisitFieldDecl(FieldDecl *D);
225 bool VisitVarDecl(VarDecl *);
226 bool VisitObjCMethodDecl(ObjCMethodDecl *ND);
Douglas Gregora59e3902010-01-21 23:27:09 +0000227 bool VisitObjCContainerDecl(ObjCContainerDecl *D);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000228 bool VisitObjCCategoryDecl(ObjCCategoryDecl *ND);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000229 bool VisitObjCProtocolDecl(ObjCProtocolDecl *PID);
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000230 bool VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
231 bool VisitObjCImplDecl(ObjCImplDecl *D);
232 bool VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
233 bool VisitObjCImplementationDecl(ObjCImplementationDecl *D);
234 // FIXME: ObjCPropertyDecl requires TypeSourceInfo, getter/setter locations,
235 // etc.
236 // FIXME: ObjCCompatibleAliasDecl requires aliased-class locations.
237 bool VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D);
238 bool VisitObjCClassDecl(ObjCClassDecl *D);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000239
240 // Type visitors
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000241 // FIXME: QualifiedTypeLoc doesn't provide any location information
242 bool VisitBuiltinTypeLoc(BuiltinTypeLoc TL);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000243 bool VisitTypedefTypeLoc(TypedefTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000244 bool VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL);
245 bool VisitTagTypeLoc(TagTypeLoc TL);
246 // FIXME: TemplateTypeParmTypeLoc doesn't provide any location information
247 bool VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL);
248 bool VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL);
249 bool VisitPointerTypeLoc(PointerTypeLoc TL);
250 bool VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL);
251 bool VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL);
252 bool VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL);
253 bool VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL);
254 bool VisitFunctionTypeLoc(FunctionTypeLoc TL);
255 bool VisitArrayTypeLoc(ArrayTypeLoc TL);
Douglas Gregor2332c112010-01-21 20:48:56 +0000256 // FIXME: Implement for TemplateSpecializationTypeLoc
257 // FIXME: Implement visitors here when the unimplemented TypeLocs get
258 // implemented
259 bool VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL);
260 bool VisitTypeOfTypeLoc(TypeOfTypeLoc TL);
Douglas Gregora59e3902010-01-21 23:27:09 +0000261
262 // Statement visitors
263 bool VisitStmt(Stmt *S);
264 bool VisitDeclStmt(DeclStmt *S);
Douglas Gregorf5bab412010-01-22 01:00:11 +0000265 // FIXME: LabelStmt label?
266 bool VisitIfStmt(IfStmt *S);
267 bool VisitSwitchStmt(SwitchStmt *S);
Douglas Gregor263b47b2010-01-25 16:12:32 +0000268 bool VisitWhileStmt(WhileStmt *S);
269 bool VisitForStmt(ForStmt *S);
Douglas Gregor336fd812010-01-23 00:40:08 +0000270
271 // Expression visitors
272 bool VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E);
273 bool VisitExplicitCastExpr(ExplicitCastExpr *E);
274 bool VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
Steve Naroff89922f82009-08-31 00:59:03 +0000275};
Douglas Gregorb1373d02010-01-20 20:59:29 +0000276
Ted Kremenekab188932010-01-05 19:32:54 +0000277} // end anonymous namespace
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000278
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000279RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
280 assert(RegionOfInterest.isValid() && "RangeCompare called with invalid range");
281 if (R.isInvalid())
282 return RangeOverlap;
283
284 // Move the end of the input range to the end of the last token in that
285 // range.
286 R.setEnd(TU->getPreprocessor().getLocForEndOfToken(R.getEnd(), 1));
287 return RangeCompare(TU->getSourceManager(), R, RegionOfInterest);
288}
289
290RangeComparisonResult CursorVisitor::CompareRegionOfInterest(CXSourceRange CXR) {
Ted Kremeneka297de22010-01-25 22:34:44 +0000291 return CompareRegionOfInterest(cxloc::translateSourceRange(CXR));
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000292}
293
Douglas Gregorb1373d02010-01-20 20:59:29 +0000294/// \brief Visit the given cursor and, if requested by the visitor,
295/// its children.
296///
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000297/// \param Cursor the cursor to visit.
298///
299/// \param CheckRegionOfInterest if true, then the caller already checked that
300/// this cursor is within the region of interest.
301///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000302/// \returns true if the visitation should be aborted, false if it
303/// should continue.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000304bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
Douglas Gregorb1373d02010-01-20 20:59:29 +0000305 if (clang_isInvalid(Cursor.kind))
306 return false;
307
308 if (clang_isDeclaration(Cursor.kind)) {
309 Decl *D = getCursorDecl(Cursor);
310 assert(D && "Invalid declaration cursor");
311 if (D->getPCHLevel() > MaxPCHLevel)
312 return false;
313
314 if (D->isImplicit())
315 return false;
316 }
317
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000318 // If we have a range of interest, and this cursor doesn't intersect with it,
319 // we're done.
320 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
321 CXSourceRange Range = clang_getCursorExtent(Cursor);
Ted Kremeneka297de22010-01-25 22:34:44 +0000322 if (cxloc::translateSourceRange(Range).isInvalid() ||
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000323 CompareRegionOfInterest(Range))
324 return false;
325 }
326
Douglas Gregorb1373d02010-01-20 20:59:29 +0000327 switch (Visitor(Cursor, Parent, ClientData)) {
328 case CXChildVisit_Break:
329 return true;
330
331 case CXChildVisit_Continue:
332 return false;
333
334 case CXChildVisit_Recurse:
335 return VisitChildren(Cursor);
336 }
337
Douglas Gregorfd643772010-01-25 16:45:46 +0000338 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000339}
340
341/// \brief Visit the children of the given cursor.
342///
343/// \returns true if the visitation should be aborted, false if it
344/// should continue.
345bool CursorVisitor::VisitChildren(CXCursor Cursor) {
Douglas Gregora59e3902010-01-21 23:27:09 +0000346 if (clang_isReference(Cursor.kind)) {
347 // By definition, references have no children.
348 return false;
349 }
350
Douglas Gregorb1373d02010-01-20 20:59:29 +0000351 // Set the Parent field to Cursor, then back to its old value once we're
352 // done.
353 class SetParentRAII {
354 CXCursor &Parent;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000355 Decl *&StmtParent;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000356 CXCursor OldParent;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000357
Douglas Gregorb1373d02010-01-20 20:59:29 +0000358 public:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000359 SetParentRAII(CXCursor &Parent, Decl *&StmtParent, CXCursor NewParent)
360 : Parent(Parent), StmtParent(StmtParent), OldParent(Parent)
Douglas Gregorb1373d02010-01-20 20:59:29 +0000361 {
362 Parent = NewParent;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000363 if (clang_isDeclaration(Parent.kind))
364 StmtParent = getCursorDecl(Parent);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000365 }
366
367 ~SetParentRAII() {
368 Parent = OldParent;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000369 if (clang_isDeclaration(Parent.kind))
370 StmtParent = getCursorDecl(Parent);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000371 }
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000372 } SetParent(Parent, StmtParent, Cursor);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000373
374 if (clang_isDeclaration(Cursor.kind)) {
375 Decl *D = getCursorDecl(Cursor);
376 assert(D && "Invalid declaration cursor");
377 return Visit(D);
378 }
379
Douglas Gregora59e3902010-01-21 23:27:09 +0000380 if (clang_isStatement(Cursor.kind))
381 return Visit(getCursorStmt(Cursor));
382 if (clang_isExpression(Cursor.kind))
383 return Visit(getCursorExpr(Cursor));
384
Douglas Gregorb1373d02010-01-20 20:59:29 +0000385 if (clang_isTranslationUnit(Cursor.kind)) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000386 ASTUnit *CXXUnit = getCursorASTUnit(Cursor);
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000387 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
388 RegionOfInterest.isInvalid()) {
Douglas Gregor7b691f332010-01-20 21:13:59 +0000389 const std::vector<Decl*> &TLDs = CXXUnit->getTopLevelDecls();
390 for (std::vector<Decl*>::const_iterator it = TLDs.begin(),
391 ie = TLDs.end(); it != ie; ++it) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000392 if (Visit(MakeCXCursor(*it, CXXUnit), true))
Douglas Gregor7b691f332010-01-20 21:13:59 +0000393 return true;
394 }
395 } else {
396 return VisitDeclContext(
Douglas Gregorb1373d02010-01-20 20:59:29 +0000397 CXXUnit->getASTContext().getTranslationUnitDecl());
Douglas Gregor7b691f332010-01-20 21:13:59 +0000398 }
399
400 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000401 }
Douglas Gregora59e3902010-01-21 23:27:09 +0000402
Douglas Gregorb1373d02010-01-20 20:59:29 +0000403 // Nothing to visit at the moment.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000404 return false;
405}
406
Douglas Gregorb1373d02010-01-20 20:59:29 +0000407bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000408 for (DeclContext::decl_iterator
Douglas Gregorb1373d02010-01-20 20:59:29 +0000409 I = DC->decls_begin(), E = DC->decls_end(); I != E; ++I) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000410 if (RegionOfInterest.isValid()) {
411 SourceRange R = (*I)->getSourceRange();
412 if (R.isInvalid())
413 continue;
414
415 switch (CompareRegionOfInterest(R)) {
416 case RangeBefore:
417 // This declaration comes before the region of interest; skip it.
418 continue;
419
420 case RangeAfter:
421 // This declaration comes after the region of interest; we're done.
422 return false;
423
424 case RangeOverlap:
425 // This declaration overlaps the region of interest; visit it.
426 break;
427 }
428 }
429
430 if (Visit(MakeCXCursor(*I, TU), true))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000431 return true;
432 }
433
434 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000435}
436
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000437bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
438 llvm_unreachable("Translation units are visited directly by Visit()");
439 return false;
440}
441
442bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
443 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
444 return Visit(TSInfo->getTypeLoc());
445
446 return false;
447}
448
449bool CursorVisitor::VisitTagDecl(TagDecl *D) {
450 return VisitDeclContext(D);
451}
452
453bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
454 if (Expr *Init = D->getInitExpr())
455 return Visit(MakeCXCursor(Init, StmtParent, TU));
456 return false;
457}
458
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000459bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
460 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
461 if (Visit(TSInfo->getTypeLoc()))
462 return true;
463
464 return false;
465}
466
Douglas Gregorb1373d02010-01-20 20:59:29 +0000467bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000468 if (VisitDeclaratorDecl(ND))
469 return true;
470
Douglas Gregora59e3902010-01-21 23:27:09 +0000471 if (ND->isThisDeclarationADefinition() &&
472 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
473 return true;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000474
475 return false;
476}
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000477
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000478bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
479 if (VisitDeclaratorDecl(D))
480 return true;
481
482 if (Expr *BitWidth = D->getBitWidth())
483 return Visit(MakeCXCursor(BitWidth, StmtParent, TU));
484
485 return false;
486}
487
488bool CursorVisitor::VisitVarDecl(VarDecl *D) {
489 if (VisitDeclaratorDecl(D))
490 return true;
491
492 if (Expr *Init = D->getInit())
493 return Visit(MakeCXCursor(Init, StmtParent, TU));
494
495 return false;
496}
497
498bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
499 // FIXME: We really need a TypeLoc covering Objective-C method declarations.
500 // At the moment, we don't have information about locations in the return
501 // type.
502 for (ObjCMethodDecl::param_iterator P = ND->param_begin(),
503 PEnd = ND->param_end();
504 P != PEnd; ++P) {
505 if (Visit(MakeCXCursor(*P, TU)))
506 return true;
507 }
508
509 if (ND->isThisDeclarationADefinition() &&
510 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
511 return true;
512
513 return false;
514}
515
Douglas Gregora59e3902010-01-21 23:27:09 +0000516bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
517 return VisitDeclContext(D);
518}
519
Douglas Gregorb1373d02010-01-20 20:59:29 +0000520bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000521 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
522 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000523 return true;
524
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000525 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
526 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
527 E = ND->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000528 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000529 return true;
530
Douglas Gregora59e3902010-01-21 23:27:09 +0000531 return VisitObjCContainerDecl(ND);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000532}
533
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000534bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
535 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
536 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
537 E = PID->protocol_end(); I != E; ++I, ++PL)
538 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
539 return true;
540
541 return VisitObjCContainerDecl(PID);
542}
543
Douglas Gregorb1373d02010-01-20 20:59:29 +0000544bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000545 // Issue callbacks for super class.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000546 if (D->getSuperClass() &&
547 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000548 D->getSuperClassLoc(),
549 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000550 return true;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000551
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000552 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
553 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
554 E = D->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000555 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000556 return true;
557
Douglas Gregora59e3902010-01-21 23:27:09 +0000558 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000559}
560
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000561bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
562 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000563}
564
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000565bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
566 if (Visit(MakeCursorObjCClassRef(D->getCategoryDecl()->getClassInterface(),
567 D->getLocation(), TU)))
568 return true;
569
570 return VisitObjCImplDecl(D);
571}
572
573bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
574#if 0
575 // Issue callbacks for super class.
576 // FIXME: No source location information!
577 if (D->getSuperClass() &&
578 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
579 D->getSuperClassLoc(),
580 TU)))
581 return true;
582#endif
583
584 return VisitObjCImplDecl(D);
585}
586
587bool CursorVisitor::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D) {
588 ObjCForwardProtocolDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
589 for (ObjCForwardProtocolDecl::protocol_iterator I = D->protocol_begin(),
590 E = D->protocol_end();
591 I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000592 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000593 return true;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000594
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000595 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000596}
597
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000598bool CursorVisitor::VisitObjCClassDecl(ObjCClassDecl *D) {
599 for (ObjCClassDecl::iterator C = D->begin(), CEnd = D->end(); C != CEnd; ++C)
600 if (Visit(MakeCursorObjCClassRef(C->getInterface(), C->getLocation(), TU)))
601 return true;
602
603 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000604}
605
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000606bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
607 ASTContext &Context = TU->getASTContext();
608
609 // Some builtin types (such as Objective-C's "id", "sel", and
610 // "Class") have associated declarations. Create cursors for those.
611 QualType VisitType;
612 switch (TL.getType()->getAs<BuiltinType>()->getKind()) {
613 case BuiltinType::Void:
614 case BuiltinType::Bool:
615 case BuiltinType::Char_U:
616 case BuiltinType::UChar:
617 case BuiltinType::Char16:
618 case BuiltinType::Char32:
619 case BuiltinType::UShort:
620 case BuiltinType::UInt:
621 case BuiltinType::ULong:
622 case BuiltinType::ULongLong:
623 case BuiltinType::UInt128:
624 case BuiltinType::Char_S:
625 case BuiltinType::SChar:
626 case BuiltinType::WChar:
627 case BuiltinType::Short:
628 case BuiltinType::Int:
629 case BuiltinType::Long:
630 case BuiltinType::LongLong:
631 case BuiltinType::Int128:
632 case BuiltinType::Float:
633 case BuiltinType::Double:
634 case BuiltinType::LongDouble:
635 case BuiltinType::NullPtr:
636 case BuiltinType::Overload:
637 case BuiltinType::Dependent:
638 break;
639
640 case BuiltinType::UndeducedAuto: // FIXME: Deserves a cursor?
641 break;
642
643 case BuiltinType::ObjCId:
644 VisitType = Context.getObjCIdType();
645 break;
646
647 case BuiltinType::ObjCClass:
648 VisitType = Context.getObjCClassType();
649 break;
650
651 case BuiltinType::ObjCSel:
652 VisitType = Context.getObjCSelType();
653 break;
654 }
655
656 if (!VisitType.isNull()) {
657 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
658 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
659 TU));
660 }
661
662 return false;
663}
664
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000665bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
666 return Visit(MakeCursorTypeRef(TL.getTypedefDecl(), TL.getNameLoc(), TU));
667}
668
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000669bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
670 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
671}
672
673bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
674 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
675}
676
677bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
678 if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
679 return true;
680
681 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
682 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
683 TU)))
684 return true;
685 }
686
687 return false;
688}
689
690bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
691 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseTypeLoc()))
692 return true;
693
694 if (TL.hasProtocolsAsWritten()) {
695 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
696 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I),
697 TL.getProtocolLoc(I),
698 TU)))
699 return true;
700 }
701 }
702
703 return false;
704}
705
706bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
707 return Visit(TL.getPointeeLoc());
708}
709
710bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
711 return Visit(TL.getPointeeLoc());
712}
713
714bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
715 return Visit(TL.getPointeeLoc());
716}
717
718bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
719 return Visit(TL.getPointeeLoc());
720}
721
722bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
723 return Visit(TL.getPointeeLoc());
724}
725
726bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
727 if (Visit(TL.getResultLoc()))
728 return true;
729
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000730 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
731 if (Visit(MakeCXCursor(TL.getArg(I), TU)))
732 return true;
733
734 return false;
735}
736
737bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
738 if (Visit(TL.getElementLoc()))
739 return true;
740
741 if (Expr *Size = TL.getSizeExpr())
742 return Visit(MakeCXCursor(Size, StmtParent, TU));
743
744 return false;
745}
746
Douglas Gregor2332c112010-01-21 20:48:56 +0000747bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
748 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
749}
750
751bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
752 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
753 return Visit(TSInfo->getTypeLoc());
754
755 return false;
756}
757
Douglas Gregora59e3902010-01-21 23:27:09 +0000758bool CursorVisitor::VisitStmt(Stmt *S) {
759 for (Stmt::child_iterator Child = S->child_begin(), ChildEnd = S->child_end();
760 Child != ChildEnd; ++Child) {
Daniel Dunbar54d67ca2010-01-25 00:40:30 +0000761 if (*Child && Visit(MakeCXCursor(*Child, StmtParent, TU)))
Douglas Gregora59e3902010-01-21 23:27:09 +0000762 return true;
763 }
764
765 return false;
766}
767
768bool CursorVisitor::VisitDeclStmt(DeclStmt *S) {
769 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
770 D != DEnd; ++D) {
Douglas Gregor263b47b2010-01-25 16:12:32 +0000771 if (*D && Visit(MakeCXCursor(*D, TU)))
Douglas Gregora59e3902010-01-21 23:27:09 +0000772 return true;
773 }
774
775 return false;
776}
777
Douglas Gregorf5bab412010-01-22 01:00:11 +0000778bool CursorVisitor::VisitIfStmt(IfStmt *S) {
779 if (VarDecl *Var = S->getConditionVariable()) {
780 if (Visit(MakeCXCursor(Var, TU)))
781 return true;
Douglas Gregor263b47b2010-01-25 16:12:32 +0000782 }
Douglas Gregorf5bab412010-01-22 01:00:11 +0000783
Douglas Gregor263b47b2010-01-25 16:12:32 +0000784 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
785 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +0000786 if (S->getThen() && Visit(MakeCXCursor(S->getThen(), StmtParent, TU)))
787 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +0000788 if (S->getElse() && Visit(MakeCXCursor(S->getElse(), StmtParent, TU)))
789 return true;
790
791 return false;
792}
793
794bool CursorVisitor::VisitSwitchStmt(SwitchStmt *S) {
795 if (VarDecl *Var = S->getConditionVariable()) {
796 if (Visit(MakeCXCursor(Var, TU)))
797 return true;
Douglas Gregor263b47b2010-01-25 16:12:32 +0000798 }
799
800 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
801 return true;
802 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
803 return true;
804
805 return false;
806}
807
808bool CursorVisitor::VisitWhileStmt(WhileStmt *S) {
809 if (VarDecl *Var = S->getConditionVariable()) {
810 if (Visit(MakeCXCursor(Var, TU)))
811 return true;
812 }
813
814 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
815 return true;
816 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
Douglas Gregorf5bab412010-01-22 01:00:11 +0000817 return true;
818
Douglas Gregor263b47b2010-01-25 16:12:32 +0000819 return false;
820}
821
822bool CursorVisitor::VisitForStmt(ForStmt *S) {
823 if (S->getInit() && Visit(MakeCXCursor(S->getInit(), StmtParent, TU)))
824 return true;
825 if (VarDecl *Var = S->getConditionVariable()) {
826 if (Visit(MakeCXCursor(Var, TU)))
827 return true;
828 }
829
830 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
831 return true;
832 if (S->getInc() && Visit(MakeCXCursor(S->getInc(), StmtParent, TU)))
833 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +0000834 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
835 return true;
836
837 return false;
838}
839
Douglas Gregor336fd812010-01-23 00:40:08 +0000840bool CursorVisitor::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E) {
841 if (E->isArgumentType()) {
842 if (TypeSourceInfo *TSInfo = E->getArgumentTypeInfo())
843 return Visit(TSInfo->getTypeLoc());
844
845 return false;
846 }
847
848 return VisitExpr(E);
849}
850
851bool CursorVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
852 if (TypeSourceInfo *TSInfo = E->getTypeInfoAsWritten())
853 if (Visit(TSInfo->getTypeLoc()))
854 return true;
855
856 return VisitCastExpr(E);
857}
858
859bool CursorVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
860 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
861 if (Visit(TSInfo->getTypeLoc()))
862 return true;
863
864 return VisitExpr(E);
865}
866
Daniel Dunbar140fce22010-01-12 02:34:07 +0000867CXString CIndexer::createCXString(const char *String, bool DupString){
Benjamin Kramer62cf3222009-11-09 19:13:48 +0000868 CXString Str;
869 if (DupString) {
870 Str.Spelling = strdup(String);
871 Str.MustFreeString = 1;
872 } else {
873 Str.Spelling = String;
874 Str.MustFreeString = 0;
875 }
876 return Str;
877}
878
Douglas Gregorfc8ea232010-01-26 17:06:03 +0000879CXString CIndexer::createCXString(llvm::StringRef String, bool DupString) {
880 CXString Result;
881 if (DupString || (!String.empty() && String.data()[String.size()] != 0)) {
882 char *Spelling = (char *)malloc(String.size() + 1);
883 memmove(Spelling, String.data(), String.size());
884 Spelling[String.size()] = 0;
885 Result.Spelling = Spelling;
886 Result.MustFreeString = 1;
887 } else {
888 Result.Spelling = String.data();
889 Result.MustFreeString = 0;
890 }
891 return Result;
892}
893
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000894extern "C" {
Steve Naroffe56b4ba2009-10-20 14:46:24 +0000895CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000896 int displayDiagnostics) {
Douglas Gregora030b7c2010-01-22 20:35:53 +0000897 CIndexer *CIdxr = new CIndexer();
Steve Naroffe56b4ba2009-10-20 14:46:24 +0000898 if (excludeDeclarationsFromPCH)
899 CIdxr->setOnlyLocalDecls();
900 if (displayDiagnostics)
901 CIdxr->setDisplayDiagnostics();
902 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +0000903}
904
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000905void clang_disposeIndex(CXIndex CIdx) {
Steve Naroff2bd6b9f2009-09-17 18:33:27 +0000906 assert(CIdx && "Passed null CXIndex");
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000907 delete static_cast<CIndexer *>(CIdx);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +0000908}
909
Daniel Dunbar8506dde2009-12-03 01:54:28 +0000910void clang_setUseExternalASTGeneration(CXIndex CIdx, int value) {
911 assert(CIdx && "Passed null CXIndex");
912 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
913 CXXIdx->setUseExternalASTGeneration(value);
914}
915
Steve Naroff50398192009-08-28 15:28:48 +0000916// FIXME: need to pass back error info.
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000917CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
918 const char *ast_filename) {
Steve Naroff50398192009-08-28 15:28:48 +0000919 assert(CIdx && "Passed null CXIndex");
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000920 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000921
Daniel Dunbar5262fda2009-12-03 01:45:44 +0000922 return ASTUnit::LoadFromPCHFile(ast_filename, CXXIdx->getDiags(),
923 CXXIdx->getOnlyLocalDecls(),
924 /* UseBumpAllocator = */ true);
Steve Naroff600866c2009-08-27 19:51:58 +0000925}
926
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000927CXTranslationUnit
928clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
929 const char *source_filename,
930 int num_command_line_args,
Douglas Gregor4db64a42010-01-23 00:14:00 +0000931 const char **command_line_args,
932 unsigned num_unsaved_files,
933 struct CXUnsavedFile *unsaved_files) {
Steve Naroffe56b4ba2009-10-20 14:46:24 +0000934 assert(CIdx && "Passed null CXIndex");
935 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
936
Douglas Gregor4db64a42010-01-23 00:14:00 +0000937 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
938 for (unsigned I = 0; I != num_unsaved_files; ++I) {
939 const llvm::MemoryBuffer *Buffer
940 = llvm::MemoryBuffer::getMemBuffer(unsaved_files[I].Contents,
941 unsaved_files[I].Contents + unsaved_files[I].Length,
942 unsaved_files[I].Filename);
943 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
944 Buffer));
945 }
946
Daniel Dunbar8506dde2009-12-03 01:54:28 +0000947 if (!CXXIdx->getUseExternalASTGeneration()) {
948 llvm::SmallVector<const char *, 16> Args;
949
950 // The 'source_filename' argument is optional. If the caller does not
951 // specify it then it is assumed that the source file is specified
952 // in the actual argument list.
953 if (source_filename)
954 Args.push_back(source_filename);
955 Args.insert(Args.end(), command_line_args,
956 command_line_args + num_command_line_args);
957
Daniel Dunbar94220972009-12-05 02:17:18 +0000958 unsigned NumErrors = CXXIdx->getDiags().getNumErrors();
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000959
Ted Kremenek29b72842010-01-07 22:49:05 +0000960#ifdef USE_CRASHTRACER
961 ArgsCrashTracerInfo ACTI(Args);
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000962#endif
963
Daniel Dunbar94220972009-12-05 02:17:18 +0000964 llvm::OwningPtr<ASTUnit> Unit(
965 ASTUnit::LoadFromCommandLine(Args.data(), Args.data() + Args.size(),
Daniel Dunbar869824e2009-12-13 03:46:13 +0000966 CXXIdx->getDiags(),
967 CXXIdx->getClangResourcesPath(),
Daniel Dunbar94220972009-12-05 02:17:18 +0000968 CXXIdx->getOnlyLocalDecls(),
Douglas Gregor4db64a42010-01-23 00:14:00 +0000969 /* UseBumpAllocator = */ true,
970 RemappedFiles.data(),
971 RemappedFiles.size()));
Ted Kremenek29b72842010-01-07 22:49:05 +0000972
Daniel Dunbar94220972009-12-05 02:17:18 +0000973 // FIXME: Until we have broader testing, just drop the entire AST if we
974 // encountered an error.
975 if (NumErrors != CXXIdx->getDiags().getNumErrors())
976 return 0;
977
978 return Unit.take();
Daniel Dunbar8506dde2009-12-03 01:54:28 +0000979 }
980
Ted Kremenek139ba862009-10-22 00:03:57 +0000981 // Build up the arguments for invoking 'clang'.
Ted Kremenek74cd0692009-10-15 23:21:22 +0000982 std::vector<const char *> argv;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000983
Ted Kremenek139ba862009-10-22 00:03:57 +0000984 // First add the complete path to the 'clang' executable.
985 llvm::sys::Path ClangPath = static_cast<CIndexer *>(CIdx)->getClangPath();
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000986 argv.push_back(ClangPath.c_str());
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000987
Ted Kremenek139ba862009-10-22 00:03:57 +0000988 // Add the '-emit-ast' option as our execution mode for 'clang'.
Ted Kremenek74cd0692009-10-15 23:21:22 +0000989 argv.push_back("-emit-ast");
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000990
Ted Kremenek139ba862009-10-22 00:03:57 +0000991 // The 'source_filename' argument is optional. If the caller does not
992 // specify it then it is assumed that the source file is specified
993 // in the actual argument list.
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000994 if (source_filename)
995 argv.push_back(source_filename);
Ted Kremenek139ba862009-10-22 00:03:57 +0000996
Steve Naroff37b5ac22009-10-15 20:50:09 +0000997 // Generate a temporary name for the AST file.
Ted Kremenek139ba862009-10-22 00:03:57 +0000998 argv.push_back("-o");
Steve Naroff37b5ac22009-10-15 20:50:09 +0000999 char astTmpFile[L_tmpnam];
Ted Kremenek74cd0692009-10-15 23:21:22 +00001000 argv.push_back(tmpnam(astTmpFile));
Ted Kremenek139ba862009-10-22 00:03:57 +00001001
Douglas Gregor4db64a42010-01-23 00:14:00 +00001002 // Remap any unsaved files to temporary files.
1003 std::vector<llvm::sys::Path> TemporaryFiles;
1004 std::vector<std::string> RemapArgs;
1005 if (RemapFiles(num_unsaved_files, unsaved_files, RemapArgs, TemporaryFiles))
1006 return 0;
1007
1008 // The pointers into the elements of RemapArgs are stable because we
1009 // won't be adding anything to RemapArgs after this point.
1010 for (unsigned i = 0, e = RemapArgs.size(); i != e; ++i)
1011 argv.push_back(RemapArgs[i].c_str());
1012
Ted Kremenek139ba862009-10-22 00:03:57 +00001013 // Process the compiler options, stripping off '-o', '-c', '-fsyntax-only'.
1014 for (int i = 0; i < num_command_line_args; ++i)
1015 if (const char *arg = command_line_args[i]) {
1016 if (strcmp(arg, "-o") == 0) {
1017 ++i; // Also skip the matching argument.
1018 continue;
1019 }
1020 if (strcmp(arg, "-emit-ast") == 0 ||
1021 strcmp(arg, "-c") == 0 ||
1022 strcmp(arg, "-fsyntax-only") == 0) {
1023 continue;
1024 }
1025
1026 // Keep the argument.
1027 argv.push_back(arg);
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001028 }
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001029
Ted Kremenek139ba862009-10-22 00:03:57 +00001030 // Add the null terminator.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001031 argv.push_back(NULL);
1032
Ted Kremenekfeb15e32009-10-26 22:14:08 +00001033 // Invoke 'clang'.
1034 llvm::sys::Path DevNull; // leave empty, causes redirection to /dev/null
1035 // on Unix or NUL (Windows).
Ted Kremenek379afec2009-10-22 03:24:01 +00001036 std::string ErrMsg;
Ted Kremenekc46e4632009-10-19 22:27:32 +00001037 const llvm::sys::Path *Redirects[] = { &DevNull, &DevNull, &DevNull, NULL };
Ted Kremenek379afec2009-10-22 03:24:01 +00001038 llvm::sys::Program::ExecuteAndWait(ClangPath, &argv[0], /* env */ NULL,
1039 /* redirects */ !CXXIdx->getDisplayDiagnostics() ? &Redirects[0] : NULL,
1040 /* secondsToWait */ 0, /* memoryLimits */ 0, &ErrMsg);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001041
Ted Kremenek0854d702009-11-10 19:18:52 +00001042 if (CXXIdx->getDisplayDiagnostics() && !ErrMsg.empty()) {
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001043 llvm::errs() << "clang_createTranslationUnitFromSourceFile: " << ErrMsg
Daniel Dunbaracca7252009-11-30 20:42:49 +00001044 << '\n' << "Arguments: \n";
Ted Kremenek379afec2009-10-22 03:24:01 +00001045 for (std::vector<const char*>::iterator I = argv.begin(), E = argv.end();
Ted Kremenek779e5f42009-10-26 22:08:39 +00001046 I!=E; ++I) {
1047 if (*I)
1048 llvm::errs() << ' ' << *I << '\n';
1049 }
1050 llvm::errs() << '\n';
Ted Kremenek379afec2009-10-22 03:24:01 +00001051 }
Benjamin Kramer0829a832009-10-18 11:19:36 +00001052
Douglas Gregor4db64a42010-01-23 00:14:00 +00001053 ASTUnit *ATU = ASTUnit::LoadFromPCHFile(astTmpFile, CXXIdx->getDiags(),
1054 CXXIdx->getOnlyLocalDecls(),
1055 /* UseBumpAllocator = */ true,
1056 RemappedFiles.data(),
1057 RemappedFiles.size());
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001058 if (ATU)
1059 ATU->unlinkTemporaryFile();
Douglas Gregor4db64a42010-01-23 00:14:00 +00001060
1061 for (unsigned i = 0, e = TemporaryFiles.size(); i != e; ++i)
1062 TemporaryFiles[i].eraseFromDisk();
1063
Steve Naroffe19944c2009-10-15 22:23:48 +00001064 return ATU;
Steve Naroff5b7d8e22009-10-15 20:04:39 +00001065}
1066
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001067void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00001068 assert(CTUnit && "Passed null CXTranslationUnit");
1069 delete static_cast<ASTUnit *>(CTUnit);
1070}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001071
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001072CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Steve Naroffaf08ddc2009-09-03 15:49:00 +00001073 assert(CTUnit && "Passed null CXTranslationUnit");
Steve Naroff77accc12009-09-03 18:19:54 +00001074 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit);
Ted Kremenek4b333d22010-01-12 00:36:38 +00001075 return CIndexer::createCXString(CXXUnit->getOriginalSourceFileName().c_str(),
1076 true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +00001077}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +00001078
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001079CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001080 CXCursor Result = { CXCursor_TranslationUnit, { 0, 0, TU } };
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001081 return Result;
1082}
1083
Ted Kremenekfb480492010-01-13 21:46:36 +00001084} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +00001085
Ted Kremenekfb480492010-01-13 21:46:36 +00001086//===----------------------------------------------------------------------===//
Douglas Gregor1db19de2010-01-19 21:36:55 +00001087// CXSourceLocation and CXSourceRange Operations.
1088//===----------------------------------------------------------------------===//
1089
Douglas Gregorb9790342010-01-22 21:44:22 +00001090extern "C" {
1091CXSourceLocation clang_getNullLocation() {
1092 CXSourceLocation Result = { 0, 0 };
1093 return Result;
1094}
1095
1096unsigned clang_equalLocations(CXSourceLocation loc1, CXSourceLocation loc2) {
1097 return loc1.ptr_data == loc2.ptr_data && loc1.int_data == loc2.int_data;
1098}
1099
1100CXSourceLocation clang_getLocation(CXTranslationUnit tu,
1101 CXFile file,
1102 unsigned line,
1103 unsigned column) {
1104 if (!tu)
1105 return clang_getNullLocation();
1106
1107 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
1108 SourceLocation SLoc
1109 = CXXUnit->getSourceManager().getLocation(
1110 static_cast<const FileEntry *>(file),
1111 line, column);
1112
Ted Kremeneka297de22010-01-25 22:34:44 +00001113 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc, false);
Douglas Gregorb9790342010-01-22 21:44:22 +00001114}
1115
1116CXSourceRange clang_getRange(CXSourceLocation begin, CXSourceLocation end) {
1117 if (begin.ptr_data != end.ptr_data) {
1118 CXSourceRange Result = { 0, 0, 0 };
1119 return Result;
1120 }
1121
1122 CXSourceRange Result = { begin.ptr_data, begin.int_data, end.int_data };
1123 return Result;
1124}
1125
Douglas Gregore69517c2010-01-26 03:07:15 +00001126static SourceLocation getAdjustedSourceLocation(CXSourceLocation location) {
Ted Kremeneka297de22010-01-25 22:34:44 +00001127 cxloc::CXSourceLocationPtr Ptr
1128 = cxloc::CXSourceLocationPtr::getFromOpaqueValue(location.ptr_data);
Douglas Gregor1db19de2010-01-19 21:36:55 +00001129 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
1130
Douglas Gregor1db19de2010-01-19 21:36:55 +00001131 // FIXME: This is largely copy-paste from
1132 ///TextDiagnosticPrinter::HighlightRange. When it is clear that this is
1133 // what we want the two routines should be refactored.
1134 ASTContext &Context = *Ptr.getPointer();
1135 SourceManager &SM = Context.getSourceManager();
1136 SourceLocation InstLoc = SM.getInstantiationLoc(Loc);
1137
1138 if (Ptr.getInt()) {
1139 // We want the last character in this location, so we will adjust
1140 // the instantiation location accordingly.
1141
1142 // If the location is from a macro instantiation, get the end of
1143 // the instantiation range.
1144 if (Loc.isMacroID())
1145 InstLoc = SM.getInstantiationRange(Loc).second;
1146
1147 // Measure the length token we're pointing at, so we can adjust
1148 // the physical location in the file to point at the last
1149 // character.
1150 // FIXME: This won't cope with trigraphs or escaped newlines
1151 // well. For that, we actually need a preprocessor, which isn't
1152 // currently available here. Eventually, we'll switch the pointer
1153 // data of CXSourceLocation/CXSourceRange to a translation unit
1154 // (CXXUnit), so that the preprocessor will be available here. At
1155 // that point, we can use Preprocessor::getLocForEndOfToken().
1156 unsigned Length = Lexer::MeasureTokenLength(InstLoc, SM,
1157 Context.getLangOptions());
1158 if (Length > 0)
1159 InstLoc = InstLoc.getFileLocWithOffset(Length - 1);
1160 }
1161
Douglas Gregore69517c2010-01-26 03:07:15 +00001162 return InstLoc;
1163}
1164
1165void clang_getInstantiationLocation(CXSourceLocation location,
1166 CXFile *file,
1167 unsigned *line,
1168 unsigned *column) {
1169 cxloc::CXSourceLocationPtr Ptr
1170 = cxloc::CXSourceLocationPtr::getFromOpaqueValue(location.ptr_data);
1171 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
1172
1173 if (!Ptr.getPointer() || Loc.isInvalid()) {
1174 if (file)
1175 *file = 0;
1176 if (line)
1177 *line = 0;
1178 if (column)
1179 *column = 0;
1180 return;
1181 }
1182
1183 SourceLocation InstLoc = getAdjustedSourceLocation(location);
1184 ASTContext &Context = *Ptr.getPointer();
1185 SourceManager &SM = Context.getSourceManager();
Douglas Gregor1db19de2010-01-19 21:36:55 +00001186 if (file)
1187 *file = (void *)SM.getFileEntryForID(SM.getFileID(InstLoc));
1188 if (line)
1189 *line = SM.getInstantiationLineNumber(InstLoc);
1190 if (column)
1191 *column = SM.getInstantiationColumnNumber(InstLoc);
1192}
1193
Douglas Gregore69517c2010-01-26 03:07:15 +00001194void clang_getInstantiationLocationOffset(CXSourceLocation location,
1195 CXFile *file,
1196 unsigned *offset) {
1197 cxloc::CXSourceLocationPtr Ptr
1198 = cxloc::CXSourceLocationPtr::getFromOpaqueValue(location.ptr_data);
1199 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
1200
1201 ASTContext &Context = *Ptr.getPointer();
1202 SourceManager &SM = Context.getSourceManager();
1203 SourceLocation InstLoc = getAdjustedSourceLocation(location);
1204 std::pair<FileID, unsigned> Decomposed = SM.getDecomposedLoc(InstLoc);
1205 if (file)
1206 *file = (void *)SM.getFileEntryForID(Decomposed.first);
1207 if (offset)
1208 *offset = Decomposed.second;
1209}
1210
Douglas Gregor1db19de2010-01-19 21:36:55 +00001211CXSourceLocation clang_getRangeStart(CXSourceRange range) {
1212 CXSourceLocation Result = { range.ptr_data, range.begin_int_data };
1213 return Result;
1214}
1215
1216CXSourceLocation clang_getRangeEnd(CXSourceRange range) {
1217 llvm::PointerIntPair<ASTContext *, 1, bool> Ptr;
1218 Ptr.setPointer(static_cast<ASTContext *>(range.ptr_data));
1219 Ptr.setInt(true);
1220 CXSourceLocation Result = { Ptr.getOpaqueValue(), range.end_int_data };
1221 return Result;
1222}
1223
Douglas Gregorb9790342010-01-22 21:44:22 +00001224} // end: extern "C"
1225
Douglas Gregor1db19de2010-01-19 21:36:55 +00001226//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00001227// CXFile Operations.
1228//===----------------------------------------------------------------------===//
1229
1230extern "C" {
Steve Naroff88145032009-10-27 14:35:18 +00001231const char *clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00001232 if (!SFile)
1233 return 0;
1234
Steve Naroff88145032009-10-27 14:35:18 +00001235 assert(SFile && "Passed null CXFile");
1236 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
1237 return FEnt->getName();
1238}
1239
1240time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00001241 if (!SFile)
1242 return 0;
1243
Steve Naroff88145032009-10-27 14:35:18 +00001244 assert(SFile && "Passed null CXFile");
1245 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
1246 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +00001247}
Douglas Gregorb9790342010-01-22 21:44:22 +00001248
1249CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
1250 if (!tu)
1251 return 0;
1252
1253 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
1254
1255 FileManager &FMgr = CXXUnit->getFileManager();
1256 const FileEntry *File = FMgr.getFile(file_name, file_name+strlen(file_name));
1257 return const_cast<FileEntry *>(File);
1258}
1259
Ted Kremenekfb480492010-01-13 21:46:36 +00001260} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +00001261
Ted Kremenekfb480492010-01-13 21:46:36 +00001262//===----------------------------------------------------------------------===//
1263// CXCursor Operations.
1264//===----------------------------------------------------------------------===//
1265
Ted Kremenekfb480492010-01-13 21:46:36 +00001266static Decl *getDeclFromExpr(Stmt *E) {
1267 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
1268 return RefExpr->getDecl();
1269 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
1270 return ME->getMemberDecl();
1271 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
1272 return RE->getDecl();
1273
1274 if (CallExpr *CE = dyn_cast<CallExpr>(E))
1275 return getDeclFromExpr(CE->getCallee());
1276 if (CastExpr *CE = dyn_cast<CastExpr>(E))
1277 return getDeclFromExpr(CE->getSubExpr());
1278 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
1279 return OME->getMethodDecl();
1280
1281 return 0;
1282}
1283
1284extern "C" {
Douglas Gregorb1373d02010-01-20 20:59:29 +00001285
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001286unsigned clang_visitChildren(CXCursor parent,
Douglas Gregorb1373d02010-01-20 20:59:29 +00001287 CXCursorVisitor visitor,
1288 CXClientData client_data) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001289 ASTUnit *CXXUnit = getCursorASTUnit(parent);
Douglas Gregorb1373d02010-01-20 20:59:29 +00001290
1291 unsigned PCHLevel = Decl::MaxPCHLevel;
1292
1293 // Set the PCHLevel to filter out unwanted decls if requested.
1294 if (CXXUnit->getOnlyLocalDecls()) {
1295 PCHLevel = 0;
1296
1297 // If the main input was an AST, bump the level.
1298 if (CXXUnit->isMainFileAST())
1299 ++PCHLevel;
1300 }
1301
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001302 CursorVisitor CursorVis(CXXUnit, visitor, client_data, PCHLevel);
Douglas Gregorb1373d02010-01-20 20:59:29 +00001303 return CursorVis.VisitChildren(parent);
1304}
1305
Douglas Gregor78205d42010-01-20 21:45:58 +00001306static CXString getDeclSpelling(Decl *D) {
1307 NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
1308 if (!ND)
1309 return CIndexer::createCXString("");
1310
1311 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
1312 return CIndexer::createCXString(OMD->getSelector().getAsString().c_str(),
1313 true);
1314
1315 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
1316 // No, this isn't the same as the code below. getIdentifier() is non-virtual
1317 // and returns different names. NamedDecl returns the class name and
1318 // ObjCCategoryImplDecl returns the category name.
1319 return CIndexer::createCXString(CIMP->getIdentifier()->getNameStart());
1320
1321 if (ND->getIdentifier())
1322 return CIndexer::createCXString(ND->getIdentifier()->getNameStart());
1323
1324 return CIndexer::createCXString("");
1325}
1326
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001327CXString clang_getCursorSpelling(CXCursor C) {
Daniel Dunbarc81d7182010-01-18 17:52:42 +00001328 assert(getCursorDecl(C) && "CXCursor has null decl");
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001329 if (clang_isTranslationUnit(C.kind))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001330 return clang_getTranslationUnitSpelling(C.data[2]);
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001331
Steve Narofff334b4e2009-09-02 18:26:48 +00001332 if (clang_isReference(C.kind)) {
1333 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00001334 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +00001335 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
1336 return CIndexer::createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00001337 }
1338 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +00001339 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
1340 return CIndexer::createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00001341 }
1342 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +00001343 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +00001344 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenek4b333d22010-01-12 00:36:38 +00001345 return CIndexer::createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00001346 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001347 case CXCursor_TypeRef: {
1348 TypeDecl *Type = getCursorTypeRef(C).first;
1349 assert(Type && "Missing type decl");
1350
1351 return CIndexer::createCXString(
1352 getCursorContext(C).getTypeDeclType(Type).getAsString().c_str(),
1353 true);
1354 }
1355
Daniel Dunbaracca7252009-11-30 20:42:49 +00001356 default:
Ted Kremenek4b333d22010-01-12 00:36:38 +00001357 return CIndexer::createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +00001358 }
1359 }
Douglas Gregor97b98722010-01-19 23:20:36 +00001360
1361 if (clang_isExpression(C.kind)) {
1362 Decl *D = getDeclFromExpr(getCursorExpr(C));
1363 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +00001364 return getDeclSpelling(D);
Douglas Gregor97b98722010-01-19 23:20:36 +00001365 return CIndexer::createCXString("");
1366 }
1367
Douglas Gregor60cbfac2010-01-25 16:56:17 +00001368 if (clang_isDeclaration(C.kind))
1369 return getDeclSpelling(getCursorDecl(C));
1370
1371 return CIndexer::createCXString("");
Steve Narofff334b4e2009-09-02 18:26:48 +00001372}
1373
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001374const char *clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00001375 switch (Kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00001376 case CXCursor_FunctionDecl: return "FunctionDecl";
1377 case CXCursor_TypedefDecl: return "TypedefDecl";
1378 case CXCursor_EnumDecl: return "EnumDecl";
1379 case CXCursor_EnumConstantDecl: return "EnumConstantDecl";
1380 case CXCursor_StructDecl: return "StructDecl";
1381 case CXCursor_UnionDecl: return "UnionDecl";
1382 case CXCursor_ClassDecl: return "ClassDecl";
1383 case CXCursor_FieldDecl: return "FieldDecl";
1384 case CXCursor_VarDecl: return "VarDecl";
1385 case CXCursor_ParmDecl: return "ParmDecl";
1386 case CXCursor_ObjCInterfaceDecl: return "ObjCInterfaceDecl";
1387 case CXCursor_ObjCCategoryDecl: return "ObjCCategoryDecl";
1388 case CXCursor_ObjCProtocolDecl: return "ObjCProtocolDecl";
1389 case CXCursor_ObjCPropertyDecl: return "ObjCPropertyDecl";
1390 case CXCursor_ObjCIvarDecl: return "ObjCIvarDecl";
1391 case CXCursor_ObjCInstanceMethodDecl: return "ObjCInstanceMethodDecl";
1392 case CXCursor_ObjCClassMethodDecl: return "ObjCClassMethodDecl";
Douglas Gregorb6998662010-01-19 19:34:47 +00001393 case CXCursor_ObjCImplementationDecl: return "ObjCImplementationDecl";
1394 case CXCursor_ObjCCategoryImplDecl: return "ObjCCategoryImplDecl";
Douglas Gregor30122132010-01-19 22:07:56 +00001395 case CXCursor_UnexposedDecl: return "UnexposedDecl";
Daniel Dunbaracca7252009-11-30 20:42:49 +00001396 case CXCursor_ObjCSuperClassRef: return "ObjCSuperClassRef";
1397 case CXCursor_ObjCProtocolRef: return "ObjCProtocolRef";
1398 case CXCursor_ObjCClassRef: return "ObjCClassRef";
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001399 case CXCursor_TypeRef: return "TypeRef";
Douglas Gregor97b98722010-01-19 23:20:36 +00001400 case CXCursor_UnexposedExpr: return "UnexposedExpr";
1401 case CXCursor_DeclRefExpr: return "DeclRefExpr";
1402 case CXCursor_MemberRefExpr: return "MemberRefExpr";
1403 case CXCursor_CallExpr: return "CallExpr";
1404 case CXCursor_ObjCMessageExpr: return "ObjCMessageExpr";
1405 case CXCursor_UnexposedStmt: return "UnexposedStmt";
Daniel Dunbaracca7252009-11-30 20:42:49 +00001406 case CXCursor_InvalidFile: return "InvalidFile";
1407 case CXCursor_NoDeclFound: return "NoDeclFound";
1408 case CXCursor_NotImplemented: return "NotImplemented";
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001409 case CXCursor_TranslationUnit: return "TranslationUnit";
Steve Naroff89922f82009-08-31 00:59:03 +00001410 }
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00001411
1412 llvm_unreachable("Unhandled CXCursorKind");
1413 return NULL;
Steve Naroff600866c2009-08-27 19:51:58 +00001414}
Steve Naroff89922f82009-08-31 00:59:03 +00001415
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001416enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
1417 CXCursor parent,
1418 CXClientData client_data) {
1419 CXCursor *BestCursor = static_cast<CXCursor *>(client_data);
1420 *BestCursor = cursor;
1421 return CXChildVisit_Recurse;
1422}
1423
Douglas Gregorb9790342010-01-22 21:44:22 +00001424CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
1425 if (!TU)
Ted Kremenekf4629892010-01-14 01:51:23 +00001426 return clang_getNullCursor();
Ted Kremenekf4629892010-01-14 01:51:23 +00001427
Douglas Gregorb9790342010-01-22 21:44:22 +00001428 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
1429
Ted Kremeneka297de22010-01-25 22:34:44 +00001430 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001431 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
1432 if (SLoc.isValid()) {
1433 SourceRange RegionOfInterest(SLoc,
1434 CXXUnit->getPreprocessor().getLocForEndOfToken(SLoc, 1));
1435
1436 // FIXME: Would be great to have a "hint" cursor, then walk from that
1437 // hint cursor upward until we find a cursor whose source range encloses
1438 // the region of interest, rather than starting from the translation unit.
1439 CXCursor Parent = clang_getTranslationUnitCursor(CXXUnit);
1440 CursorVisitor CursorVis(CXXUnit, GetCursorVisitor, &Result,
1441 Decl::MaxPCHLevel, RegionOfInterest);
1442 CursorVis.VisitChildren(Parent);
Steve Naroff77128dd2009-09-15 20:25:34 +00001443 }
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001444 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00001445}
1446
Ted Kremenek73885552009-11-17 19:28:59 +00001447CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00001448 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00001449}
1450
1451unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00001452 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00001453}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001454
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001455unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00001456 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
1457}
1458
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001459unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +00001460 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
1461}
Steve Naroff2d4d6292009-08-31 14:26:51 +00001462
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001463unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00001464 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
1465}
1466
Douglas Gregor97b98722010-01-19 23:20:36 +00001467unsigned clang_isExpression(enum CXCursorKind K) {
1468 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
1469}
1470
1471unsigned clang_isStatement(enum CXCursorKind K) {
1472 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
1473}
1474
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001475unsigned clang_isTranslationUnit(enum CXCursorKind K) {
1476 return K == CXCursor_TranslationUnit;
1477}
1478
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001479CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00001480 return C.kind;
1481}
1482
Douglas Gregor97b98722010-01-19 23:20:36 +00001483static SourceLocation getLocationFromExpr(Expr *E) {
1484 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
1485 return /*FIXME:*/Msg->getLeftLoc();
1486 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
1487 return DRE->getLocation();
1488 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
1489 return Member->getMemberLoc();
1490 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
1491 return Ivar->getLocation();
1492 return E->getLocStart();
1493}
1494
Douglas Gregor98258af2010-01-18 22:46:11 +00001495CXSourceLocation clang_getCursorLocation(CXCursor C) {
1496 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00001497 switch (C.kind) {
1498 case CXCursor_ObjCSuperClassRef: {
1499 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1500 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001501 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001502 }
1503
1504 case CXCursor_ObjCProtocolRef: {
1505 std::pair<ObjCProtocolDecl *, SourceLocation> P
1506 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001507 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001508 }
1509
1510 case CXCursor_ObjCClassRef: {
1511 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1512 = getCursorObjCClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001513 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001514 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001515
1516 case CXCursor_TypeRef: {
1517 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001518 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001519 }
Douglas Gregorf46034a2010-01-18 23:41:10 +00001520
Douglas Gregorf46034a2010-01-18 23:41:10 +00001521 default:
1522 // FIXME: Need a way to enumerate all non-reference cases.
1523 llvm_unreachable("Missed a reference kind");
1524 }
Douglas Gregor98258af2010-01-18 22:46:11 +00001525 }
Douglas Gregor97b98722010-01-19 23:20:36 +00001526
1527 if (clang_isExpression(C.kind))
Ted Kremeneka297de22010-01-25 22:34:44 +00001528 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00001529 getLocationFromExpr(getCursorExpr(C)));
1530
Douglas Gregor98258af2010-01-18 22:46:11 +00001531 if (!getCursorDecl(C)) {
Douglas Gregor1db19de2010-01-19 21:36:55 +00001532 CXSourceLocation empty = { 0, 0 };
Douglas Gregor98258af2010-01-18 22:46:11 +00001533 return empty;
1534 }
1535
Douglas Gregorf46034a2010-01-18 23:41:10 +00001536 Decl *D = getCursorDecl(C);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001537 SourceLocation Loc = D->getLocation();
1538 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
1539 Loc = Class->getClassLoc();
Ted Kremeneka297de22010-01-25 22:34:44 +00001540 return cxloc::translateSourceLocation(D->getASTContext(), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00001541}
Douglas Gregora7bde202010-01-19 00:34:46 +00001542
1543CXSourceRange clang_getCursorExtent(CXCursor C) {
1544 if (clang_isReference(C.kind)) {
1545 switch (C.kind) {
1546 case CXCursor_ObjCSuperClassRef: {
1547 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1548 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001549 return cxloc::translateSourceRange(P.first->getASTContext(), P.second);
Douglas Gregora7bde202010-01-19 00:34:46 +00001550 }
1551
1552 case CXCursor_ObjCProtocolRef: {
1553 std::pair<ObjCProtocolDecl *, SourceLocation> P
1554 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001555 return cxloc::translateSourceRange(P.first->getASTContext(), P.second);
Douglas Gregora7bde202010-01-19 00:34:46 +00001556 }
1557
1558 case CXCursor_ObjCClassRef: {
1559 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1560 = getCursorObjCClassRef(C);
1561
Ted Kremeneka297de22010-01-25 22:34:44 +00001562 return cxloc::translateSourceRange(P.first->getASTContext(), P.second);
Douglas Gregora7bde202010-01-19 00:34:46 +00001563 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001564
1565 case CXCursor_TypeRef: {
1566 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001567 return cxloc::translateSourceRange(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001568 }
Douglas Gregora7bde202010-01-19 00:34:46 +00001569
Douglas Gregora7bde202010-01-19 00:34:46 +00001570 default:
1571 // FIXME: Need a way to enumerate all non-reference cases.
1572 llvm_unreachable("Missed a reference kind");
1573 }
1574 }
Douglas Gregor97b98722010-01-19 23:20:36 +00001575
1576 if (clang_isExpression(C.kind))
Ted Kremeneka297de22010-01-25 22:34:44 +00001577 return cxloc::translateSourceRange(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00001578 getCursorExpr(C)->getSourceRange());
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001579
1580 if (clang_isStatement(C.kind))
Ted Kremeneka297de22010-01-25 22:34:44 +00001581 return cxloc::translateSourceRange(getCursorContext(C),
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001582 getCursorStmt(C)->getSourceRange());
Douglas Gregora7bde202010-01-19 00:34:46 +00001583
1584 if (!getCursorDecl(C)) {
Douglas Gregor1db19de2010-01-19 21:36:55 +00001585 CXSourceRange empty = { 0, 0, 0 };
Douglas Gregora7bde202010-01-19 00:34:46 +00001586 return empty;
1587 }
1588
1589 Decl *D = getCursorDecl(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001590 return cxloc::translateSourceRange(D->getASTContext(), D->getSourceRange());
Douglas Gregora7bde202010-01-19 00:34:46 +00001591}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001592
1593CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001594 if (clang_isInvalid(C.kind))
1595 return clang_getNullCursor();
1596
1597 ASTUnit *CXXUnit = getCursorASTUnit(C);
Douglas Gregorb6998662010-01-19 19:34:47 +00001598 if (clang_isDeclaration(C.kind))
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001599 return C;
Douglas Gregor98258af2010-01-18 22:46:11 +00001600
Douglas Gregor97b98722010-01-19 23:20:36 +00001601 if (clang_isExpression(C.kind)) {
1602 Decl *D = getDeclFromExpr(getCursorExpr(C));
1603 if (D)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001604 return MakeCXCursor(D, CXXUnit);
Douglas Gregor97b98722010-01-19 23:20:36 +00001605 return clang_getNullCursor();
1606 }
1607
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001608 if (!clang_isReference(C.kind))
1609 return clang_getNullCursor();
1610
1611 switch (C.kind) {
1612 case CXCursor_ObjCSuperClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001613 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, CXXUnit);
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001614
1615 case CXCursor_ObjCProtocolRef: {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001616 return MakeCXCursor(getCursorObjCProtocolRef(C).first, CXXUnit);
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001617
1618 case CXCursor_ObjCClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001619 return MakeCXCursor(getCursorObjCClassRef(C).first, CXXUnit);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001620
1621 case CXCursor_TypeRef:
1622 return MakeCXCursor(getCursorTypeRef(C).first, CXXUnit);
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001623
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001624 default:
1625 // We would prefer to enumerate all non-reference cursor kinds here.
1626 llvm_unreachable("Unhandled reference cursor kind");
1627 break;
1628 }
1629 }
1630
1631 return clang_getNullCursor();
1632}
1633
Douglas Gregorb6998662010-01-19 19:34:47 +00001634CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001635 if (clang_isInvalid(C.kind))
1636 return clang_getNullCursor();
1637
1638 ASTUnit *CXXUnit = getCursorASTUnit(C);
1639
Douglas Gregorb6998662010-01-19 19:34:47 +00001640 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00001641 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00001642 C = clang_getCursorReferenced(C);
1643 WasReference = true;
1644 }
1645
1646 if (!clang_isDeclaration(C.kind))
1647 return clang_getNullCursor();
1648
1649 Decl *D = getCursorDecl(C);
1650 if (!D)
1651 return clang_getNullCursor();
1652
1653 switch (D->getKind()) {
1654 // Declaration kinds that don't really separate the notions of
1655 // declaration and definition.
1656 case Decl::Namespace:
1657 case Decl::Typedef:
1658 case Decl::TemplateTypeParm:
1659 case Decl::EnumConstant:
1660 case Decl::Field:
1661 case Decl::ObjCIvar:
1662 case Decl::ObjCAtDefsField:
1663 case Decl::ImplicitParam:
1664 case Decl::ParmVar:
1665 case Decl::NonTypeTemplateParm:
1666 case Decl::TemplateTemplateParm:
1667 case Decl::ObjCCategoryImpl:
1668 case Decl::ObjCImplementation:
1669 case Decl::LinkageSpec:
1670 case Decl::ObjCPropertyImpl:
1671 case Decl::FileScopeAsm:
1672 case Decl::StaticAssert:
1673 case Decl::Block:
1674 return C;
1675
1676 // Declaration kinds that don't make any sense here, but are
1677 // nonetheless harmless.
1678 case Decl::TranslationUnit:
1679 case Decl::Template:
1680 case Decl::ObjCContainer:
1681 break;
1682
1683 // Declaration kinds for which the definition is not resolvable.
1684 case Decl::UnresolvedUsingTypename:
1685 case Decl::UnresolvedUsingValue:
1686 break;
1687
1688 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001689 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
1690 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001691
1692 case Decl::NamespaceAlias:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001693 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001694
1695 case Decl::Enum:
1696 case Decl::Record:
1697 case Decl::CXXRecord:
1698 case Decl::ClassTemplateSpecialization:
1699 case Decl::ClassTemplatePartialSpecialization:
1700 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition(D->getASTContext()))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001701 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001702 return clang_getNullCursor();
1703
1704 case Decl::Function:
1705 case Decl::CXXMethod:
1706 case Decl::CXXConstructor:
1707 case Decl::CXXDestructor:
1708 case Decl::CXXConversion: {
1709 const FunctionDecl *Def = 0;
1710 if (cast<FunctionDecl>(D)->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001711 return MakeCXCursor(const_cast<FunctionDecl *>(Def), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001712 return clang_getNullCursor();
1713 }
1714
1715 case Decl::Var: {
1716 VarDecl *Var = cast<VarDecl>(D);
1717
1718 // Variables with initializers have definitions.
1719 const VarDecl *Def = 0;
1720 if (Var->getDefinition(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001721 return MakeCXCursor(const_cast<VarDecl *>(Def), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001722
1723 // extern and private_extern variables are not definitions.
1724 if (Var->hasExternalStorage())
1725 return clang_getNullCursor();
1726
1727 // In-line static data members do not have definitions.
1728 if (Var->isStaticDataMember() && !Var->isOutOfLine())
1729 return clang_getNullCursor();
1730
1731 // All other variables are themselves definitions.
1732 return C;
1733 }
1734
1735 case Decl::FunctionTemplate: {
1736 const FunctionDecl *Def = 0;
1737 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001738 return MakeCXCursor(Def->getDescribedFunctionTemplate(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001739 return clang_getNullCursor();
1740 }
1741
1742 case Decl::ClassTemplate: {
1743 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
1744 ->getDefinition(D->getASTContext()))
1745 return MakeCXCursor(
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001746 cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
1747 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001748 return clang_getNullCursor();
1749 }
1750
1751 case Decl::Using: {
1752 UsingDecl *Using = cast<UsingDecl>(D);
1753 CXCursor Def = clang_getNullCursor();
1754 for (UsingDecl::shadow_iterator S = Using->shadow_begin(),
1755 SEnd = Using->shadow_end();
1756 S != SEnd; ++S) {
1757 if (Def != clang_getNullCursor()) {
1758 // FIXME: We have no way to return multiple results.
1759 return clang_getNullCursor();
1760 }
1761
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001762 Def = clang_getCursorDefinition(MakeCXCursor((*S)->getTargetDecl(),
1763 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00001764 }
1765
1766 return Def;
1767 }
1768
1769 case Decl::UsingShadow:
1770 return clang_getCursorDefinition(
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001771 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
1772 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00001773
1774 case Decl::ObjCMethod: {
1775 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
1776 if (Method->isThisDeclarationADefinition())
1777 return C;
1778
1779 // Dig out the method definition in the associated
1780 // @implementation, if we have it.
1781 // FIXME: The ASTs should make finding the definition easier.
1782 if (ObjCInterfaceDecl *Class
1783 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
1784 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
1785 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
1786 Method->isInstanceMethod()))
1787 if (Def->isThisDeclarationADefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001788 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001789
1790 return clang_getNullCursor();
1791 }
1792
1793 case Decl::ObjCCategory:
1794 if (ObjCCategoryImplDecl *Impl
1795 = cast<ObjCCategoryDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001796 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001797 return clang_getNullCursor();
1798
1799 case Decl::ObjCProtocol:
1800 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
1801 return C;
1802 return clang_getNullCursor();
1803
1804 case Decl::ObjCInterface:
1805 // There are two notions of a "definition" for an Objective-C
1806 // class: the interface and its implementation. When we resolved a
1807 // reference to an Objective-C class, produce the @interface as
1808 // the definition; when we were provided with the interface,
1809 // produce the @implementation as the definition.
1810 if (WasReference) {
1811 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
1812 return C;
1813 } else if (ObjCImplementationDecl *Impl
1814 = cast<ObjCInterfaceDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001815 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001816 return clang_getNullCursor();
1817
1818 case Decl::ObjCProperty:
1819 // FIXME: We don't really know where to find the
1820 // ObjCPropertyImplDecls that implement this property.
1821 return clang_getNullCursor();
1822
1823 case Decl::ObjCCompatibleAlias:
1824 if (ObjCInterfaceDecl *Class
1825 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
1826 if (!Class->isForwardDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001827 return MakeCXCursor(Class, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001828
1829 return clang_getNullCursor();
1830
1831 case Decl::ObjCForwardProtocol: {
1832 ObjCForwardProtocolDecl *Forward = cast<ObjCForwardProtocolDecl>(D);
1833 if (Forward->protocol_size() == 1)
1834 return clang_getCursorDefinition(
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001835 MakeCXCursor(*Forward->protocol_begin(),
1836 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00001837
1838 // FIXME: Cannot return multiple definitions.
1839 return clang_getNullCursor();
1840 }
1841
1842 case Decl::ObjCClass: {
1843 ObjCClassDecl *Class = cast<ObjCClassDecl>(D);
1844 if (Class->size() == 1) {
1845 ObjCInterfaceDecl *IFace = Class->begin()->getInterface();
1846 if (!IFace->isForwardDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001847 return MakeCXCursor(IFace, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001848 return clang_getNullCursor();
1849 }
1850
1851 // FIXME: Cannot return multiple definitions.
1852 return clang_getNullCursor();
1853 }
1854
1855 case Decl::Friend:
1856 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001857 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00001858 return clang_getNullCursor();
1859
1860 case Decl::FriendTemplate:
1861 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001862 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00001863 return clang_getNullCursor();
1864 }
1865
1866 return clang_getNullCursor();
1867}
1868
1869unsigned clang_isCursorDefinition(CXCursor C) {
1870 if (!clang_isDeclaration(C.kind))
1871 return 0;
1872
1873 return clang_getCursorDefinition(C) == C;
1874}
1875
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001876void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00001877 const char **startBuf,
1878 const char **endBuf,
1879 unsigned *startLine,
1880 unsigned *startColumn,
1881 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001882 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00001883 assert(getCursorDecl(C) && "CXCursor has null decl");
1884 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00001885 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
1886 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekfb480492010-01-13 21:46:36 +00001887
Steve Naroff4ade6d62009-09-23 17:52:52 +00001888 SourceManager &SM = FD->getASTContext().getSourceManager();
1889 *startBuf = SM.getCharacterData(Body->getLBracLoc());
1890 *endBuf = SM.getCharacterData(Body->getRBracLoc());
1891 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
1892 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
1893 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
1894 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
1895}
Ted Kremenekfb480492010-01-13 21:46:36 +00001896
1897} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00001898
Ted Kremenekfb480492010-01-13 21:46:36 +00001899//===----------------------------------------------------------------------===//
Douglas Gregorfc8ea232010-01-26 17:06:03 +00001900// Token-based Operations.
1901//===----------------------------------------------------------------------===//
1902
1903/* CXToken layout:
1904 * int_data[0]: a CXTokenKind
1905 * int_data[1]: starting token location
1906 * int_data[2]: token length
1907 * int_data[3]: reserved
1908 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
1909 * otherwise unused.
1910 */
1911extern "C" {
1912
1913CXTokenKind clang_getTokenKind(CXToken CXTok) {
1914 return static_cast<CXTokenKind>(CXTok.int_data[0]);
1915}
1916
1917CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
1918 switch (clang_getTokenKind(CXTok)) {
1919 case CXToken_Identifier:
1920 case CXToken_Keyword:
1921 // We know we have an IdentifierInfo*, so use that.
1922 return CIndexer::createCXString(
1923 static_cast<IdentifierInfo *>(CXTok.ptr_data)->getNameStart());
1924
1925 case CXToken_Literal: {
1926 // We have stashed the starting pointer in the ptr_data field. Use it.
1927 const char *Text = static_cast<const char *>(CXTok.ptr_data);
1928 return CIndexer::createCXString(llvm::StringRef(Text, CXTok.int_data[2]),
1929 true);
1930 }
1931
1932 case CXToken_Punctuation:
1933 case CXToken_Comment:
1934 break;
1935 }
1936
1937 // We have to find the starting buffer pointer the hard way, by
1938 // deconstructing the source location.
1939 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
1940 if (!CXXUnit)
1941 return CIndexer::createCXString("");
1942
1943 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
1944 std::pair<FileID, unsigned> LocInfo
1945 = CXXUnit->getSourceManager().getDecomposedLoc(Loc);
1946 std::pair<const char *,const char *> Buffer
1947 = CXXUnit->getSourceManager().getBufferData(LocInfo.first);
1948
1949 return CIndexer::createCXString(llvm::StringRef(Buffer.first+LocInfo.second,
1950 CXTok.int_data[2]),
1951 true);
1952}
1953
1954CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
1955 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
1956 if (!CXXUnit)
1957 return clang_getNullLocation();
1958
1959 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
1960 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
1961}
1962
1963CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
1964 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
1965 if (!CXXUnit) {
1966 CXSourceRange Result = { 0, 0, 0 };
1967 return Result;
1968 }
1969
1970 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
1971 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
1972}
1973
1974void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
1975 CXToken **Tokens, unsigned *NumTokens) {
1976 if (Tokens)
1977 *Tokens = 0;
1978 if (NumTokens)
1979 *NumTokens = 0;
1980
1981 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
1982 if (!CXXUnit || !Tokens || !NumTokens)
1983 return;
1984
1985 SourceRange R = cxloc::translateSourceRange(Range);
1986 if (R.isInvalid())
1987 return;
1988
1989 SourceManager &SourceMgr = CXXUnit->getSourceManager();
1990 std::pair<FileID, unsigned> BeginLocInfo
1991 = SourceMgr.getDecomposedLoc(R.getBegin());
1992 std::pair<FileID, unsigned> EndLocInfo
1993 = SourceMgr.getDecomposedLoc(R.getEnd());
1994
1995 // Cannot tokenize across files.
1996 if (BeginLocInfo.first != EndLocInfo.first)
1997 return;
1998
1999 // Create a lexer
2000 std::pair<const char *,const char *> Buffer
2001 = SourceMgr.getBufferData(BeginLocInfo.first);
2002 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
2003 CXXUnit->getASTContext().getLangOptions(),
2004 Buffer.first, Buffer.first + BeginLocInfo.second, Buffer.second);
2005 Lex.SetCommentRetentionState(true);
2006
2007 // Lex tokens until we hit the end of the range.
2008 const char *EffectiveBufferEnd = Buffer.first + EndLocInfo.second;
2009 llvm::SmallVector<CXToken, 32> CXTokens;
2010 Token Tok;
2011 do {
2012 // Lex the next token
2013 Lex.LexFromRawLexer(Tok);
2014 if (Tok.is(tok::eof))
2015 break;
2016
2017 // Initialize the CXToken.
2018 CXToken CXTok;
2019
2020 // - Common fields
2021 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
2022 CXTok.int_data[2] = Tok.getLength();
2023 CXTok.int_data[3] = 0;
2024
2025 // - Kind-specific fields
2026 if (Tok.isLiteral()) {
2027 CXTok.int_data[0] = CXToken_Literal;
2028 CXTok.ptr_data = (void *)Tok.getLiteralData();
2029 } else if (Tok.is(tok::identifier)) {
2030 // Lookup the identifier to determine whether we have a
2031 std::pair<FileID, unsigned> LocInfo
2032 = SourceMgr.getDecomposedLoc(Tok.getLocation());
2033 const char *StartPos
2034 = CXXUnit->getSourceManager().getBufferData(LocInfo.first).first +
2035 LocInfo.second;
2036 IdentifierInfo *II
2037 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok, StartPos);
2038 CXTok.int_data[0] = II->getTokenID() == tok::identifier?
2039 CXToken_Identifier
2040 : CXToken_Keyword;
2041 CXTok.ptr_data = II;
2042 } else if (Tok.is(tok::comment)) {
2043 CXTok.int_data[0] = CXToken_Comment;
2044 CXTok.ptr_data = 0;
2045 } else {
2046 CXTok.int_data[0] = CXToken_Punctuation;
2047 CXTok.ptr_data = 0;
2048 }
2049 CXTokens.push_back(CXTok);
2050 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
2051
2052 if (CXTokens.empty())
2053 return;
2054
2055 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
2056 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
2057 *NumTokens = CXTokens.size();
2058}
2059
2060void clang_annotateTokens(CXTranslationUnit TU,
2061 CXToken *Tokens, unsigned NumTokens,
2062 CXCursor *Cursors) {
2063 // FIXME: Actually perform some meaningful lookup here.
2064 for (unsigned I = 0; I != NumTokens; ++I)
2065 Cursors[I] = clang_getNullCursor();
2066}
2067
2068void clang_disposeTokens(CXTranslationUnit TU,
2069 CXToken *Tokens, unsigned NumTokens) {
2070 if (Tokens)
2071 free(Tokens);
2072}
2073
2074} // end: extern "C"
2075
2076//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00002077// CXString Operations.
2078//===----------------------------------------------------------------------===//
2079
2080extern "C" {
2081const char *clang_getCString(CXString string) {
2082 return string.Spelling;
2083}
2084
2085void clang_disposeString(CXString string) {
2086 if (string.MustFreeString && string.Spelling)
2087 free((void*)string.Spelling);
2088}
Ted Kremenek04bb7162010-01-22 22:44:15 +00002089
Ted Kremenekfb480492010-01-13 21:46:36 +00002090} // end: extern "C"
Ted Kremenek04bb7162010-01-22 22:44:15 +00002091
2092//===----------------------------------------------------------------------===//
2093// Misc. utility functions.
2094//===----------------------------------------------------------------------===//
2095
2096extern "C" {
2097
2098const char *clang_getClangVersion() {
Ted Kremeneka18f1b82010-01-23 02:11:34 +00002099 return getClangFullVersion();
Ted Kremenek04bb7162010-01-22 22:44:15 +00002100}
2101
2102} // end: extern "C"
2103