blob: 443862279486613268238fc5f5a472ce9c2d468a [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"
Douglas Gregor5352ac02010-01-28 00:27:43 +000018#include "CIndexDiagnostic.h"
Ted Kremenekab188932010-01-05 19:32:54 +000019
Ted Kremenek04bb7162010-01-22 22:44:15 +000020#include "clang/Basic/Version.h"
Douglas Gregor936ea3b2010-01-28 00:56:43 +000021
Steve Naroff50398192009-08-28 15:28:48 +000022#include "clang/AST/DeclVisitor.h"
Steve Narofffb570422009-09-22 19:25:29 +000023#include "clang/AST/StmtVisitor.h"
Douglas Gregor7d0d40e2010-01-21 16:28:34 +000024#include "clang/AST/TypeLocVisitor.h"
Douglas Gregor936ea3b2010-01-28 00:56:43 +000025#include "clang/Frontend/FrontendDiagnostic.h"
Ted Kremenekd8210652010-01-06 23:43:31 +000026#include "clang/Lex/Lexer.h"
Douglas Gregor33e9abd2010-01-22 19:49:59 +000027#include "clang/Lex/Preprocessor.h"
Douglas Gregor02465752009-10-16 21:24:31 +000028#include "llvm/Support/MemoryBuffer.h"
Benjamin Kramer0829a832009-10-18 11:19:36 +000029#include "llvm/System/Program.h"
Ted Kremenekfc062212009-10-19 21:44:57 +000030
Ted Kremenekdb3d0da2010-01-05 20:55:39 +000031// Needed to define L_TMPNAM on some systems.
32#include <cstdio>
33
Steve Naroff50398192009-08-28 15:28:48 +000034using namespace clang;
Ted Kremenek16c440a2010-01-15 20:35:54 +000035using namespace clang::cxcursor;
Steve Naroff50398192009-08-28 15:28:48 +000036using namespace idx;
37
Ted Kremenek8a8da7d2010-01-06 03:42:32 +000038//===----------------------------------------------------------------------===//
39// Crash Reporting.
40//===----------------------------------------------------------------------===//
41
42#ifdef __APPLE__
Ted Kremenek29b72842010-01-07 22:49:05 +000043#ifndef NDEBUG
44#define USE_CRASHTRACER
Ted Kremenek8a8da7d2010-01-06 03:42:32 +000045#include "clang/Analysis/Support/SaveAndRestore.h"
46// Integrate with crash reporter.
47extern "C" const char *__crashreporter_info__;
Ted Kremenek29b72842010-01-07 22:49:05 +000048#define NUM_CRASH_STRINGS 16
49static unsigned crashtracer_counter = 0;
Ted Kremenek254ba7c2010-01-07 23:13:53 +000050static unsigned crashtracer_counter_id[NUM_CRASH_STRINGS] = { 0 };
Ted Kremenek29b72842010-01-07 22:49:05 +000051static const char *crashtracer_strings[NUM_CRASH_STRINGS] = { 0 };
52static const char *agg_crashtracer_strings[NUM_CRASH_STRINGS] = { 0 };
53
54static unsigned SetCrashTracerInfo(const char *str,
55 llvm::SmallString<1024> &AggStr) {
56
Ted Kremenek254ba7c2010-01-07 23:13:53 +000057 unsigned slot = 0;
Ted Kremenek29b72842010-01-07 22:49:05 +000058 while (crashtracer_strings[slot]) {
59 if (++slot == NUM_CRASH_STRINGS)
60 slot = 0;
61 }
62 crashtracer_strings[slot] = str;
Ted Kremenek254ba7c2010-01-07 23:13:53 +000063 crashtracer_counter_id[slot] = ++crashtracer_counter;
Ted Kremenek29b72842010-01-07 22:49:05 +000064
65 // We need to create an aggregate string because multiple threads
66 // may be in this method at one time. The crash reporter string
67 // will attempt to overapproximate the set of in-flight invocations
68 // of this function. Race conditions can still cause this goal
69 // to not be achieved.
70 {
71 llvm::raw_svector_ostream Out(AggStr);
72 for (unsigned i = 0; i < NUM_CRASH_STRINGS; ++i)
73 if (crashtracer_strings[i]) Out << crashtracer_strings[i] << '\n';
74 }
75 __crashreporter_info__ = agg_crashtracer_strings[slot] = AggStr.c_str();
76 return slot;
77}
78
79static void ResetCrashTracerInfo(unsigned slot) {
Ted Kremenek254ba7c2010-01-07 23:13:53 +000080 unsigned max_slot = 0;
81 unsigned max_value = 0;
82
83 crashtracer_strings[slot] = agg_crashtracer_strings[slot] = 0;
84
85 for (unsigned i = 0 ; i < NUM_CRASH_STRINGS; ++i)
86 if (agg_crashtracer_strings[i] &&
87 crashtracer_counter_id[i] > max_value) {
88 max_slot = i;
89 max_value = crashtracer_counter_id[i];
Ted Kremenek29b72842010-01-07 22:49:05 +000090 }
Ted Kremenek254ba7c2010-01-07 23:13:53 +000091
92 __crashreporter_info__ = agg_crashtracer_strings[max_slot];
Ted Kremenek29b72842010-01-07 22:49:05 +000093}
94
95namespace {
96class ArgsCrashTracerInfo {
97 llvm::SmallString<1024> CrashString;
98 llvm::SmallString<1024> AggregateString;
99 unsigned crashtracerSlot;
100public:
101 ArgsCrashTracerInfo(llvm::SmallVectorImpl<const char*> &Args)
102 : crashtracerSlot(0)
103 {
104 {
105 llvm::raw_svector_ostream Out(CrashString);
106 Out << "ClangCIndex [createTranslationUnitFromSourceFile]: clang";
107 for (llvm::SmallVectorImpl<const char*>::iterator I=Args.begin(),
108 E=Args.end(); I!=E; ++I)
109 Out << ' ' << *I;
110 }
111 crashtracerSlot = SetCrashTracerInfo(CrashString.c_str(),
112 AggregateString);
113 }
114
115 ~ArgsCrashTracerInfo() {
116 ResetCrashTracerInfo(crashtracerSlot);
117 }
118};
119}
120#endif
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000121#endif
122
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000123/// \brief The result of comparing two source ranges.
124enum RangeComparisonResult {
125 /// \brief Either the ranges overlap or one of the ranges is invalid.
126 RangeOverlap,
127
128 /// \brief The first range ends before the second range starts.
129 RangeBefore,
130
131 /// \brief The first range starts after the second range ends.
132 RangeAfter
133};
134
135/// \brief Compare two source ranges to determine their relative position in
136/// the translation unit.
137static RangeComparisonResult RangeCompare(SourceManager &SM,
138 SourceRange R1,
139 SourceRange R2) {
140 assert(R1.isValid() && "First range is invalid?");
141 assert(R2.isValid() && "Second range is invalid?");
Daniel Dunbard52864b2010-02-14 10:02:57 +0000142 if (R1.getEnd() == R2.getBegin() ||
143 SM.isBeforeInTranslationUnit(R1.getEnd(), R2.getBegin()))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000144 return RangeBefore;
Daniel Dunbard52864b2010-02-14 10:02:57 +0000145 if (R2.getEnd() == R1.getBegin() ||
146 SM.isBeforeInTranslationUnit(R2.getEnd(), R1.getBegin()))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000147 return RangeAfter;
148 return RangeOverlap;
149}
150
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000151/// \brief Translate a Clang source range into a CIndex source range.
152///
153/// Clang internally represents ranges where the end location points to the
154/// start of the token at the end. However, for external clients it is more
155/// useful to have a CXSourceRange be a proper half-open interval. This routine
156/// does the appropriate translation.
157CXSourceRange cxloc::translateSourceRange(const SourceManager &SM,
158 const LangOptions &LangOpts,
159 SourceRange R) {
160 // FIXME: This is largely copy-paste from
161 // TextDiagnosticPrinter::HighlightRange. When it is clear that this is what
162 // we want the two routines should be refactored.
163
164 // We want the last character in this location, so we will adjust the
165 // instantiation location accordingly.
166
167 // If the location is from a macro instantiation, get the end of the
168 // instantiation range.
169 SourceLocation EndLoc = R.getEnd();
170 SourceLocation InstLoc = SM.getInstantiationLoc(EndLoc);
171 if (EndLoc.isMacroID())
172 InstLoc = SM.getInstantiationRange(EndLoc).second;
173
174 // Measure the length token we're pointing at, so we can adjust the physical
175 // location in the file to point at the last character.
176 //
177 // FIXME: This won't cope with trigraphs or escaped newlines well. For that,
178 // we actually need a preprocessor, which isn't currently available
179 // here. Eventually, we'll switch the pointer data of
180 // CXSourceLocation/CXSourceRange to a translation unit (CXXUnit), so that the
181 // preprocessor will be available here. At that point, we can use
182 // Preprocessor::getLocForEndOfToken().
183 if (InstLoc.isValid()) {
184 unsigned Length = Lexer::MeasureTokenLength(InstLoc, SM, LangOpts);
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000185 EndLoc = EndLoc.getFileLocWithOffset(Length);
186 }
187
188 CXSourceRange Result = { { (void *)&SM, (void *)&LangOpts },
189 R.getBegin().getRawEncoding(),
190 EndLoc.getRawEncoding() };
191 return Result;
192}
Douglas Gregor1db19de2010-01-19 21:36:55 +0000193
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000194//===----------------------------------------------------------------------===//
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000195// Cursor visitor.
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000196//===----------------------------------------------------------------------===//
197
Steve Naroff89922f82009-08-31 00:59:03 +0000198namespace {
Ted Kremenekedc8aa62010-01-16 00:36:30 +0000199
Douglas Gregorb1373d02010-01-20 20:59:29 +0000200// Cursor visitor.
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000201class CursorVisitor : public DeclVisitor<CursorVisitor, bool>,
Douglas Gregora59e3902010-01-21 23:27:09 +0000202 public TypeLocVisitor<CursorVisitor, bool>,
203 public StmtVisitor<CursorVisitor, bool>
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000204{
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000205 /// \brief The translation unit we are traversing.
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000206 ASTUnit *TU;
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000207
208 /// \brief The parent cursor whose children we are traversing.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000209 CXCursor Parent;
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000210
211 /// \brief The declaration that serves at the parent of any statement or
212 /// expression nodes.
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000213 Decl *StmtParent;
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000214
215 /// \brief The visitor function.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000216 CXCursorVisitor Visitor;
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000217
218 /// \brief The opaque client data, to be passed along to the visitor.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000219 CXClientData ClientData;
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000220
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000221 // MaxPCHLevel - the maximum PCH level of declarations that we will pass on
222 // to the visitor. Declarations with a PCH level greater than this value will
223 // be suppressed.
224 unsigned MaxPCHLevel;
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000225
226 /// \brief When valid, a source range to which the cursor should restrict
227 /// its search.
228 SourceRange RegionOfInterest;
229
Douglas Gregorb1373d02010-01-20 20:59:29 +0000230 using DeclVisitor<CursorVisitor, bool>::Visit;
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000231 using TypeLocVisitor<CursorVisitor, bool>::Visit;
Douglas Gregora59e3902010-01-21 23:27:09 +0000232 using StmtVisitor<CursorVisitor, bool>::Visit;
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000233
234 /// \brief Determine whether this particular source range comes before, comes
235 /// after, or overlaps the region of interest.
236 ///
Daniel Dunbard52864b2010-02-14 10:02:57 +0000237 /// \param R a half-open source range retrieved from the abstract syntax tree.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000238 RangeComparisonResult CompareRegionOfInterest(SourceRange R);
239
Steve Naroff89922f82009-08-31 00:59:03 +0000240public:
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000241 CursorVisitor(ASTUnit *TU, CXCursorVisitor Visitor, CXClientData ClientData,
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000242 unsigned MaxPCHLevel,
243 SourceRange RegionOfInterest = SourceRange())
244 : TU(TU), Visitor(Visitor), ClientData(ClientData),
245 MaxPCHLevel(MaxPCHLevel), RegionOfInterest(RegionOfInterest)
Douglas Gregorb1373d02010-01-20 20:59:29 +0000246 {
247 Parent.kind = CXCursor_NoDeclFound;
248 Parent.data[0] = 0;
249 Parent.data[1] = 0;
250 Parent.data[2] = 0;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000251 StmtParent = 0;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000252 }
253
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000254 bool Visit(CXCursor Cursor, bool CheckedRegionOfInterest = false);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000255 bool VisitChildren(CXCursor Parent);
256
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000257 // Declaration visitors
Douglas Gregorb1373d02010-01-20 20:59:29 +0000258 bool VisitDeclContext(DeclContext *DC);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000259 bool VisitTranslationUnitDecl(TranslationUnitDecl *D);
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000260 bool VisitTypedefDecl(TypedefDecl *D);
261 bool VisitTagDecl(TagDecl *D);
262 bool VisitEnumConstantDecl(EnumConstantDecl *D);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000263 bool VisitDeclaratorDecl(DeclaratorDecl *DD);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000264 bool VisitFunctionDecl(FunctionDecl *ND);
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000265 bool VisitFieldDecl(FieldDecl *D);
266 bool VisitVarDecl(VarDecl *);
267 bool VisitObjCMethodDecl(ObjCMethodDecl *ND);
Douglas Gregora59e3902010-01-21 23:27:09 +0000268 bool VisitObjCContainerDecl(ObjCContainerDecl *D);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000269 bool VisitObjCCategoryDecl(ObjCCategoryDecl *ND);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000270 bool VisitObjCProtocolDecl(ObjCProtocolDecl *PID);
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000271 bool VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
272 bool VisitObjCImplDecl(ObjCImplDecl *D);
273 bool VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
274 bool VisitObjCImplementationDecl(ObjCImplementationDecl *D);
275 // FIXME: ObjCPropertyDecl requires TypeSourceInfo, getter/setter locations,
276 // etc.
277 // FIXME: ObjCCompatibleAliasDecl requires aliased-class locations.
278 bool VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D);
279 bool VisitObjCClassDecl(ObjCClassDecl *D);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000280
281 // Type visitors
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000282 // FIXME: QualifiedTypeLoc doesn't provide any location information
283 bool VisitBuiltinTypeLoc(BuiltinTypeLoc TL);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000284 bool VisitTypedefTypeLoc(TypedefTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000285 bool VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL);
286 bool VisitTagTypeLoc(TagTypeLoc TL);
287 // FIXME: TemplateTypeParmTypeLoc doesn't provide any location information
288 bool VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL);
289 bool VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL);
290 bool VisitPointerTypeLoc(PointerTypeLoc TL);
291 bool VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL);
292 bool VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL);
293 bool VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL);
294 bool VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL);
295 bool VisitFunctionTypeLoc(FunctionTypeLoc TL);
296 bool VisitArrayTypeLoc(ArrayTypeLoc TL);
Douglas Gregor2332c112010-01-21 20:48:56 +0000297 // FIXME: Implement for TemplateSpecializationTypeLoc
298 // FIXME: Implement visitors here when the unimplemented TypeLocs get
299 // implemented
300 bool VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL);
301 bool VisitTypeOfTypeLoc(TypeOfTypeLoc TL);
Douglas Gregora59e3902010-01-21 23:27:09 +0000302
303 // Statement visitors
304 bool VisitStmt(Stmt *S);
305 bool VisitDeclStmt(DeclStmt *S);
Douglas Gregorf5bab412010-01-22 01:00:11 +0000306 // FIXME: LabelStmt label?
307 bool VisitIfStmt(IfStmt *S);
308 bool VisitSwitchStmt(SwitchStmt *S);
Douglas Gregor263b47b2010-01-25 16:12:32 +0000309 bool VisitWhileStmt(WhileStmt *S);
310 bool VisitForStmt(ForStmt *S);
Douglas Gregor336fd812010-01-23 00:40:08 +0000311
312 // Expression visitors
313 bool VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E);
314 bool VisitExplicitCastExpr(ExplicitCastExpr *E);
315 bool VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
Steve Naroff89922f82009-08-31 00:59:03 +0000316};
Douglas Gregorb1373d02010-01-20 20:59:29 +0000317
Ted Kremenekab188932010-01-05 19:32:54 +0000318} // end anonymous namespace
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000319
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000320RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000321 return RangeCompare(TU->getSourceManager(), R, RegionOfInterest);
322}
323
Douglas Gregorb1373d02010-01-20 20:59:29 +0000324/// \brief Visit the given cursor and, if requested by the visitor,
325/// its children.
326///
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000327/// \param Cursor the cursor to visit.
328///
329/// \param CheckRegionOfInterest if true, then the caller already checked that
330/// this cursor is within the region of interest.
331///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000332/// \returns true if the visitation should be aborted, false if it
333/// should continue.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000334bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
Douglas Gregorb1373d02010-01-20 20:59:29 +0000335 if (clang_isInvalid(Cursor.kind))
336 return false;
337
338 if (clang_isDeclaration(Cursor.kind)) {
339 Decl *D = getCursorDecl(Cursor);
340 assert(D && "Invalid declaration cursor");
341 if (D->getPCHLevel() > MaxPCHLevel)
342 return false;
343
344 if (D->isImplicit())
345 return false;
346 }
347
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000348 // If we have a range of interest, and this cursor doesn't intersect with it,
349 // we're done.
350 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
Daniel Dunbarf408f322010-02-14 08:32:05 +0000351 SourceRange Range =
352 cxloc::translateCXSourceRange(clang_getCursorExtent(Cursor));
353 if (Range.isInvalid() || CompareRegionOfInterest(Range))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000354 return false;
355 }
356
Douglas Gregorb1373d02010-01-20 20:59:29 +0000357 switch (Visitor(Cursor, Parent, ClientData)) {
358 case CXChildVisit_Break:
359 return true;
360
361 case CXChildVisit_Continue:
362 return false;
363
364 case CXChildVisit_Recurse:
365 return VisitChildren(Cursor);
366 }
367
Douglas Gregorfd643772010-01-25 16:45:46 +0000368 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000369}
370
371/// \brief Visit the children of the given cursor.
372///
373/// \returns true if the visitation should be aborted, false if it
374/// should continue.
375bool CursorVisitor::VisitChildren(CXCursor Cursor) {
Douglas Gregora59e3902010-01-21 23:27:09 +0000376 if (clang_isReference(Cursor.kind)) {
377 // By definition, references have no children.
378 return false;
379 }
380
Douglas Gregorb1373d02010-01-20 20:59:29 +0000381 // Set the Parent field to Cursor, then back to its old value once we're
382 // done.
383 class SetParentRAII {
384 CXCursor &Parent;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000385 Decl *&StmtParent;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000386 CXCursor OldParent;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000387
Douglas Gregorb1373d02010-01-20 20:59:29 +0000388 public:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000389 SetParentRAII(CXCursor &Parent, Decl *&StmtParent, CXCursor NewParent)
390 : Parent(Parent), StmtParent(StmtParent), OldParent(Parent)
Douglas Gregorb1373d02010-01-20 20:59:29 +0000391 {
392 Parent = NewParent;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000393 if (clang_isDeclaration(Parent.kind))
394 StmtParent = getCursorDecl(Parent);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000395 }
396
397 ~SetParentRAII() {
398 Parent = OldParent;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000399 if (clang_isDeclaration(Parent.kind))
400 StmtParent = getCursorDecl(Parent);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000401 }
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000402 } SetParent(Parent, StmtParent, Cursor);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000403
404 if (clang_isDeclaration(Cursor.kind)) {
405 Decl *D = getCursorDecl(Cursor);
406 assert(D && "Invalid declaration cursor");
407 return Visit(D);
408 }
409
Douglas Gregora59e3902010-01-21 23:27:09 +0000410 if (clang_isStatement(Cursor.kind))
411 return Visit(getCursorStmt(Cursor));
412 if (clang_isExpression(Cursor.kind))
413 return Visit(getCursorExpr(Cursor));
414
Douglas Gregorb1373d02010-01-20 20:59:29 +0000415 if (clang_isTranslationUnit(Cursor.kind)) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000416 ASTUnit *CXXUnit = getCursorASTUnit(Cursor);
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000417 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
418 RegionOfInterest.isInvalid()) {
Douglas Gregor7b691f332010-01-20 21:13:59 +0000419 const std::vector<Decl*> &TLDs = CXXUnit->getTopLevelDecls();
420 for (std::vector<Decl*>::const_iterator it = TLDs.begin(),
421 ie = TLDs.end(); it != ie; ++it) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000422 if (Visit(MakeCXCursor(*it, CXXUnit), true))
Douglas Gregor7b691f332010-01-20 21:13:59 +0000423 return true;
424 }
425 } else {
426 return VisitDeclContext(
Douglas Gregorb1373d02010-01-20 20:59:29 +0000427 CXXUnit->getASTContext().getTranslationUnitDecl());
Douglas Gregor7b691f332010-01-20 21:13:59 +0000428 }
429
430 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000431 }
Douglas Gregora59e3902010-01-21 23:27:09 +0000432
Douglas Gregorb1373d02010-01-20 20:59:29 +0000433 // Nothing to visit at the moment.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000434 return false;
435}
436
Douglas Gregorb1373d02010-01-20 20:59:29 +0000437bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000438 for (DeclContext::decl_iterator
Douglas Gregorb1373d02010-01-20 20:59:29 +0000439 I = DC->decls_begin(), E = DC->decls_end(); I != E; ++I) {
Daniel Dunbard52864b2010-02-14 10:02:57 +0000440 CXCursor Cursor = MakeCXCursor(*I, TU);
441
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000442 if (RegionOfInterest.isValid()) {
Daniel Dunbard52864b2010-02-14 10:02:57 +0000443 SourceRange Range =
444 cxloc::translateCXSourceRange(clang_getCursorExtent(Cursor));
445 if (Range.isInvalid())
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000446 continue;
Daniel Dunbard52864b2010-02-14 10:02:57 +0000447
448 switch (CompareRegionOfInterest(Range)) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000449 case RangeBefore:
450 // This declaration comes before the region of interest; skip it.
451 continue;
452
453 case RangeAfter:
454 // This declaration comes after the region of interest; we're done.
455 return false;
456
457 case RangeOverlap:
458 // This declaration overlaps the region of interest; visit it.
459 break;
460 }
461 }
462
Daniel Dunbard52864b2010-02-14 10:02:57 +0000463 if (Visit(Cursor, true))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000464 return true;
465 }
466
467 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000468}
469
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000470bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
471 llvm_unreachable("Translation units are visited directly by Visit()");
472 return false;
473}
474
475bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
476 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
477 return Visit(TSInfo->getTypeLoc());
478
479 return false;
480}
481
482bool CursorVisitor::VisitTagDecl(TagDecl *D) {
483 return VisitDeclContext(D);
484}
485
486bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
487 if (Expr *Init = D->getInitExpr())
488 return Visit(MakeCXCursor(Init, StmtParent, TU));
489 return false;
490}
491
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000492bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
493 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
494 if (Visit(TSInfo->getTypeLoc()))
495 return true;
496
497 return false;
498}
499
Douglas Gregorb1373d02010-01-20 20:59:29 +0000500bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000501 if (VisitDeclaratorDecl(ND))
502 return true;
503
Douglas Gregora59e3902010-01-21 23:27:09 +0000504 if (ND->isThisDeclarationADefinition() &&
505 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
506 return true;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000507
508 return false;
509}
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000510
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000511bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
512 if (VisitDeclaratorDecl(D))
513 return true;
514
515 if (Expr *BitWidth = D->getBitWidth())
516 return Visit(MakeCXCursor(BitWidth, StmtParent, TU));
517
518 return false;
519}
520
521bool CursorVisitor::VisitVarDecl(VarDecl *D) {
522 if (VisitDeclaratorDecl(D))
523 return true;
524
525 if (Expr *Init = D->getInit())
526 return Visit(MakeCXCursor(Init, StmtParent, TU));
527
528 return false;
529}
530
531bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
532 // FIXME: We really need a TypeLoc covering Objective-C method declarations.
533 // At the moment, we don't have information about locations in the return
534 // type.
535 for (ObjCMethodDecl::param_iterator P = ND->param_begin(),
536 PEnd = ND->param_end();
537 P != PEnd; ++P) {
538 if (Visit(MakeCXCursor(*P, TU)))
539 return true;
540 }
541
542 if (ND->isThisDeclarationADefinition() &&
543 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
544 return true;
545
546 return false;
547}
548
Douglas Gregora59e3902010-01-21 23:27:09 +0000549bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
550 return VisitDeclContext(D);
551}
552
Douglas Gregorb1373d02010-01-20 20:59:29 +0000553bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000554 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
555 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000556 return true;
557
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000558 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
559 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
560 E = ND->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000561 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000562 return true;
563
Douglas Gregora59e3902010-01-21 23:27:09 +0000564 return VisitObjCContainerDecl(ND);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000565}
566
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000567bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
568 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
569 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
570 E = PID->protocol_end(); I != E; ++I, ++PL)
571 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
572 return true;
573
574 return VisitObjCContainerDecl(PID);
575}
576
Douglas Gregorb1373d02010-01-20 20:59:29 +0000577bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000578 // Issue callbacks for super class.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000579 if (D->getSuperClass() &&
580 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000581 D->getSuperClassLoc(),
582 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000583 return true;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000584
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000585 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
586 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
587 E = D->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000588 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000589 return true;
590
Douglas Gregora59e3902010-01-21 23:27:09 +0000591 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000592}
593
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000594bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
595 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000596}
597
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000598bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
599 if (Visit(MakeCursorObjCClassRef(D->getCategoryDecl()->getClassInterface(),
600 D->getLocation(), TU)))
601 return true;
602
603 return VisitObjCImplDecl(D);
604}
605
606bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
607#if 0
608 // Issue callbacks for super class.
609 // FIXME: No source location information!
610 if (D->getSuperClass() &&
611 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
612 D->getSuperClassLoc(),
613 TU)))
614 return true;
615#endif
616
617 return VisitObjCImplDecl(D);
618}
619
620bool CursorVisitor::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D) {
621 ObjCForwardProtocolDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
622 for (ObjCForwardProtocolDecl::protocol_iterator I = D->protocol_begin(),
623 E = D->protocol_end();
624 I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000625 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000626 return true;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000627
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000628 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000629}
630
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000631bool CursorVisitor::VisitObjCClassDecl(ObjCClassDecl *D) {
632 for (ObjCClassDecl::iterator C = D->begin(), CEnd = D->end(); C != CEnd; ++C)
633 if (Visit(MakeCursorObjCClassRef(C->getInterface(), C->getLocation(), TU)))
634 return true;
635
636 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000637}
638
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000639bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
640 ASTContext &Context = TU->getASTContext();
641
642 // Some builtin types (such as Objective-C's "id", "sel", and
643 // "Class") have associated declarations. Create cursors for those.
644 QualType VisitType;
645 switch (TL.getType()->getAs<BuiltinType>()->getKind()) {
646 case BuiltinType::Void:
647 case BuiltinType::Bool:
648 case BuiltinType::Char_U:
649 case BuiltinType::UChar:
650 case BuiltinType::Char16:
651 case BuiltinType::Char32:
652 case BuiltinType::UShort:
653 case BuiltinType::UInt:
654 case BuiltinType::ULong:
655 case BuiltinType::ULongLong:
656 case BuiltinType::UInt128:
657 case BuiltinType::Char_S:
658 case BuiltinType::SChar:
659 case BuiltinType::WChar:
660 case BuiltinType::Short:
661 case BuiltinType::Int:
662 case BuiltinType::Long:
663 case BuiltinType::LongLong:
664 case BuiltinType::Int128:
665 case BuiltinType::Float:
666 case BuiltinType::Double:
667 case BuiltinType::LongDouble:
668 case BuiltinType::NullPtr:
669 case BuiltinType::Overload:
670 case BuiltinType::Dependent:
671 break;
672
673 case BuiltinType::UndeducedAuto: // FIXME: Deserves a cursor?
674 break;
675
676 case BuiltinType::ObjCId:
677 VisitType = Context.getObjCIdType();
678 break;
679
680 case BuiltinType::ObjCClass:
681 VisitType = Context.getObjCClassType();
682 break;
683
684 case BuiltinType::ObjCSel:
685 VisitType = Context.getObjCSelType();
686 break;
687 }
688
689 if (!VisitType.isNull()) {
690 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
691 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
692 TU));
693 }
694
695 return false;
696}
697
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000698bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
699 return Visit(MakeCursorTypeRef(TL.getTypedefDecl(), TL.getNameLoc(), TU));
700}
701
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000702bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
703 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
704}
705
706bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
707 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
708}
709
710bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
711 if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
712 return true;
713
714 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
715 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
716 TU)))
717 return true;
718 }
719
720 return false;
721}
722
723bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
724 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseTypeLoc()))
725 return true;
726
727 if (TL.hasProtocolsAsWritten()) {
728 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
729 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I),
730 TL.getProtocolLoc(I),
731 TU)))
732 return true;
733 }
734 }
735
736 return false;
737}
738
739bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
740 return Visit(TL.getPointeeLoc());
741}
742
743bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
744 return Visit(TL.getPointeeLoc());
745}
746
747bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
748 return Visit(TL.getPointeeLoc());
749}
750
751bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
752 return Visit(TL.getPointeeLoc());
753}
754
755bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
756 return Visit(TL.getPointeeLoc());
757}
758
759bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
760 if (Visit(TL.getResultLoc()))
761 return true;
762
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000763 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
764 if (Visit(MakeCXCursor(TL.getArg(I), TU)))
765 return true;
766
767 return false;
768}
769
770bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
771 if (Visit(TL.getElementLoc()))
772 return true;
773
774 if (Expr *Size = TL.getSizeExpr())
775 return Visit(MakeCXCursor(Size, StmtParent, TU));
776
777 return false;
778}
779
Douglas Gregor2332c112010-01-21 20:48:56 +0000780bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
781 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
782}
783
784bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
785 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
786 return Visit(TSInfo->getTypeLoc());
787
788 return false;
789}
790
Douglas Gregora59e3902010-01-21 23:27:09 +0000791bool CursorVisitor::VisitStmt(Stmt *S) {
792 for (Stmt::child_iterator Child = S->child_begin(), ChildEnd = S->child_end();
793 Child != ChildEnd; ++Child) {
Daniel Dunbar54d67ca2010-01-25 00:40:30 +0000794 if (*Child && Visit(MakeCXCursor(*Child, StmtParent, TU)))
Douglas Gregora59e3902010-01-21 23:27:09 +0000795 return true;
796 }
797
798 return false;
799}
800
801bool CursorVisitor::VisitDeclStmt(DeclStmt *S) {
802 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
803 D != DEnd; ++D) {
Douglas Gregor263b47b2010-01-25 16:12:32 +0000804 if (*D && Visit(MakeCXCursor(*D, TU)))
Douglas Gregora59e3902010-01-21 23:27:09 +0000805 return true;
806 }
807
808 return false;
809}
810
Douglas Gregorf5bab412010-01-22 01:00:11 +0000811bool CursorVisitor::VisitIfStmt(IfStmt *S) {
812 if (VarDecl *Var = S->getConditionVariable()) {
813 if (Visit(MakeCXCursor(Var, TU)))
814 return true;
Douglas Gregor263b47b2010-01-25 16:12:32 +0000815 }
Douglas Gregorf5bab412010-01-22 01:00:11 +0000816
Douglas Gregor263b47b2010-01-25 16:12:32 +0000817 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
818 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +0000819 if (S->getThen() && Visit(MakeCXCursor(S->getThen(), StmtParent, TU)))
820 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +0000821 if (S->getElse() && Visit(MakeCXCursor(S->getElse(), StmtParent, TU)))
822 return true;
823
824 return false;
825}
826
827bool CursorVisitor::VisitSwitchStmt(SwitchStmt *S) {
828 if (VarDecl *Var = S->getConditionVariable()) {
829 if (Visit(MakeCXCursor(Var, TU)))
830 return true;
Douglas Gregor263b47b2010-01-25 16:12:32 +0000831 }
832
833 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
834 return true;
835 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
836 return true;
837
838 return false;
839}
840
841bool CursorVisitor::VisitWhileStmt(WhileStmt *S) {
842 if (VarDecl *Var = S->getConditionVariable()) {
843 if (Visit(MakeCXCursor(Var, TU)))
844 return true;
845 }
846
847 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
848 return true;
849 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
Douglas Gregorf5bab412010-01-22 01:00:11 +0000850 return true;
851
Douglas Gregor263b47b2010-01-25 16:12:32 +0000852 return false;
853}
854
855bool CursorVisitor::VisitForStmt(ForStmt *S) {
856 if (S->getInit() && Visit(MakeCXCursor(S->getInit(), StmtParent, TU)))
857 return true;
858 if (VarDecl *Var = S->getConditionVariable()) {
859 if (Visit(MakeCXCursor(Var, TU)))
860 return true;
861 }
862
863 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
864 return true;
865 if (S->getInc() && Visit(MakeCXCursor(S->getInc(), StmtParent, TU)))
866 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +0000867 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
868 return true;
869
870 return false;
871}
872
Douglas Gregor336fd812010-01-23 00:40:08 +0000873bool CursorVisitor::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E) {
874 if (E->isArgumentType()) {
875 if (TypeSourceInfo *TSInfo = E->getArgumentTypeInfo())
876 return Visit(TSInfo->getTypeLoc());
877
878 return false;
879 }
880
881 return VisitExpr(E);
882}
883
884bool CursorVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
885 if (TypeSourceInfo *TSInfo = E->getTypeInfoAsWritten())
886 if (Visit(TSInfo->getTypeLoc()))
887 return true;
888
889 return VisitCastExpr(E);
890}
891
892bool CursorVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
893 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
894 if (Visit(TSInfo->getTypeLoc()))
895 return true;
896
897 return VisitExpr(E);
898}
899
Daniel Dunbar140fce22010-01-12 02:34:07 +0000900CXString CIndexer::createCXString(const char *String, bool DupString){
Benjamin Kramer62cf3222009-11-09 19:13:48 +0000901 CXString Str;
902 if (DupString) {
903 Str.Spelling = strdup(String);
904 Str.MustFreeString = 1;
905 } else {
906 Str.Spelling = String;
907 Str.MustFreeString = 0;
908 }
909 return Str;
910}
911
Douglas Gregorfc8ea232010-01-26 17:06:03 +0000912CXString CIndexer::createCXString(llvm::StringRef String, bool DupString) {
913 CXString Result;
914 if (DupString || (!String.empty() && String.data()[String.size()] != 0)) {
915 char *Spelling = (char *)malloc(String.size() + 1);
916 memmove(Spelling, String.data(), String.size());
917 Spelling[String.size()] = 0;
918 Result.Spelling = Spelling;
919 Result.MustFreeString = 1;
920 } else {
921 Result.Spelling = String.data();
922 Result.MustFreeString = 0;
923 }
924 return Result;
925}
926
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000927extern "C" {
Douglas Gregor936ea3b2010-01-28 00:56:43 +0000928CXIndex clang_createIndex(int excludeDeclarationsFromPCH) {
Douglas Gregora030b7c2010-01-22 20:35:53 +0000929 CIndexer *CIdxr = new CIndexer();
Steve Naroffe56b4ba2009-10-20 14:46:24 +0000930 if (excludeDeclarationsFromPCH)
931 CIdxr->setOnlyLocalDecls();
Steve Naroffe56b4ba2009-10-20 14:46:24 +0000932 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +0000933}
934
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000935void clang_disposeIndex(CXIndex CIdx) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +0000936 if (CIdx)
937 delete static_cast<CIndexer *>(CIdx);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +0000938}
939
Daniel Dunbar8506dde2009-12-03 01:54:28 +0000940void clang_setUseExternalASTGeneration(CXIndex CIdx, int value) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +0000941 if (CIdx) {
942 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
943 CXXIdx->setUseExternalASTGeneration(value);
944 }
Daniel Dunbar8506dde2009-12-03 01:54:28 +0000945}
946
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000947CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
Douglas Gregor5352ac02010-01-28 00:27:43 +0000948 const char *ast_filename,
949 CXDiagnosticCallback diag_callback,
950 CXClientData diag_client_data) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +0000951 if (!CIdx)
952 return 0;
953
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000954 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000955
Douglas Gregor5352ac02010-01-28 00:27:43 +0000956 // Configure the diagnostics.
957 DiagnosticOptions DiagOpts;
958 llvm::OwningPtr<Diagnostic> Diags;
959 Diags.reset(CompilerInstance::createDiagnostics(DiagOpts, 0, 0));
960 CIndexDiagnosticClient DiagClient(diag_callback, diag_client_data);
961 Diags->setClient(&DiagClient);
962
963 return ASTUnit::LoadFromPCHFile(ast_filename, *Diags,
Daniel Dunbar5262fda2009-12-03 01:45:44 +0000964 CXXIdx->getOnlyLocalDecls(),
965 /* UseBumpAllocator = */ true);
Steve Naroff600866c2009-08-27 19:51:58 +0000966}
967
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000968CXTranslationUnit
969clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
970 const char *source_filename,
971 int num_command_line_args,
Douglas Gregor4db64a42010-01-23 00:14:00 +0000972 const char **command_line_args,
973 unsigned num_unsaved_files,
Douglas Gregor5352ac02010-01-28 00:27:43 +0000974 struct CXUnsavedFile *unsaved_files,
975 CXDiagnosticCallback diag_callback,
976 CXClientData diag_client_data) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +0000977 if (!CIdx)
978 return 0;
979
Steve Naroffe56b4ba2009-10-20 14:46:24 +0000980 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
981
Douglas Gregor5352ac02010-01-28 00:27:43 +0000982 // Configure the diagnostics.
983 DiagnosticOptions DiagOpts;
984 llvm::OwningPtr<Diagnostic> Diags;
985 Diags.reset(CompilerInstance::createDiagnostics(DiagOpts, 0, 0));
986 CIndexDiagnosticClient DiagClient(diag_callback, diag_client_data);
987 Diags->setClient(&DiagClient);
988
Douglas Gregor4db64a42010-01-23 00:14:00 +0000989 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
990 for (unsigned I = 0; I != num_unsaved_files; ++I) {
991 const llvm::MemoryBuffer *Buffer
992 = llvm::MemoryBuffer::getMemBuffer(unsaved_files[I].Contents,
993 unsaved_files[I].Contents + unsaved_files[I].Length,
994 unsaved_files[I].Filename);
995 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
996 Buffer));
997 }
998
Daniel Dunbar8506dde2009-12-03 01:54:28 +0000999 if (!CXXIdx->getUseExternalASTGeneration()) {
1000 llvm::SmallVector<const char *, 16> Args;
1001
1002 // The 'source_filename' argument is optional. If the caller does not
1003 // specify it then it is assumed that the source file is specified
1004 // in the actual argument list.
1005 if (source_filename)
1006 Args.push_back(source_filename);
1007 Args.insert(Args.end(), command_line_args,
1008 command_line_args + num_command_line_args);
1009
Douglas Gregor5352ac02010-01-28 00:27:43 +00001010 unsigned NumErrors = Diags->getNumErrors();
Ted Kremenek8a8da7d2010-01-06 03:42:32 +00001011
Ted Kremenek29b72842010-01-07 22:49:05 +00001012#ifdef USE_CRASHTRACER
1013 ArgsCrashTracerInfo ACTI(Args);
Ted Kremenek8a8da7d2010-01-06 03:42:32 +00001014#endif
1015
Daniel Dunbar94220972009-12-05 02:17:18 +00001016 llvm::OwningPtr<ASTUnit> Unit(
1017 ASTUnit::LoadFromCommandLine(Args.data(), Args.data() + Args.size(),
Douglas Gregor5352ac02010-01-28 00:27:43 +00001018 *Diags,
Daniel Dunbar869824e2009-12-13 03:46:13 +00001019 CXXIdx->getClangResourcesPath(),
Daniel Dunbar94220972009-12-05 02:17:18 +00001020 CXXIdx->getOnlyLocalDecls(),
Douglas Gregor4db64a42010-01-23 00:14:00 +00001021 /* UseBumpAllocator = */ true,
1022 RemappedFiles.data(),
1023 RemappedFiles.size()));
Ted Kremenek29b72842010-01-07 22:49:05 +00001024
Daniel Dunbar94220972009-12-05 02:17:18 +00001025 // FIXME: Until we have broader testing, just drop the entire AST if we
1026 // encountered an error.
Douglas Gregor5352ac02010-01-28 00:27:43 +00001027 if (NumErrors != Diags->getNumErrors())
Daniel Dunbar94220972009-12-05 02:17:18 +00001028 return 0;
1029
1030 return Unit.take();
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001031 }
1032
Ted Kremenek139ba862009-10-22 00:03:57 +00001033 // Build up the arguments for invoking 'clang'.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001034 std::vector<const char *> argv;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001035
Ted Kremenek139ba862009-10-22 00:03:57 +00001036 // First add the complete path to the 'clang' executable.
1037 llvm::sys::Path ClangPath = static_cast<CIndexer *>(CIdx)->getClangPath();
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00001038 argv.push_back(ClangPath.c_str());
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001039
Ted Kremenek139ba862009-10-22 00:03:57 +00001040 // Add the '-emit-ast' option as our execution mode for 'clang'.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001041 argv.push_back("-emit-ast");
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001042
Ted Kremenek139ba862009-10-22 00:03:57 +00001043 // The 'source_filename' argument is optional. If the caller does not
1044 // specify it then it is assumed that the source file is specified
1045 // in the actual argument list.
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001046 if (source_filename)
1047 argv.push_back(source_filename);
Ted Kremenek139ba862009-10-22 00:03:57 +00001048
Steve Naroff37b5ac22009-10-15 20:50:09 +00001049 // Generate a temporary name for the AST file.
Ted Kremenek139ba862009-10-22 00:03:57 +00001050 argv.push_back("-o");
Steve Naroff37b5ac22009-10-15 20:50:09 +00001051 char astTmpFile[L_tmpnam];
Ted Kremenek74cd0692009-10-15 23:21:22 +00001052 argv.push_back(tmpnam(astTmpFile));
Ted Kremenek139ba862009-10-22 00:03:57 +00001053
Douglas Gregor4db64a42010-01-23 00:14:00 +00001054 // Remap any unsaved files to temporary files.
1055 std::vector<llvm::sys::Path> TemporaryFiles;
1056 std::vector<std::string> RemapArgs;
1057 if (RemapFiles(num_unsaved_files, unsaved_files, RemapArgs, TemporaryFiles))
1058 return 0;
1059
1060 // The pointers into the elements of RemapArgs are stable because we
1061 // won't be adding anything to RemapArgs after this point.
1062 for (unsigned i = 0, e = RemapArgs.size(); i != e; ++i)
1063 argv.push_back(RemapArgs[i].c_str());
1064
Ted Kremenek139ba862009-10-22 00:03:57 +00001065 // Process the compiler options, stripping off '-o', '-c', '-fsyntax-only'.
1066 for (int i = 0; i < num_command_line_args; ++i)
1067 if (const char *arg = command_line_args[i]) {
1068 if (strcmp(arg, "-o") == 0) {
1069 ++i; // Also skip the matching argument.
1070 continue;
1071 }
1072 if (strcmp(arg, "-emit-ast") == 0 ||
1073 strcmp(arg, "-c") == 0 ||
1074 strcmp(arg, "-fsyntax-only") == 0) {
1075 continue;
1076 }
1077
1078 // Keep the argument.
1079 argv.push_back(arg);
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001080 }
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001081
Douglas Gregord93256e2010-01-28 06:00:51 +00001082 // Generate a temporary name for the diagnostics file.
1083 char tmpFileResults[L_tmpnam];
1084 char *tmpResultsFileName = tmpnam(tmpFileResults);
1085 llvm::sys::Path DiagnosticsFile(tmpResultsFileName);
1086 TemporaryFiles.push_back(DiagnosticsFile);
1087 argv.push_back("-fdiagnostics-binary");
1088
Ted Kremenek139ba862009-10-22 00:03:57 +00001089 // Add the null terminator.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001090 argv.push_back(NULL);
1091
Ted Kremenekfeb15e32009-10-26 22:14:08 +00001092 // Invoke 'clang'.
1093 llvm::sys::Path DevNull; // leave empty, causes redirection to /dev/null
1094 // on Unix or NUL (Windows).
Ted Kremenek379afec2009-10-22 03:24:01 +00001095 std::string ErrMsg;
Douglas Gregord93256e2010-01-28 06:00:51 +00001096 const llvm::sys::Path *Redirects[] = { &DevNull, &DevNull, &DiagnosticsFile,
1097 NULL };
Ted Kremenek379afec2009-10-22 03:24:01 +00001098 llvm::sys::Program::ExecuteAndWait(ClangPath, &argv[0], /* env */ NULL,
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001099 /* redirects */ &Redirects[0],
Ted Kremenek379afec2009-10-22 03:24:01 +00001100 /* secondsToWait */ 0, /* memoryLimits */ 0, &ErrMsg);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001101
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001102 if (!ErrMsg.empty()) {
1103 std::string AllArgs;
Ted Kremenek379afec2009-10-22 03:24:01 +00001104 for (std::vector<const char*>::iterator I = argv.begin(), E = argv.end();
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001105 I != E; ++I) {
1106 AllArgs += ' ';
Ted Kremenek779e5f42009-10-26 22:08:39 +00001107 if (*I)
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001108 AllArgs += *I;
Ted Kremenek779e5f42009-10-26 22:08:39 +00001109 }
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001110
1111 Diags->Report(diag::err_fe_clang) << AllArgs << ErrMsg;
Ted Kremenek379afec2009-10-22 03:24:01 +00001112 }
Benjamin Kramer0829a832009-10-18 11:19:36 +00001113
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001114 // FIXME: Parse the (redirected) standard error to emit diagnostics.
1115
Douglas Gregor5352ac02010-01-28 00:27:43 +00001116 ASTUnit *ATU = ASTUnit::LoadFromPCHFile(astTmpFile, *Diags,
Douglas Gregor4db64a42010-01-23 00:14:00 +00001117 CXXIdx->getOnlyLocalDecls(),
1118 /* UseBumpAllocator = */ true,
1119 RemappedFiles.data(),
1120 RemappedFiles.size());
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001121 if (ATU)
1122 ATU->unlinkTemporaryFile();
Douglas Gregor4db64a42010-01-23 00:14:00 +00001123
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00001124 // FIXME: Currently we don't report diagnostics on invalid ASTs.
1125 if (ATU)
1126 ReportSerializedDiagnostics(DiagnosticsFile, *Diags,
1127 num_unsaved_files, unsaved_files,
1128 ATU->getASTContext().getLangOptions());
Douglas Gregord93256e2010-01-28 06:00:51 +00001129
Douglas Gregor4db64a42010-01-23 00:14:00 +00001130 for (unsigned i = 0, e = TemporaryFiles.size(); i != e; ++i)
1131 TemporaryFiles[i].eraseFromDisk();
1132
Steve Naroffe19944c2009-10-15 22:23:48 +00001133 return ATU;
Steve Naroff5b7d8e22009-10-15 20:04:39 +00001134}
1135
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001136void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001137 if (CTUnit)
1138 delete static_cast<ASTUnit *>(CTUnit);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00001139}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001140
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001141CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001142 if (!CTUnit)
1143 return CIndexer::createCXString("");
1144
Steve Naroff77accc12009-09-03 18:19:54 +00001145 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit);
Ted Kremenek4b333d22010-01-12 00:36:38 +00001146 return CIndexer::createCXString(CXXUnit->getOriginalSourceFileName().c_str(),
1147 true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +00001148}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +00001149
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001150CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001151 CXCursor Result = { CXCursor_TranslationUnit, { 0, 0, TU } };
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001152 return Result;
1153}
1154
Ted Kremenekfb480492010-01-13 21:46:36 +00001155} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +00001156
Ted Kremenekfb480492010-01-13 21:46:36 +00001157//===----------------------------------------------------------------------===//
Douglas Gregor1db19de2010-01-19 21:36:55 +00001158// CXSourceLocation and CXSourceRange Operations.
1159//===----------------------------------------------------------------------===//
1160
Douglas Gregorb9790342010-01-22 21:44:22 +00001161extern "C" {
1162CXSourceLocation clang_getNullLocation() {
Douglas Gregor5352ac02010-01-28 00:27:43 +00001163 CXSourceLocation Result = { { 0, 0 }, 0 };
Douglas Gregorb9790342010-01-22 21:44:22 +00001164 return Result;
1165}
1166
1167unsigned clang_equalLocations(CXSourceLocation loc1, CXSourceLocation loc2) {
Daniel Dunbar90a6b9e2010-01-30 23:58:27 +00001168 return (loc1.ptr_data[0] == loc2.ptr_data[0] &&
1169 loc1.ptr_data[1] == loc2.ptr_data[1] &&
1170 loc1.int_data == loc2.int_data);
Douglas Gregorb9790342010-01-22 21:44:22 +00001171}
1172
1173CXSourceLocation clang_getLocation(CXTranslationUnit tu,
1174 CXFile file,
1175 unsigned line,
1176 unsigned column) {
1177 if (!tu)
1178 return clang_getNullLocation();
1179
1180 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
1181 SourceLocation SLoc
1182 = CXXUnit->getSourceManager().getLocation(
1183 static_cast<const FileEntry *>(file),
1184 line, column);
1185
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00001186 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
Douglas Gregorb9790342010-01-22 21:44:22 +00001187}
1188
Douglas Gregor5352ac02010-01-28 00:27:43 +00001189CXSourceRange clang_getNullRange() {
1190 CXSourceRange Result = { { 0, 0 }, 0, 0 };
1191 return Result;
1192}
Daniel Dunbard52864b2010-02-14 10:02:57 +00001193
Douglas Gregor5352ac02010-01-28 00:27:43 +00001194CXSourceRange clang_getRange(CXSourceLocation begin, CXSourceLocation end) {
1195 if (begin.ptr_data[0] != end.ptr_data[0] ||
1196 begin.ptr_data[1] != end.ptr_data[1])
1197 return clang_getNullRange();
1198
1199 CXSourceRange Result = { { begin.ptr_data[0], begin.ptr_data[1] },
1200 begin.int_data, end.int_data };
Douglas Gregorb9790342010-01-22 21:44:22 +00001201 return Result;
1202}
1203
Douglas Gregor46766dc2010-01-26 19:19:08 +00001204void clang_getInstantiationLocation(CXSourceLocation location,
1205 CXFile *file,
1206 unsigned *line,
1207 unsigned *column,
1208 unsigned *offset) {
Douglas Gregor1db19de2010-01-19 21:36:55 +00001209 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
1210
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00001211 if (!location.ptr_data[0] || Loc.isInvalid()) {
Douglas Gregor46766dc2010-01-26 19:19:08 +00001212 if (file)
1213 *file = 0;
1214 if (line)
1215 *line = 0;
1216 if (column)
1217 *column = 0;
1218 if (offset)
1219 *offset = 0;
1220 return;
1221 }
1222
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00001223 const SourceManager &SM =
1224 *static_cast<const SourceManager*>(location.ptr_data[0]);
Douglas Gregor1db19de2010-01-19 21:36:55 +00001225 SourceLocation InstLoc = SM.getInstantiationLoc(Loc);
Douglas Gregor1db19de2010-01-19 21:36:55 +00001226
1227 if (file)
1228 *file = (void *)SM.getFileEntryForID(SM.getFileID(InstLoc));
1229 if (line)
1230 *line = SM.getInstantiationLineNumber(InstLoc);
1231 if (column)
1232 *column = SM.getInstantiationColumnNumber(InstLoc);
Douglas Gregore69517c2010-01-26 03:07:15 +00001233 if (offset)
Douglas Gregor46766dc2010-01-26 19:19:08 +00001234 *offset = SM.getDecomposedLoc(InstLoc).second;
Douglas Gregore69517c2010-01-26 03:07:15 +00001235}
1236
Douglas Gregor1db19de2010-01-19 21:36:55 +00001237CXSourceLocation clang_getRangeStart(CXSourceRange range) {
Douglas Gregor5352ac02010-01-28 00:27:43 +00001238 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
1239 range.begin_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00001240 return Result;
1241}
1242
1243CXSourceLocation clang_getRangeEnd(CXSourceRange range) {
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00001244 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00001245 range.end_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00001246 return Result;
1247}
1248
Douglas Gregorb9790342010-01-22 21:44:22 +00001249} // end: extern "C"
1250
Douglas Gregor1db19de2010-01-19 21:36:55 +00001251//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00001252// CXFile Operations.
1253//===----------------------------------------------------------------------===//
1254
1255extern "C" {
Steve Naroff88145032009-10-27 14:35:18 +00001256const char *clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00001257 if (!SFile)
1258 return 0;
1259
Steve Naroff88145032009-10-27 14:35:18 +00001260 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
1261 return FEnt->getName();
1262}
1263
1264time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00001265 if (!SFile)
1266 return 0;
1267
Steve Naroff88145032009-10-27 14:35:18 +00001268 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
1269 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +00001270}
Douglas Gregorb9790342010-01-22 21:44:22 +00001271
1272CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
1273 if (!tu)
1274 return 0;
1275
1276 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
1277
1278 FileManager &FMgr = CXXUnit->getFileManager();
1279 const FileEntry *File = FMgr.getFile(file_name, file_name+strlen(file_name));
1280 return const_cast<FileEntry *>(File);
1281}
1282
Ted Kremenekfb480492010-01-13 21:46:36 +00001283} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +00001284
Ted Kremenekfb480492010-01-13 21:46:36 +00001285//===----------------------------------------------------------------------===//
1286// CXCursor Operations.
1287//===----------------------------------------------------------------------===//
1288
Ted Kremenekfb480492010-01-13 21:46:36 +00001289static Decl *getDeclFromExpr(Stmt *E) {
1290 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
1291 return RefExpr->getDecl();
1292 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
1293 return ME->getMemberDecl();
1294 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
1295 return RE->getDecl();
1296
1297 if (CallExpr *CE = dyn_cast<CallExpr>(E))
1298 return getDeclFromExpr(CE->getCallee());
1299 if (CastExpr *CE = dyn_cast<CastExpr>(E))
1300 return getDeclFromExpr(CE->getSubExpr());
1301 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
1302 return OME->getMethodDecl();
1303
1304 return 0;
1305}
1306
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00001307static SourceLocation getLocationFromExpr(Expr *E) {
1308 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
1309 return /*FIXME:*/Msg->getLeftLoc();
1310 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
1311 return DRE->getLocation();
1312 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
1313 return Member->getMemberLoc();
1314 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
1315 return Ivar->getLocation();
1316 return E->getLocStart();
1317}
1318
Ted Kremenekfb480492010-01-13 21:46:36 +00001319extern "C" {
Douglas Gregorb1373d02010-01-20 20:59:29 +00001320
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001321unsigned clang_visitChildren(CXCursor parent,
Douglas Gregorb1373d02010-01-20 20:59:29 +00001322 CXCursorVisitor visitor,
1323 CXClientData client_data) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001324 ASTUnit *CXXUnit = getCursorASTUnit(parent);
Douglas Gregorb1373d02010-01-20 20:59:29 +00001325
1326 unsigned PCHLevel = Decl::MaxPCHLevel;
1327
1328 // Set the PCHLevel to filter out unwanted decls if requested.
1329 if (CXXUnit->getOnlyLocalDecls()) {
1330 PCHLevel = 0;
1331
1332 // If the main input was an AST, bump the level.
1333 if (CXXUnit->isMainFileAST())
1334 ++PCHLevel;
1335 }
1336
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001337 CursorVisitor CursorVis(CXXUnit, visitor, client_data, PCHLevel);
Douglas Gregorb1373d02010-01-20 20:59:29 +00001338 return CursorVis.VisitChildren(parent);
1339}
1340
Douglas Gregor78205d42010-01-20 21:45:58 +00001341static CXString getDeclSpelling(Decl *D) {
1342 NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
1343 if (!ND)
1344 return CIndexer::createCXString("");
1345
1346 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
1347 return CIndexer::createCXString(OMD->getSelector().getAsString().c_str(),
1348 true);
1349
1350 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
1351 // No, this isn't the same as the code below. getIdentifier() is non-virtual
1352 // and returns different names. NamedDecl returns the class name and
1353 // ObjCCategoryImplDecl returns the category name.
1354 return CIndexer::createCXString(CIMP->getIdentifier()->getNameStart());
1355
1356 if (ND->getIdentifier())
1357 return CIndexer::createCXString(ND->getIdentifier()->getNameStart());
1358
1359 return CIndexer::createCXString("");
1360}
1361
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001362CXString clang_getCursorSpelling(CXCursor C) {
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001363 if (clang_isTranslationUnit(C.kind))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001364 return clang_getTranslationUnitSpelling(C.data[2]);
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001365
Steve Narofff334b4e2009-09-02 18:26:48 +00001366 if (clang_isReference(C.kind)) {
1367 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00001368 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +00001369 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
1370 return CIndexer::createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00001371 }
1372 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +00001373 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
1374 return CIndexer::createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00001375 }
1376 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +00001377 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +00001378 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenek4b333d22010-01-12 00:36:38 +00001379 return CIndexer::createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00001380 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001381 case CXCursor_TypeRef: {
1382 TypeDecl *Type = getCursorTypeRef(C).first;
1383 assert(Type && "Missing type decl");
1384
1385 return CIndexer::createCXString(
1386 getCursorContext(C).getTypeDeclType(Type).getAsString().c_str(),
1387 true);
1388 }
1389
Daniel Dunbaracca7252009-11-30 20:42:49 +00001390 default:
Ted Kremenek4b333d22010-01-12 00:36:38 +00001391 return CIndexer::createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +00001392 }
1393 }
Douglas Gregor97b98722010-01-19 23:20:36 +00001394
1395 if (clang_isExpression(C.kind)) {
1396 Decl *D = getDeclFromExpr(getCursorExpr(C));
1397 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +00001398 return getDeclSpelling(D);
Douglas Gregor97b98722010-01-19 23:20:36 +00001399 return CIndexer::createCXString("");
1400 }
1401
Douglas Gregor60cbfac2010-01-25 16:56:17 +00001402 if (clang_isDeclaration(C.kind))
1403 return getDeclSpelling(getCursorDecl(C));
1404
1405 return CIndexer::createCXString("");
Steve Narofff334b4e2009-09-02 18:26:48 +00001406}
1407
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001408const char *clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00001409 switch (Kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00001410 case CXCursor_FunctionDecl: return "FunctionDecl";
1411 case CXCursor_TypedefDecl: return "TypedefDecl";
1412 case CXCursor_EnumDecl: return "EnumDecl";
1413 case CXCursor_EnumConstantDecl: return "EnumConstantDecl";
1414 case CXCursor_StructDecl: return "StructDecl";
1415 case CXCursor_UnionDecl: return "UnionDecl";
1416 case CXCursor_ClassDecl: return "ClassDecl";
1417 case CXCursor_FieldDecl: return "FieldDecl";
1418 case CXCursor_VarDecl: return "VarDecl";
1419 case CXCursor_ParmDecl: return "ParmDecl";
1420 case CXCursor_ObjCInterfaceDecl: return "ObjCInterfaceDecl";
1421 case CXCursor_ObjCCategoryDecl: return "ObjCCategoryDecl";
1422 case CXCursor_ObjCProtocolDecl: return "ObjCProtocolDecl";
1423 case CXCursor_ObjCPropertyDecl: return "ObjCPropertyDecl";
1424 case CXCursor_ObjCIvarDecl: return "ObjCIvarDecl";
1425 case CXCursor_ObjCInstanceMethodDecl: return "ObjCInstanceMethodDecl";
1426 case CXCursor_ObjCClassMethodDecl: return "ObjCClassMethodDecl";
Douglas Gregorb6998662010-01-19 19:34:47 +00001427 case CXCursor_ObjCImplementationDecl: return "ObjCImplementationDecl";
1428 case CXCursor_ObjCCategoryImplDecl: return "ObjCCategoryImplDecl";
Douglas Gregor30122132010-01-19 22:07:56 +00001429 case CXCursor_UnexposedDecl: return "UnexposedDecl";
Daniel Dunbaracca7252009-11-30 20:42:49 +00001430 case CXCursor_ObjCSuperClassRef: return "ObjCSuperClassRef";
1431 case CXCursor_ObjCProtocolRef: return "ObjCProtocolRef";
1432 case CXCursor_ObjCClassRef: return "ObjCClassRef";
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001433 case CXCursor_TypeRef: return "TypeRef";
Douglas Gregor97b98722010-01-19 23:20:36 +00001434 case CXCursor_UnexposedExpr: return "UnexposedExpr";
1435 case CXCursor_DeclRefExpr: return "DeclRefExpr";
1436 case CXCursor_MemberRefExpr: return "MemberRefExpr";
1437 case CXCursor_CallExpr: return "CallExpr";
1438 case CXCursor_ObjCMessageExpr: return "ObjCMessageExpr";
1439 case CXCursor_UnexposedStmt: return "UnexposedStmt";
Daniel Dunbaracca7252009-11-30 20:42:49 +00001440 case CXCursor_InvalidFile: return "InvalidFile";
1441 case CXCursor_NoDeclFound: return "NoDeclFound";
1442 case CXCursor_NotImplemented: return "NotImplemented";
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001443 case CXCursor_TranslationUnit: return "TranslationUnit";
Steve Naroff89922f82009-08-31 00:59:03 +00001444 }
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00001445
1446 llvm_unreachable("Unhandled CXCursorKind");
1447 return NULL;
Steve Naroff600866c2009-08-27 19:51:58 +00001448}
Steve Naroff89922f82009-08-31 00:59:03 +00001449
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001450enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
1451 CXCursor parent,
1452 CXClientData client_data) {
1453 CXCursor *BestCursor = static_cast<CXCursor *>(client_data);
1454 *BestCursor = cursor;
1455 return CXChildVisit_Recurse;
1456}
1457
Douglas Gregorb9790342010-01-22 21:44:22 +00001458CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
1459 if (!TU)
Ted Kremenekf4629892010-01-14 01:51:23 +00001460 return clang_getNullCursor();
Ted Kremenekf4629892010-01-14 01:51:23 +00001461
Douglas Gregorb9790342010-01-22 21:44:22 +00001462 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
1463
Ted Kremeneka297de22010-01-25 22:34:44 +00001464 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001465 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
1466 if (SLoc.isValid()) {
Daniel Dunbard52864b2010-02-14 10:02:57 +00001467 SourceRange RegionOfInterest(SLoc, SLoc.getFileLocWithOffset(1));
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001468
1469 // FIXME: Would be great to have a "hint" cursor, then walk from that
1470 // hint cursor upward until we find a cursor whose source range encloses
1471 // the region of interest, rather than starting from the translation unit.
1472 CXCursor Parent = clang_getTranslationUnitCursor(CXXUnit);
1473 CursorVisitor CursorVis(CXXUnit, GetCursorVisitor, &Result,
1474 Decl::MaxPCHLevel, RegionOfInterest);
1475 CursorVis.VisitChildren(Parent);
Steve Naroff77128dd2009-09-15 20:25:34 +00001476 }
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001477 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00001478}
1479
Ted Kremenek73885552009-11-17 19:28:59 +00001480CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00001481 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00001482}
1483
1484unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00001485 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00001486}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001487
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001488unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00001489 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
1490}
1491
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001492unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +00001493 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
1494}
Steve Naroff2d4d6292009-08-31 14:26:51 +00001495
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001496unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00001497 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
1498}
1499
Douglas Gregor97b98722010-01-19 23:20:36 +00001500unsigned clang_isExpression(enum CXCursorKind K) {
1501 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
1502}
1503
1504unsigned clang_isStatement(enum CXCursorKind K) {
1505 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
1506}
1507
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001508unsigned clang_isTranslationUnit(enum CXCursorKind K) {
1509 return K == CXCursor_TranslationUnit;
1510}
1511
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001512CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00001513 return C.kind;
1514}
1515
Douglas Gregor98258af2010-01-18 22:46:11 +00001516CXSourceLocation clang_getCursorLocation(CXCursor C) {
1517 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00001518 switch (C.kind) {
1519 case CXCursor_ObjCSuperClassRef: {
1520 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1521 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001522 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001523 }
1524
1525 case CXCursor_ObjCProtocolRef: {
1526 std::pair<ObjCProtocolDecl *, SourceLocation> P
1527 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001528 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001529 }
1530
1531 case CXCursor_ObjCClassRef: {
1532 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1533 = getCursorObjCClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001534 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001535 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001536
1537 case CXCursor_TypeRef: {
1538 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001539 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001540 }
Douglas Gregorf46034a2010-01-18 23:41:10 +00001541
Douglas Gregorf46034a2010-01-18 23:41:10 +00001542 default:
1543 // FIXME: Need a way to enumerate all non-reference cases.
1544 llvm_unreachable("Missed a reference kind");
1545 }
Douglas Gregor98258af2010-01-18 22:46:11 +00001546 }
Douglas Gregor97b98722010-01-19 23:20:36 +00001547
1548 if (clang_isExpression(C.kind))
Ted Kremeneka297de22010-01-25 22:34:44 +00001549 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00001550 getLocationFromExpr(getCursorExpr(C)));
1551
Douglas Gregor5352ac02010-01-28 00:27:43 +00001552 if (!getCursorDecl(C))
1553 return clang_getNullLocation();
Douglas Gregor98258af2010-01-18 22:46:11 +00001554
Douglas Gregorf46034a2010-01-18 23:41:10 +00001555 Decl *D = getCursorDecl(C);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001556 SourceLocation Loc = D->getLocation();
1557 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
1558 Loc = Class->getClassLoc();
Ted Kremeneka297de22010-01-25 22:34:44 +00001559 return cxloc::translateSourceLocation(D->getASTContext(), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00001560}
Douglas Gregora7bde202010-01-19 00:34:46 +00001561
1562CXSourceRange clang_getCursorExtent(CXCursor C) {
1563 if (clang_isReference(C.kind)) {
1564 switch (C.kind) {
1565 case CXCursor_ObjCSuperClassRef: {
1566 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1567 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001568 return cxloc::translateSourceRange(P.first->getASTContext(), P.second);
Douglas Gregora7bde202010-01-19 00:34:46 +00001569 }
1570
1571 case CXCursor_ObjCProtocolRef: {
1572 std::pair<ObjCProtocolDecl *, SourceLocation> P
1573 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001574 return cxloc::translateSourceRange(P.first->getASTContext(), P.second);
Douglas Gregora7bde202010-01-19 00:34:46 +00001575 }
1576
1577 case CXCursor_ObjCClassRef: {
1578 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1579 = getCursorObjCClassRef(C);
1580
Ted Kremeneka297de22010-01-25 22:34:44 +00001581 return cxloc::translateSourceRange(P.first->getASTContext(), P.second);
Douglas Gregora7bde202010-01-19 00:34:46 +00001582 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001583
1584 case CXCursor_TypeRef: {
1585 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001586 return cxloc::translateSourceRange(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001587 }
Douglas Gregora7bde202010-01-19 00:34:46 +00001588
Douglas Gregora7bde202010-01-19 00:34:46 +00001589 default:
1590 // FIXME: Need a way to enumerate all non-reference cases.
1591 llvm_unreachable("Missed a reference kind");
1592 }
1593 }
Douglas Gregor97b98722010-01-19 23:20:36 +00001594
1595 if (clang_isExpression(C.kind))
Ted Kremeneka297de22010-01-25 22:34:44 +00001596 return cxloc::translateSourceRange(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00001597 getCursorExpr(C)->getSourceRange());
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001598
1599 if (clang_isStatement(C.kind))
Ted Kremeneka297de22010-01-25 22:34:44 +00001600 return cxloc::translateSourceRange(getCursorContext(C),
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001601 getCursorStmt(C)->getSourceRange());
Douglas Gregora7bde202010-01-19 00:34:46 +00001602
Douglas Gregor5352ac02010-01-28 00:27:43 +00001603 if (!getCursorDecl(C))
1604 return clang_getNullRange();
Douglas Gregora7bde202010-01-19 00:34:46 +00001605
1606 Decl *D = getCursorDecl(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001607 return cxloc::translateSourceRange(D->getASTContext(), D->getSourceRange());
Douglas Gregora7bde202010-01-19 00:34:46 +00001608}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001609
1610CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001611 if (clang_isInvalid(C.kind))
1612 return clang_getNullCursor();
1613
1614 ASTUnit *CXXUnit = getCursorASTUnit(C);
Douglas Gregorb6998662010-01-19 19:34:47 +00001615 if (clang_isDeclaration(C.kind))
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001616 return C;
Douglas Gregor98258af2010-01-18 22:46:11 +00001617
Douglas Gregor97b98722010-01-19 23:20:36 +00001618 if (clang_isExpression(C.kind)) {
1619 Decl *D = getDeclFromExpr(getCursorExpr(C));
1620 if (D)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001621 return MakeCXCursor(D, CXXUnit);
Douglas Gregor97b98722010-01-19 23:20:36 +00001622 return clang_getNullCursor();
1623 }
1624
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001625 if (!clang_isReference(C.kind))
1626 return clang_getNullCursor();
1627
1628 switch (C.kind) {
1629 case CXCursor_ObjCSuperClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001630 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, CXXUnit);
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001631
1632 case CXCursor_ObjCProtocolRef: {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001633 return MakeCXCursor(getCursorObjCProtocolRef(C).first, CXXUnit);
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001634
1635 case CXCursor_ObjCClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001636 return MakeCXCursor(getCursorObjCClassRef(C).first, CXXUnit);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001637
1638 case CXCursor_TypeRef:
1639 return MakeCXCursor(getCursorTypeRef(C).first, CXXUnit);
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001640
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001641 default:
1642 // We would prefer to enumerate all non-reference cursor kinds here.
1643 llvm_unreachable("Unhandled reference cursor kind");
1644 break;
1645 }
1646 }
1647
1648 return clang_getNullCursor();
1649}
1650
Douglas Gregorb6998662010-01-19 19:34:47 +00001651CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001652 if (clang_isInvalid(C.kind))
1653 return clang_getNullCursor();
1654
1655 ASTUnit *CXXUnit = getCursorASTUnit(C);
1656
Douglas Gregorb6998662010-01-19 19:34:47 +00001657 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00001658 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00001659 C = clang_getCursorReferenced(C);
1660 WasReference = true;
1661 }
1662
1663 if (!clang_isDeclaration(C.kind))
1664 return clang_getNullCursor();
1665
1666 Decl *D = getCursorDecl(C);
1667 if (!D)
1668 return clang_getNullCursor();
1669
1670 switch (D->getKind()) {
1671 // Declaration kinds that don't really separate the notions of
1672 // declaration and definition.
1673 case Decl::Namespace:
1674 case Decl::Typedef:
1675 case Decl::TemplateTypeParm:
1676 case Decl::EnumConstant:
1677 case Decl::Field:
1678 case Decl::ObjCIvar:
1679 case Decl::ObjCAtDefsField:
1680 case Decl::ImplicitParam:
1681 case Decl::ParmVar:
1682 case Decl::NonTypeTemplateParm:
1683 case Decl::TemplateTemplateParm:
1684 case Decl::ObjCCategoryImpl:
1685 case Decl::ObjCImplementation:
1686 case Decl::LinkageSpec:
1687 case Decl::ObjCPropertyImpl:
1688 case Decl::FileScopeAsm:
1689 case Decl::StaticAssert:
1690 case Decl::Block:
1691 return C;
1692
1693 // Declaration kinds that don't make any sense here, but are
1694 // nonetheless harmless.
1695 case Decl::TranslationUnit:
1696 case Decl::Template:
1697 case Decl::ObjCContainer:
1698 break;
1699
1700 // Declaration kinds for which the definition is not resolvable.
1701 case Decl::UnresolvedUsingTypename:
1702 case Decl::UnresolvedUsingValue:
1703 break;
1704
1705 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001706 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
1707 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001708
1709 case Decl::NamespaceAlias:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001710 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001711
1712 case Decl::Enum:
1713 case Decl::Record:
1714 case Decl::CXXRecord:
1715 case Decl::ClassTemplateSpecialization:
1716 case Decl::ClassTemplatePartialSpecialization:
Douglas Gregor952b0172010-02-11 01:04:33 +00001717 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001718 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001719 return clang_getNullCursor();
1720
1721 case Decl::Function:
1722 case Decl::CXXMethod:
1723 case Decl::CXXConstructor:
1724 case Decl::CXXDestructor:
1725 case Decl::CXXConversion: {
1726 const FunctionDecl *Def = 0;
1727 if (cast<FunctionDecl>(D)->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001728 return MakeCXCursor(const_cast<FunctionDecl *>(Def), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001729 return clang_getNullCursor();
1730 }
1731
1732 case Decl::Var: {
Sebastian Redl31310a22010-02-01 20:16:42 +00001733 // Ask the variable if it has a definition.
1734 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
1735 return MakeCXCursor(Def, CXXUnit);
1736 return clang_getNullCursor();
Douglas Gregorb6998662010-01-19 19:34:47 +00001737 }
1738
1739 case Decl::FunctionTemplate: {
1740 const FunctionDecl *Def = 0;
1741 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001742 return MakeCXCursor(Def->getDescribedFunctionTemplate(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001743 return clang_getNullCursor();
1744 }
1745
1746 case Decl::ClassTemplate: {
1747 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
Douglas Gregor952b0172010-02-11 01:04:33 +00001748 ->getDefinition())
Douglas Gregorb6998662010-01-19 19:34:47 +00001749 return MakeCXCursor(
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001750 cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
1751 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001752 return clang_getNullCursor();
1753 }
1754
1755 case Decl::Using: {
1756 UsingDecl *Using = cast<UsingDecl>(D);
1757 CXCursor Def = clang_getNullCursor();
1758 for (UsingDecl::shadow_iterator S = Using->shadow_begin(),
1759 SEnd = Using->shadow_end();
1760 S != SEnd; ++S) {
1761 if (Def != clang_getNullCursor()) {
1762 // FIXME: We have no way to return multiple results.
1763 return clang_getNullCursor();
1764 }
1765
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001766 Def = clang_getCursorDefinition(MakeCXCursor((*S)->getTargetDecl(),
1767 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00001768 }
1769
1770 return Def;
1771 }
1772
1773 case Decl::UsingShadow:
1774 return clang_getCursorDefinition(
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001775 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
1776 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00001777
1778 case Decl::ObjCMethod: {
1779 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
1780 if (Method->isThisDeclarationADefinition())
1781 return C;
1782
1783 // Dig out the method definition in the associated
1784 // @implementation, if we have it.
1785 // FIXME: The ASTs should make finding the definition easier.
1786 if (ObjCInterfaceDecl *Class
1787 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
1788 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
1789 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
1790 Method->isInstanceMethod()))
1791 if (Def->isThisDeclarationADefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001792 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001793
1794 return clang_getNullCursor();
1795 }
1796
1797 case Decl::ObjCCategory:
1798 if (ObjCCategoryImplDecl *Impl
1799 = cast<ObjCCategoryDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001800 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001801 return clang_getNullCursor();
1802
1803 case Decl::ObjCProtocol:
1804 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
1805 return C;
1806 return clang_getNullCursor();
1807
1808 case Decl::ObjCInterface:
1809 // There are two notions of a "definition" for an Objective-C
1810 // class: the interface and its implementation. When we resolved a
1811 // reference to an Objective-C class, produce the @interface as
1812 // the definition; when we were provided with the interface,
1813 // produce the @implementation as the definition.
1814 if (WasReference) {
1815 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
1816 return C;
1817 } else if (ObjCImplementationDecl *Impl
1818 = cast<ObjCInterfaceDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001819 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001820 return clang_getNullCursor();
1821
1822 case Decl::ObjCProperty:
1823 // FIXME: We don't really know where to find the
1824 // ObjCPropertyImplDecls that implement this property.
1825 return clang_getNullCursor();
1826
1827 case Decl::ObjCCompatibleAlias:
1828 if (ObjCInterfaceDecl *Class
1829 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
1830 if (!Class->isForwardDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001831 return MakeCXCursor(Class, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001832
1833 return clang_getNullCursor();
1834
1835 case Decl::ObjCForwardProtocol: {
1836 ObjCForwardProtocolDecl *Forward = cast<ObjCForwardProtocolDecl>(D);
1837 if (Forward->protocol_size() == 1)
1838 return clang_getCursorDefinition(
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001839 MakeCXCursor(*Forward->protocol_begin(),
1840 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00001841
1842 // FIXME: Cannot return multiple definitions.
1843 return clang_getNullCursor();
1844 }
1845
1846 case Decl::ObjCClass: {
1847 ObjCClassDecl *Class = cast<ObjCClassDecl>(D);
1848 if (Class->size() == 1) {
1849 ObjCInterfaceDecl *IFace = Class->begin()->getInterface();
1850 if (!IFace->isForwardDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001851 return MakeCXCursor(IFace, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001852 return clang_getNullCursor();
1853 }
1854
1855 // FIXME: Cannot return multiple definitions.
1856 return clang_getNullCursor();
1857 }
1858
1859 case Decl::Friend:
1860 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001861 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00001862 return clang_getNullCursor();
1863
1864 case Decl::FriendTemplate:
1865 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001866 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00001867 return clang_getNullCursor();
1868 }
1869
1870 return clang_getNullCursor();
1871}
1872
1873unsigned clang_isCursorDefinition(CXCursor C) {
1874 if (!clang_isDeclaration(C.kind))
1875 return 0;
1876
1877 return clang_getCursorDefinition(C) == C;
1878}
1879
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001880void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00001881 const char **startBuf,
1882 const char **endBuf,
1883 unsigned *startLine,
1884 unsigned *startColumn,
1885 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001886 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00001887 assert(getCursorDecl(C) && "CXCursor has null decl");
1888 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00001889 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
1890 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekfb480492010-01-13 21:46:36 +00001891
Steve Naroff4ade6d62009-09-23 17:52:52 +00001892 SourceManager &SM = FD->getASTContext().getSourceManager();
1893 *startBuf = SM.getCharacterData(Body->getLBracLoc());
1894 *endBuf = SM.getCharacterData(Body->getRBracLoc());
1895 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
1896 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
1897 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
1898 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
1899}
Ted Kremenekfb480492010-01-13 21:46:36 +00001900
1901} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00001902
Ted Kremenekfb480492010-01-13 21:46:36 +00001903//===----------------------------------------------------------------------===//
Douglas Gregorfc8ea232010-01-26 17:06:03 +00001904// Token-based Operations.
1905//===----------------------------------------------------------------------===//
1906
1907/* CXToken layout:
1908 * int_data[0]: a CXTokenKind
1909 * int_data[1]: starting token location
1910 * int_data[2]: token length
1911 * int_data[3]: reserved
1912 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
1913 * otherwise unused.
1914 */
1915extern "C" {
1916
1917CXTokenKind clang_getTokenKind(CXToken CXTok) {
1918 return static_cast<CXTokenKind>(CXTok.int_data[0]);
1919}
1920
1921CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
1922 switch (clang_getTokenKind(CXTok)) {
1923 case CXToken_Identifier:
1924 case CXToken_Keyword:
1925 // We know we have an IdentifierInfo*, so use that.
1926 return CIndexer::createCXString(
1927 static_cast<IdentifierInfo *>(CXTok.ptr_data)->getNameStart());
1928
1929 case CXToken_Literal: {
1930 // We have stashed the starting pointer in the ptr_data field. Use it.
1931 const char *Text = static_cast<const char *>(CXTok.ptr_data);
1932 return CIndexer::createCXString(llvm::StringRef(Text, CXTok.int_data[2]),
1933 true);
1934 }
1935
1936 case CXToken_Punctuation:
1937 case CXToken_Comment:
1938 break;
1939 }
1940
1941 // We have to find the starting buffer pointer the hard way, by
1942 // deconstructing the source location.
1943 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
1944 if (!CXXUnit)
1945 return CIndexer::createCXString("");
1946
1947 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
1948 std::pair<FileID, unsigned> LocInfo
1949 = CXXUnit->getSourceManager().getDecomposedLoc(Loc);
1950 std::pair<const char *,const char *> Buffer
1951 = CXXUnit->getSourceManager().getBufferData(LocInfo.first);
1952
1953 return CIndexer::createCXString(llvm::StringRef(Buffer.first+LocInfo.second,
1954 CXTok.int_data[2]),
1955 true);
1956}
1957
1958CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
1959 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
1960 if (!CXXUnit)
1961 return clang_getNullLocation();
1962
1963 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
1964 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
1965}
1966
1967CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
1968 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregor5352ac02010-01-28 00:27:43 +00001969 if (!CXXUnit)
1970 return clang_getNullRange();
Douglas Gregorfc8ea232010-01-26 17:06:03 +00001971
1972 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
1973 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
1974}
1975
1976void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
1977 CXToken **Tokens, unsigned *NumTokens) {
1978 if (Tokens)
1979 *Tokens = 0;
1980 if (NumTokens)
1981 *NumTokens = 0;
1982
1983 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
1984 if (!CXXUnit || !Tokens || !NumTokens)
1985 return;
1986
Daniel Dunbar85b988f2010-02-14 08:31:57 +00001987 SourceRange R = cxloc::translateCXSourceRange(Range);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00001988 if (R.isInvalid())
1989 return;
1990
1991 SourceManager &SourceMgr = CXXUnit->getSourceManager();
1992 std::pair<FileID, unsigned> BeginLocInfo
1993 = SourceMgr.getDecomposedLoc(R.getBegin());
1994 std::pair<FileID, unsigned> EndLocInfo
1995 = SourceMgr.getDecomposedLoc(R.getEnd());
1996
1997 // Cannot tokenize across files.
1998 if (BeginLocInfo.first != EndLocInfo.first)
1999 return;
2000
2001 // Create a lexer
2002 std::pair<const char *,const char *> Buffer
2003 = SourceMgr.getBufferData(BeginLocInfo.first);
2004 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
2005 CXXUnit->getASTContext().getLangOptions(),
2006 Buffer.first, Buffer.first + BeginLocInfo.second, Buffer.second);
2007 Lex.SetCommentRetentionState(true);
2008
2009 // Lex tokens until we hit the end of the range.
2010 const char *EffectiveBufferEnd = Buffer.first + EndLocInfo.second;
2011 llvm::SmallVector<CXToken, 32> CXTokens;
2012 Token Tok;
2013 do {
2014 // Lex the next token
2015 Lex.LexFromRawLexer(Tok);
2016 if (Tok.is(tok::eof))
2017 break;
2018
2019 // Initialize the CXToken.
2020 CXToken CXTok;
2021
2022 // - Common fields
2023 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
2024 CXTok.int_data[2] = Tok.getLength();
2025 CXTok.int_data[3] = 0;
2026
2027 // - Kind-specific fields
2028 if (Tok.isLiteral()) {
2029 CXTok.int_data[0] = CXToken_Literal;
2030 CXTok.ptr_data = (void *)Tok.getLiteralData();
2031 } else if (Tok.is(tok::identifier)) {
2032 // Lookup the identifier to determine whether we have a
2033 std::pair<FileID, unsigned> LocInfo
2034 = SourceMgr.getDecomposedLoc(Tok.getLocation());
2035 const char *StartPos
2036 = CXXUnit->getSourceManager().getBufferData(LocInfo.first).first +
2037 LocInfo.second;
2038 IdentifierInfo *II
2039 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok, StartPos);
2040 CXTok.int_data[0] = II->getTokenID() == tok::identifier?
2041 CXToken_Identifier
2042 : CXToken_Keyword;
2043 CXTok.ptr_data = II;
2044 } else if (Tok.is(tok::comment)) {
2045 CXTok.int_data[0] = CXToken_Comment;
2046 CXTok.ptr_data = 0;
2047 } else {
2048 CXTok.int_data[0] = CXToken_Punctuation;
2049 CXTok.ptr_data = 0;
2050 }
2051 CXTokens.push_back(CXTok);
2052 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
2053
2054 if (CXTokens.empty())
2055 return;
2056
2057 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
2058 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
2059 *NumTokens = CXTokens.size();
2060}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002061
2062typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
2063
2064enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
2065 CXCursor parent,
2066 CXClientData client_data) {
2067 AnnotateTokensData *Data = static_cast<AnnotateTokensData *>(client_data);
2068
2069 // We only annotate the locations of declarations, simple
2070 // references, and expressions which directly reference something.
2071 CXCursorKind Kind = clang_getCursorKind(cursor);
2072 if (clang_isDeclaration(Kind) || clang_isReference(Kind)) {
2073 // Okay: We can annotate the location of this declaration with the
2074 // declaration or reference
2075 } else if (clang_isExpression(cursor.kind)) {
2076 if (Kind != CXCursor_DeclRefExpr &&
2077 Kind != CXCursor_MemberRefExpr &&
2078 Kind != CXCursor_ObjCMessageExpr)
2079 return CXChildVisit_Recurse;
2080
2081 CXCursor Referenced = clang_getCursorReferenced(cursor);
2082 if (Referenced == cursor || Referenced == clang_getNullCursor())
2083 return CXChildVisit_Recurse;
2084
2085 // Okay: we can annotate the location of this expression
2086 } else {
2087 // Nothing to annotate
2088 return CXChildVisit_Recurse;
2089 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002090
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002091 CXSourceLocation Loc = clang_getCursorLocation(cursor);
2092 (*Data)[Loc.int_data] = cursor;
2093 return CXChildVisit_Recurse;
2094}
2095
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002096void clang_annotateTokens(CXTranslationUnit TU,
2097 CXToken *Tokens, unsigned NumTokens,
2098 CXCursor *Cursors) {
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002099 if (NumTokens == 0)
2100 return;
2101
2102 // Any token we don't specifically annotate will have a NULL cursor.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002103 for (unsigned I = 0; I != NumTokens; ++I)
2104 Cursors[I] = clang_getNullCursor();
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002105
2106 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2107 if (!CXXUnit || !Tokens)
2108 return;
2109
2110 // Annotate all of the source locations in the region of interest that map
2111 SourceRange RegionOfInterest;
2112 RegionOfInterest.setBegin(
2113 cxloc::translateSourceLocation(clang_getTokenLocation(TU, Tokens[0])));
2114 SourceLocation End
2115 = cxloc::translateSourceLocation(clang_getTokenLocation(TU,
2116 Tokens[NumTokens - 1]));
Daniel Dunbard52864b2010-02-14 10:02:57 +00002117 RegionOfInterest.setEnd(CXXUnit->getPreprocessor().getLocForEndOfToken(End));
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002118 // FIXME: Would be great to have a "hint" cursor, then walk from that
2119 // hint cursor upward until we find a cursor whose source range encloses
2120 // the region of interest, rather than starting from the translation unit.
2121 AnnotateTokensData Annotated;
2122 CXCursor Parent = clang_getTranslationUnitCursor(CXXUnit);
2123 CursorVisitor AnnotateVis(CXXUnit, AnnotateTokensVisitor, &Annotated,
2124 Decl::MaxPCHLevel, RegionOfInterest);
2125 AnnotateVis.VisitChildren(Parent);
2126
2127 for (unsigned I = 0; I != NumTokens; ++I) {
2128 // Determine whether we saw a cursor at this token's location.
2129 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
2130 if (Pos == Annotated.end())
2131 continue;
2132
2133 Cursors[I] = Pos->second;
2134 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002135}
2136
2137void clang_disposeTokens(CXTranslationUnit TU,
2138 CXToken *Tokens, unsigned NumTokens) {
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002139 free(Tokens);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002140}
2141
2142} // end: extern "C"
2143
2144//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00002145// CXString Operations.
2146//===----------------------------------------------------------------------===//
2147
2148extern "C" {
2149const char *clang_getCString(CXString string) {
2150 return string.Spelling;
2151}
2152
2153void clang_disposeString(CXString string) {
2154 if (string.MustFreeString && string.Spelling)
2155 free((void*)string.Spelling);
2156}
Ted Kremenek04bb7162010-01-22 22:44:15 +00002157
Ted Kremenekfb480492010-01-13 21:46:36 +00002158} // end: extern "C"
Ted Kremenek04bb7162010-01-22 22:44:15 +00002159
2160//===----------------------------------------------------------------------===//
2161// Misc. utility functions.
2162//===----------------------------------------------------------------------===//
2163
2164extern "C" {
2165
Ted Kremeneka2a9d6e2010-02-12 22:54:40 +00002166CXString clang_getClangVersion() {
2167 return CIndexer::createCXString(getClangFullVersion(), true);
Ted Kremenek04bb7162010-01-22 22:44:15 +00002168}
2169
2170} // end: extern "C"
2171