blob: f9995eb743dfb6413b1ba3dd0871a2f59e04b751 [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 Dunbarb26d4832010-02-16 01:55:04 +0000964 CXXIdx->getOnlyLocalDecls());
Steve Naroff600866c2009-08-27 19:51:58 +0000965}
966
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000967CXTranslationUnit
968clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
969 const char *source_filename,
970 int num_command_line_args,
Douglas Gregor4db64a42010-01-23 00:14:00 +0000971 const char **command_line_args,
972 unsigned num_unsaved_files,
Douglas Gregor5352ac02010-01-28 00:27:43 +0000973 struct CXUnsavedFile *unsaved_files,
974 CXDiagnosticCallback diag_callback,
975 CXClientData diag_client_data) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +0000976 if (!CIdx)
977 return 0;
978
Steve Naroffe56b4ba2009-10-20 14:46:24 +0000979 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
980
Douglas Gregor5352ac02010-01-28 00:27:43 +0000981 // Configure the diagnostics.
982 DiagnosticOptions DiagOpts;
983 llvm::OwningPtr<Diagnostic> Diags;
984 Diags.reset(CompilerInstance::createDiagnostics(DiagOpts, 0, 0));
985 CIndexDiagnosticClient DiagClient(diag_callback, diag_client_data);
986 Diags->setClient(&DiagClient);
987
Douglas Gregor4db64a42010-01-23 00:14:00 +0000988 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
989 for (unsigned I = 0; I != num_unsaved_files; ++I) {
990 const llvm::MemoryBuffer *Buffer
991 = llvm::MemoryBuffer::getMemBuffer(unsaved_files[I].Contents,
992 unsaved_files[I].Contents + unsaved_files[I].Length,
993 unsaved_files[I].Filename);
994 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
995 Buffer));
996 }
997
Daniel Dunbar8506dde2009-12-03 01:54:28 +0000998 if (!CXXIdx->getUseExternalASTGeneration()) {
999 llvm::SmallVector<const char *, 16> Args;
1000
1001 // The 'source_filename' argument is optional. If the caller does not
1002 // specify it then it is assumed that the source file is specified
1003 // in the actual argument list.
1004 if (source_filename)
1005 Args.push_back(source_filename);
1006 Args.insert(Args.end(), command_line_args,
1007 command_line_args + num_command_line_args);
1008
Douglas Gregor5352ac02010-01-28 00:27:43 +00001009 unsigned NumErrors = Diags->getNumErrors();
Ted Kremenek8a8da7d2010-01-06 03:42:32 +00001010
Ted Kremenek29b72842010-01-07 22:49:05 +00001011#ifdef USE_CRASHTRACER
1012 ArgsCrashTracerInfo ACTI(Args);
Ted Kremenek8a8da7d2010-01-06 03:42:32 +00001013#endif
1014
Daniel Dunbar94220972009-12-05 02:17:18 +00001015 llvm::OwningPtr<ASTUnit> Unit(
1016 ASTUnit::LoadFromCommandLine(Args.data(), Args.data() + Args.size(),
Douglas Gregor5352ac02010-01-28 00:27:43 +00001017 *Diags,
Daniel Dunbar869824e2009-12-13 03:46:13 +00001018 CXXIdx->getClangResourcesPath(),
Daniel Dunbar94220972009-12-05 02:17:18 +00001019 CXXIdx->getOnlyLocalDecls(),
Douglas Gregor4db64a42010-01-23 00:14:00 +00001020 RemappedFiles.data(),
1021 RemappedFiles.size()));
Ted Kremenek29b72842010-01-07 22:49:05 +00001022
Daniel Dunbar94220972009-12-05 02:17:18 +00001023 // FIXME: Until we have broader testing, just drop the entire AST if we
1024 // encountered an error.
Douglas Gregor5352ac02010-01-28 00:27:43 +00001025 if (NumErrors != Diags->getNumErrors())
Daniel Dunbar94220972009-12-05 02:17:18 +00001026 return 0;
1027
1028 return Unit.take();
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001029 }
1030
Ted Kremenek139ba862009-10-22 00:03:57 +00001031 // Build up the arguments for invoking 'clang'.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001032 std::vector<const char *> argv;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001033
Ted Kremenek139ba862009-10-22 00:03:57 +00001034 // First add the complete path to the 'clang' executable.
1035 llvm::sys::Path ClangPath = static_cast<CIndexer *>(CIdx)->getClangPath();
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00001036 argv.push_back(ClangPath.c_str());
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001037
Ted Kremenek139ba862009-10-22 00:03:57 +00001038 // Add the '-emit-ast' option as our execution mode for 'clang'.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001039 argv.push_back("-emit-ast");
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001040
Ted Kremenek139ba862009-10-22 00:03:57 +00001041 // The 'source_filename' argument is optional. If the caller does not
1042 // specify it then it is assumed that the source file is specified
1043 // in the actual argument list.
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001044 if (source_filename)
1045 argv.push_back(source_filename);
Ted Kremenek139ba862009-10-22 00:03:57 +00001046
Steve Naroff37b5ac22009-10-15 20:50:09 +00001047 // Generate a temporary name for the AST file.
Ted Kremenek139ba862009-10-22 00:03:57 +00001048 argv.push_back("-o");
Steve Naroff37b5ac22009-10-15 20:50:09 +00001049 char astTmpFile[L_tmpnam];
Ted Kremenek74cd0692009-10-15 23:21:22 +00001050 argv.push_back(tmpnam(astTmpFile));
Ted Kremenek139ba862009-10-22 00:03:57 +00001051
Douglas Gregor4db64a42010-01-23 00:14:00 +00001052 // Remap any unsaved files to temporary files.
1053 std::vector<llvm::sys::Path> TemporaryFiles;
1054 std::vector<std::string> RemapArgs;
1055 if (RemapFiles(num_unsaved_files, unsaved_files, RemapArgs, TemporaryFiles))
1056 return 0;
1057
1058 // The pointers into the elements of RemapArgs are stable because we
1059 // won't be adding anything to RemapArgs after this point.
1060 for (unsigned i = 0, e = RemapArgs.size(); i != e; ++i)
1061 argv.push_back(RemapArgs[i].c_str());
1062
Ted Kremenek139ba862009-10-22 00:03:57 +00001063 // Process the compiler options, stripping off '-o', '-c', '-fsyntax-only'.
1064 for (int i = 0; i < num_command_line_args; ++i)
1065 if (const char *arg = command_line_args[i]) {
1066 if (strcmp(arg, "-o") == 0) {
1067 ++i; // Also skip the matching argument.
1068 continue;
1069 }
1070 if (strcmp(arg, "-emit-ast") == 0 ||
1071 strcmp(arg, "-c") == 0 ||
1072 strcmp(arg, "-fsyntax-only") == 0) {
1073 continue;
1074 }
1075
1076 // Keep the argument.
1077 argv.push_back(arg);
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001078 }
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001079
Douglas Gregord93256e2010-01-28 06:00:51 +00001080 // Generate a temporary name for the diagnostics file.
1081 char tmpFileResults[L_tmpnam];
1082 char *tmpResultsFileName = tmpnam(tmpFileResults);
1083 llvm::sys::Path DiagnosticsFile(tmpResultsFileName);
1084 TemporaryFiles.push_back(DiagnosticsFile);
1085 argv.push_back("-fdiagnostics-binary");
1086
Ted Kremenek139ba862009-10-22 00:03:57 +00001087 // Add the null terminator.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001088 argv.push_back(NULL);
1089
Ted Kremenekfeb15e32009-10-26 22:14:08 +00001090 // Invoke 'clang'.
1091 llvm::sys::Path DevNull; // leave empty, causes redirection to /dev/null
1092 // on Unix or NUL (Windows).
Ted Kremenek379afec2009-10-22 03:24:01 +00001093 std::string ErrMsg;
Douglas Gregord93256e2010-01-28 06:00:51 +00001094 const llvm::sys::Path *Redirects[] = { &DevNull, &DevNull, &DiagnosticsFile,
1095 NULL };
Ted Kremenek379afec2009-10-22 03:24:01 +00001096 llvm::sys::Program::ExecuteAndWait(ClangPath, &argv[0], /* env */ NULL,
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001097 /* redirects */ &Redirects[0],
Ted Kremenek379afec2009-10-22 03:24:01 +00001098 /* secondsToWait */ 0, /* memoryLimits */ 0, &ErrMsg);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001099
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001100 if (!ErrMsg.empty()) {
1101 std::string AllArgs;
Ted Kremenek379afec2009-10-22 03:24:01 +00001102 for (std::vector<const char*>::iterator I = argv.begin(), E = argv.end();
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001103 I != E; ++I) {
1104 AllArgs += ' ';
Ted Kremenek779e5f42009-10-26 22:08:39 +00001105 if (*I)
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001106 AllArgs += *I;
Ted Kremenek779e5f42009-10-26 22:08:39 +00001107 }
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001108
1109 Diags->Report(diag::err_fe_clang) << AllArgs << ErrMsg;
Ted Kremenek379afec2009-10-22 03:24:01 +00001110 }
Benjamin Kramer0829a832009-10-18 11:19:36 +00001111
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001112 // FIXME: Parse the (redirected) standard error to emit diagnostics.
1113
Douglas Gregor5352ac02010-01-28 00:27:43 +00001114 ASTUnit *ATU = ASTUnit::LoadFromPCHFile(astTmpFile, *Diags,
Douglas Gregor4db64a42010-01-23 00:14:00 +00001115 CXXIdx->getOnlyLocalDecls(),
Douglas Gregor4db64a42010-01-23 00:14:00 +00001116 RemappedFiles.data(),
1117 RemappedFiles.size());
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001118 if (ATU)
1119 ATU->unlinkTemporaryFile();
Douglas Gregor4db64a42010-01-23 00:14:00 +00001120
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00001121 // FIXME: Currently we don't report diagnostics on invalid ASTs.
1122 if (ATU)
1123 ReportSerializedDiagnostics(DiagnosticsFile, *Diags,
1124 num_unsaved_files, unsaved_files,
1125 ATU->getASTContext().getLangOptions());
Douglas Gregord93256e2010-01-28 06:00:51 +00001126
Douglas Gregor4db64a42010-01-23 00:14:00 +00001127 for (unsigned i = 0, e = TemporaryFiles.size(); i != e; ++i)
1128 TemporaryFiles[i].eraseFromDisk();
1129
Steve Naroffe19944c2009-10-15 22:23:48 +00001130 return ATU;
Steve Naroff5b7d8e22009-10-15 20:04:39 +00001131}
1132
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001133void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001134 if (CTUnit)
1135 delete static_cast<ASTUnit *>(CTUnit);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00001136}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001137
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001138CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001139 if (!CTUnit)
1140 return CIndexer::createCXString("");
1141
Steve Naroff77accc12009-09-03 18:19:54 +00001142 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit);
Ted Kremenek4b333d22010-01-12 00:36:38 +00001143 return CIndexer::createCXString(CXXUnit->getOriginalSourceFileName().c_str(),
1144 true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +00001145}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +00001146
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001147CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001148 CXCursor Result = { CXCursor_TranslationUnit, { 0, 0, TU } };
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001149 return Result;
1150}
1151
Ted Kremenekfb480492010-01-13 21:46:36 +00001152} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +00001153
Ted Kremenekfb480492010-01-13 21:46:36 +00001154//===----------------------------------------------------------------------===//
Douglas Gregor1db19de2010-01-19 21:36:55 +00001155// CXSourceLocation and CXSourceRange Operations.
1156//===----------------------------------------------------------------------===//
1157
Douglas Gregorb9790342010-01-22 21:44:22 +00001158extern "C" {
1159CXSourceLocation clang_getNullLocation() {
Douglas Gregor5352ac02010-01-28 00:27:43 +00001160 CXSourceLocation Result = { { 0, 0 }, 0 };
Douglas Gregorb9790342010-01-22 21:44:22 +00001161 return Result;
1162}
1163
1164unsigned clang_equalLocations(CXSourceLocation loc1, CXSourceLocation loc2) {
Daniel Dunbar90a6b9e2010-01-30 23:58:27 +00001165 return (loc1.ptr_data[0] == loc2.ptr_data[0] &&
1166 loc1.ptr_data[1] == loc2.ptr_data[1] &&
1167 loc1.int_data == loc2.int_data);
Douglas Gregorb9790342010-01-22 21:44:22 +00001168}
1169
1170CXSourceLocation clang_getLocation(CXTranslationUnit tu,
1171 CXFile file,
1172 unsigned line,
1173 unsigned column) {
1174 if (!tu)
1175 return clang_getNullLocation();
1176
1177 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
1178 SourceLocation SLoc
1179 = CXXUnit->getSourceManager().getLocation(
1180 static_cast<const FileEntry *>(file),
1181 line, column);
1182
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00001183 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
Douglas Gregorb9790342010-01-22 21:44:22 +00001184}
1185
Douglas Gregor5352ac02010-01-28 00:27:43 +00001186CXSourceRange clang_getNullRange() {
1187 CXSourceRange Result = { { 0, 0 }, 0, 0 };
1188 return Result;
1189}
Daniel Dunbard52864b2010-02-14 10:02:57 +00001190
Douglas Gregor5352ac02010-01-28 00:27:43 +00001191CXSourceRange clang_getRange(CXSourceLocation begin, CXSourceLocation end) {
1192 if (begin.ptr_data[0] != end.ptr_data[0] ||
1193 begin.ptr_data[1] != end.ptr_data[1])
1194 return clang_getNullRange();
1195
1196 CXSourceRange Result = { { begin.ptr_data[0], begin.ptr_data[1] },
1197 begin.int_data, end.int_data };
Douglas Gregorb9790342010-01-22 21:44:22 +00001198 return Result;
1199}
1200
Douglas Gregor46766dc2010-01-26 19:19:08 +00001201void clang_getInstantiationLocation(CXSourceLocation location,
1202 CXFile *file,
1203 unsigned *line,
1204 unsigned *column,
1205 unsigned *offset) {
Douglas Gregor1db19de2010-01-19 21:36:55 +00001206 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
1207
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00001208 if (!location.ptr_data[0] || Loc.isInvalid()) {
Douglas Gregor46766dc2010-01-26 19:19:08 +00001209 if (file)
1210 *file = 0;
1211 if (line)
1212 *line = 0;
1213 if (column)
1214 *column = 0;
1215 if (offset)
1216 *offset = 0;
1217 return;
1218 }
1219
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00001220 const SourceManager &SM =
1221 *static_cast<const SourceManager*>(location.ptr_data[0]);
Douglas Gregor1db19de2010-01-19 21:36:55 +00001222 SourceLocation InstLoc = SM.getInstantiationLoc(Loc);
Douglas Gregor1db19de2010-01-19 21:36:55 +00001223
1224 if (file)
1225 *file = (void *)SM.getFileEntryForID(SM.getFileID(InstLoc));
1226 if (line)
1227 *line = SM.getInstantiationLineNumber(InstLoc);
1228 if (column)
1229 *column = SM.getInstantiationColumnNumber(InstLoc);
Douglas Gregore69517c2010-01-26 03:07:15 +00001230 if (offset)
Douglas Gregor46766dc2010-01-26 19:19:08 +00001231 *offset = SM.getDecomposedLoc(InstLoc).second;
Douglas Gregore69517c2010-01-26 03:07:15 +00001232}
1233
Douglas Gregor1db19de2010-01-19 21:36:55 +00001234CXSourceLocation clang_getRangeStart(CXSourceRange range) {
Douglas Gregor5352ac02010-01-28 00:27:43 +00001235 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
1236 range.begin_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00001237 return Result;
1238}
1239
1240CXSourceLocation clang_getRangeEnd(CXSourceRange range) {
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00001241 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00001242 range.end_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00001243 return Result;
1244}
1245
Douglas Gregorb9790342010-01-22 21:44:22 +00001246} // end: extern "C"
1247
Douglas Gregor1db19de2010-01-19 21:36:55 +00001248//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00001249// CXFile Operations.
1250//===----------------------------------------------------------------------===//
1251
1252extern "C" {
Steve Naroff88145032009-10-27 14:35:18 +00001253const char *clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00001254 if (!SFile)
1255 return 0;
1256
Steve Naroff88145032009-10-27 14:35:18 +00001257 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
1258 return FEnt->getName();
1259}
1260
1261time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00001262 if (!SFile)
1263 return 0;
1264
Steve Naroff88145032009-10-27 14:35:18 +00001265 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
1266 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +00001267}
Douglas Gregorb9790342010-01-22 21:44:22 +00001268
1269CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
1270 if (!tu)
1271 return 0;
1272
1273 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
1274
1275 FileManager &FMgr = CXXUnit->getFileManager();
1276 const FileEntry *File = FMgr.getFile(file_name, file_name+strlen(file_name));
1277 return const_cast<FileEntry *>(File);
1278}
1279
Ted Kremenekfb480492010-01-13 21:46:36 +00001280} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +00001281
Ted Kremenekfb480492010-01-13 21:46:36 +00001282//===----------------------------------------------------------------------===//
1283// CXCursor Operations.
1284//===----------------------------------------------------------------------===//
1285
Ted Kremenekfb480492010-01-13 21:46:36 +00001286static Decl *getDeclFromExpr(Stmt *E) {
1287 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
1288 return RefExpr->getDecl();
1289 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
1290 return ME->getMemberDecl();
1291 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
1292 return RE->getDecl();
1293
1294 if (CallExpr *CE = dyn_cast<CallExpr>(E))
1295 return getDeclFromExpr(CE->getCallee());
1296 if (CastExpr *CE = dyn_cast<CastExpr>(E))
1297 return getDeclFromExpr(CE->getSubExpr());
1298 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
1299 return OME->getMethodDecl();
1300
1301 return 0;
1302}
1303
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00001304static SourceLocation getLocationFromExpr(Expr *E) {
1305 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
1306 return /*FIXME:*/Msg->getLeftLoc();
1307 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
1308 return DRE->getLocation();
1309 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
1310 return Member->getMemberLoc();
1311 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
1312 return Ivar->getLocation();
1313 return E->getLocStart();
1314}
1315
Ted Kremenekfb480492010-01-13 21:46:36 +00001316extern "C" {
Douglas Gregorb1373d02010-01-20 20:59:29 +00001317
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001318unsigned clang_visitChildren(CXCursor parent,
Douglas Gregorb1373d02010-01-20 20:59:29 +00001319 CXCursorVisitor visitor,
1320 CXClientData client_data) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001321 ASTUnit *CXXUnit = getCursorASTUnit(parent);
Douglas Gregorb1373d02010-01-20 20:59:29 +00001322
1323 unsigned PCHLevel = Decl::MaxPCHLevel;
1324
1325 // Set the PCHLevel to filter out unwanted decls if requested.
1326 if (CXXUnit->getOnlyLocalDecls()) {
1327 PCHLevel = 0;
1328
1329 // If the main input was an AST, bump the level.
1330 if (CXXUnit->isMainFileAST())
1331 ++PCHLevel;
1332 }
1333
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001334 CursorVisitor CursorVis(CXXUnit, visitor, client_data, PCHLevel);
Douglas Gregorb1373d02010-01-20 20:59:29 +00001335 return CursorVis.VisitChildren(parent);
1336}
1337
Douglas Gregor78205d42010-01-20 21:45:58 +00001338static CXString getDeclSpelling(Decl *D) {
1339 NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
1340 if (!ND)
1341 return CIndexer::createCXString("");
1342
1343 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
1344 return CIndexer::createCXString(OMD->getSelector().getAsString().c_str(),
1345 true);
1346
1347 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
1348 // No, this isn't the same as the code below. getIdentifier() is non-virtual
1349 // and returns different names. NamedDecl returns the class name and
1350 // ObjCCategoryImplDecl returns the category name.
1351 return CIndexer::createCXString(CIMP->getIdentifier()->getNameStart());
1352
1353 if (ND->getIdentifier())
1354 return CIndexer::createCXString(ND->getIdentifier()->getNameStart());
1355
1356 return CIndexer::createCXString("");
1357}
1358
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001359CXString clang_getCursorSpelling(CXCursor C) {
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001360 if (clang_isTranslationUnit(C.kind))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001361 return clang_getTranslationUnitSpelling(C.data[2]);
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001362
Steve Narofff334b4e2009-09-02 18:26:48 +00001363 if (clang_isReference(C.kind)) {
1364 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00001365 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +00001366 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
1367 return CIndexer::createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00001368 }
1369 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +00001370 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
1371 return CIndexer::createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00001372 }
1373 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +00001374 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +00001375 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenek4b333d22010-01-12 00:36:38 +00001376 return CIndexer::createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00001377 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001378 case CXCursor_TypeRef: {
1379 TypeDecl *Type = getCursorTypeRef(C).first;
1380 assert(Type && "Missing type decl");
1381
1382 return CIndexer::createCXString(
1383 getCursorContext(C).getTypeDeclType(Type).getAsString().c_str(),
1384 true);
1385 }
1386
Daniel Dunbaracca7252009-11-30 20:42:49 +00001387 default:
Ted Kremenek4b333d22010-01-12 00:36:38 +00001388 return CIndexer::createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +00001389 }
1390 }
Douglas Gregor97b98722010-01-19 23:20:36 +00001391
1392 if (clang_isExpression(C.kind)) {
1393 Decl *D = getDeclFromExpr(getCursorExpr(C));
1394 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +00001395 return getDeclSpelling(D);
Douglas Gregor97b98722010-01-19 23:20:36 +00001396 return CIndexer::createCXString("");
1397 }
1398
Douglas Gregor60cbfac2010-01-25 16:56:17 +00001399 if (clang_isDeclaration(C.kind))
1400 return getDeclSpelling(getCursorDecl(C));
1401
1402 return CIndexer::createCXString("");
Steve Narofff334b4e2009-09-02 18:26:48 +00001403}
1404
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001405const char *clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00001406 switch (Kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00001407 case CXCursor_FunctionDecl: return "FunctionDecl";
1408 case CXCursor_TypedefDecl: return "TypedefDecl";
1409 case CXCursor_EnumDecl: return "EnumDecl";
1410 case CXCursor_EnumConstantDecl: return "EnumConstantDecl";
1411 case CXCursor_StructDecl: return "StructDecl";
1412 case CXCursor_UnionDecl: return "UnionDecl";
1413 case CXCursor_ClassDecl: return "ClassDecl";
1414 case CXCursor_FieldDecl: return "FieldDecl";
1415 case CXCursor_VarDecl: return "VarDecl";
1416 case CXCursor_ParmDecl: return "ParmDecl";
1417 case CXCursor_ObjCInterfaceDecl: return "ObjCInterfaceDecl";
1418 case CXCursor_ObjCCategoryDecl: return "ObjCCategoryDecl";
1419 case CXCursor_ObjCProtocolDecl: return "ObjCProtocolDecl";
1420 case CXCursor_ObjCPropertyDecl: return "ObjCPropertyDecl";
1421 case CXCursor_ObjCIvarDecl: return "ObjCIvarDecl";
1422 case CXCursor_ObjCInstanceMethodDecl: return "ObjCInstanceMethodDecl";
1423 case CXCursor_ObjCClassMethodDecl: return "ObjCClassMethodDecl";
Douglas Gregorb6998662010-01-19 19:34:47 +00001424 case CXCursor_ObjCImplementationDecl: return "ObjCImplementationDecl";
1425 case CXCursor_ObjCCategoryImplDecl: return "ObjCCategoryImplDecl";
Douglas Gregor30122132010-01-19 22:07:56 +00001426 case CXCursor_UnexposedDecl: return "UnexposedDecl";
Daniel Dunbaracca7252009-11-30 20:42:49 +00001427 case CXCursor_ObjCSuperClassRef: return "ObjCSuperClassRef";
1428 case CXCursor_ObjCProtocolRef: return "ObjCProtocolRef";
1429 case CXCursor_ObjCClassRef: return "ObjCClassRef";
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001430 case CXCursor_TypeRef: return "TypeRef";
Douglas Gregor97b98722010-01-19 23:20:36 +00001431 case CXCursor_UnexposedExpr: return "UnexposedExpr";
1432 case CXCursor_DeclRefExpr: return "DeclRefExpr";
1433 case CXCursor_MemberRefExpr: return "MemberRefExpr";
1434 case CXCursor_CallExpr: return "CallExpr";
1435 case CXCursor_ObjCMessageExpr: return "ObjCMessageExpr";
1436 case CXCursor_UnexposedStmt: return "UnexposedStmt";
Daniel Dunbaracca7252009-11-30 20:42:49 +00001437 case CXCursor_InvalidFile: return "InvalidFile";
1438 case CXCursor_NoDeclFound: return "NoDeclFound";
1439 case CXCursor_NotImplemented: return "NotImplemented";
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001440 case CXCursor_TranslationUnit: return "TranslationUnit";
Steve Naroff89922f82009-08-31 00:59:03 +00001441 }
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00001442
1443 llvm_unreachable("Unhandled CXCursorKind");
1444 return NULL;
Steve Naroff600866c2009-08-27 19:51:58 +00001445}
Steve Naroff89922f82009-08-31 00:59:03 +00001446
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001447enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
1448 CXCursor parent,
1449 CXClientData client_data) {
1450 CXCursor *BestCursor = static_cast<CXCursor *>(client_data);
1451 *BestCursor = cursor;
1452 return CXChildVisit_Recurse;
1453}
1454
Douglas Gregorb9790342010-01-22 21:44:22 +00001455CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
1456 if (!TU)
Ted Kremenekf4629892010-01-14 01:51:23 +00001457 return clang_getNullCursor();
Ted Kremenekf4629892010-01-14 01:51:23 +00001458
Douglas Gregorb9790342010-01-22 21:44:22 +00001459 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
1460
Ted Kremeneka297de22010-01-25 22:34:44 +00001461 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001462 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
1463 if (SLoc.isValid()) {
Daniel Dunbard52864b2010-02-14 10:02:57 +00001464 SourceRange RegionOfInterest(SLoc, SLoc.getFileLocWithOffset(1));
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001465
1466 // FIXME: Would be great to have a "hint" cursor, then walk from that
1467 // hint cursor upward until we find a cursor whose source range encloses
1468 // the region of interest, rather than starting from the translation unit.
1469 CXCursor Parent = clang_getTranslationUnitCursor(CXXUnit);
1470 CursorVisitor CursorVis(CXXUnit, GetCursorVisitor, &Result,
1471 Decl::MaxPCHLevel, RegionOfInterest);
1472 CursorVis.VisitChildren(Parent);
Steve Naroff77128dd2009-09-15 20:25:34 +00001473 }
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001474 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00001475}
1476
Ted Kremenek73885552009-11-17 19:28:59 +00001477CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00001478 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00001479}
1480
1481unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00001482 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00001483}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001484
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001485unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00001486 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
1487}
1488
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001489unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +00001490 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
1491}
Steve Naroff2d4d6292009-08-31 14:26:51 +00001492
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001493unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00001494 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
1495}
1496
Douglas Gregor97b98722010-01-19 23:20:36 +00001497unsigned clang_isExpression(enum CXCursorKind K) {
1498 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
1499}
1500
1501unsigned clang_isStatement(enum CXCursorKind K) {
1502 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
1503}
1504
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001505unsigned clang_isTranslationUnit(enum CXCursorKind K) {
1506 return K == CXCursor_TranslationUnit;
1507}
1508
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001509CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00001510 return C.kind;
1511}
1512
Douglas Gregor98258af2010-01-18 22:46:11 +00001513CXSourceLocation clang_getCursorLocation(CXCursor C) {
1514 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00001515 switch (C.kind) {
1516 case CXCursor_ObjCSuperClassRef: {
1517 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1518 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001519 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001520 }
1521
1522 case CXCursor_ObjCProtocolRef: {
1523 std::pair<ObjCProtocolDecl *, SourceLocation> P
1524 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001525 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001526 }
1527
1528 case CXCursor_ObjCClassRef: {
1529 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1530 = getCursorObjCClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001531 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001532 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001533
1534 case CXCursor_TypeRef: {
1535 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001536 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001537 }
Douglas Gregorf46034a2010-01-18 23:41:10 +00001538
Douglas Gregorf46034a2010-01-18 23:41:10 +00001539 default:
1540 // FIXME: Need a way to enumerate all non-reference cases.
1541 llvm_unreachable("Missed a reference kind");
1542 }
Douglas Gregor98258af2010-01-18 22:46:11 +00001543 }
Douglas Gregor97b98722010-01-19 23:20:36 +00001544
1545 if (clang_isExpression(C.kind))
Ted Kremeneka297de22010-01-25 22:34:44 +00001546 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00001547 getLocationFromExpr(getCursorExpr(C)));
1548
Douglas Gregor5352ac02010-01-28 00:27:43 +00001549 if (!getCursorDecl(C))
1550 return clang_getNullLocation();
Douglas Gregor98258af2010-01-18 22:46:11 +00001551
Douglas Gregorf46034a2010-01-18 23:41:10 +00001552 Decl *D = getCursorDecl(C);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001553 SourceLocation Loc = D->getLocation();
1554 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
1555 Loc = Class->getClassLoc();
Ted Kremeneka297de22010-01-25 22:34:44 +00001556 return cxloc::translateSourceLocation(D->getASTContext(), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00001557}
Douglas Gregora7bde202010-01-19 00:34:46 +00001558
1559CXSourceRange clang_getCursorExtent(CXCursor C) {
1560 if (clang_isReference(C.kind)) {
1561 switch (C.kind) {
1562 case CXCursor_ObjCSuperClassRef: {
1563 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1564 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001565 return cxloc::translateSourceRange(P.first->getASTContext(), P.second);
Douglas Gregora7bde202010-01-19 00:34:46 +00001566 }
1567
1568 case CXCursor_ObjCProtocolRef: {
1569 std::pair<ObjCProtocolDecl *, SourceLocation> P
1570 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001571 return cxloc::translateSourceRange(P.first->getASTContext(), P.second);
Douglas Gregora7bde202010-01-19 00:34:46 +00001572 }
1573
1574 case CXCursor_ObjCClassRef: {
1575 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1576 = getCursorObjCClassRef(C);
1577
Ted Kremeneka297de22010-01-25 22:34:44 +00001578 return cxloc::translateSourceRange(P.first->getASTContext(), P.second);
Douglas Gregora7bde202010-01-19 00:34:46 +00001579 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001580
1581 case CXCursor_TypeRef: {
1582 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001583 return cxloc::translateSourceRange(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001584 }
Douglas Gregora7bde202010-01-19 00:34:46 +00001585
Douglas Gregora7bde202010-01-19 00:34:46 +00001586 default:
1587 // FIXME: Need a way to enumerate all non-reference cases.
1588 llvm_unreachable("Missed a reference kind");
1589 }
1590 }
Douglas Gregor97b98722010-01-19 23:20:36 +00001591
1592 if (clang_isExpression(C.kind))
Ted Kremeneka297de22010-01-25 22:34:44 +00001593 return cxloc::translateSourceRange(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00001594 getCursorExpr(C)->getSourceRange());
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001595
1596 if (clang_isStatement(C.kind))
Ted Kremeneka297de22010-01-25 22:34:44 +00001597 return cxloc::translateSourceRange(getCursorContext(C),
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001598 getCursorStmt(C)->getSourceRange());
Douglas Gregora7bde202010-01-19 00:34:46 +00001599
Douglas Gregor5352ac02010-01-28 00:27:43 +00001600 if (!getCursorDecl(C))
1601 return clang_getNullRange();
Douglas Gregora7bde202010-01-19 00:34:46 +00001602
1603 Decl *D = getCursorDecl(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001604 return cxloc::translateSourceRange(D->getASTContext(), D->getSourceRange());
Douglas Gregora7bde202010-01-19 00:34:46 +00001605}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001606
1607CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001608 if (clang_isInvalid(C.kind))
1609 return clang_getNullCursor();
1610
1611 ASTUnit *CXXUnit = getCursorASTUnit(C);
Douglas Gregorb6998662010-01-19 19:34:47 +00001612 if (clang_isDeclaration(C.kind))
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001613 return C;
Douglas Gregor98258af2010-01-18 22:46:11 +00001614
Douglas Gregor97b98722010-01-19 23:20:36 +00001615 if (clang_isExpression(C.kind)) {
1616 Decl *D = getDeclFromExpr(getCursorExpr(C));
1617 if (D)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001618 return MakeCXCursor(D, CXXUnit);
Douglas Gregor97b98722010-01-19 23:20:36 +00001619 return clang_getNullCursor();
1620 }
1621
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001622 if (!clang_isReference(C.kind))
1623 return clang_getNullCursor();
1624
1625 switch (C.kind) {
1626 case CXCursor_ObjCSuperClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001627 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, CXXUnit);
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001628
1629 case CXCursor_ObjCProtocolRef: {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001630 return MakeCXCursor(getCursorObjCProtocolRef(C).first, CXXUnit);
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001631
1632 case CXCursor_ObjCClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001633 return MakeCXCursor(getCursorObjCClassRef(C).first, CXXUnit);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001634
1635 case CXCursor_TypeRef:
1636 return MakeCXCursor(getCursorTypeRef(C).first, CXXUnit);
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001637
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001638 default:
1639 // We would prefer to enumerate all non-reference cursor kinds here.
1640 llvm_unreachable("Unhandled reference cursor kind");
1641 break;
1642 }
1643 }
1644
1645 return clang_getNullCursor();
1646}
1647
Douglas Gregorb6998662010-01-19 19:34:47 +00001648CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001649 if (clang_isInvalid(C.kind))
1650 return clang_getNullCursor();
1651
1652 ASTUnit *CXXUnit = getCursorASTUnit(C);
1653
Douglas Gregorb6998662010-01-19 19:34:47 +00001654 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00001655 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00001656 C = clang_getCursorReferenced(C);
1657 WasReference = true;
1658 }
1659
1660 if (!clang_isDeclaration(C.kind))
1661 return clang_getNullCursor();
1662
1663 Decl *D = getCursorDecl(C);
1664 if (!D)
1665 return clang_getNullCursor();
1666
1667 switch (D->getKind()) {
1668 // Declaration kinds that don't really separate the notions of
1669 // declaration and definition.
1670 case Decl::Namespace:
1671 case Decl::Typedef:
1672 case Decl::TemplateTypeParm:
1673 case Decl::EnumConstant:
1674 case Decl::Field:
1675 case Decl::ObjCIvar:
1676 case Decl::ObjCAtDefsField:
1677 case Decl::ImplicitParam:
1678 case Decl::ParmVar:
1679 case Decl::NonTypeTemplateParm:
1680 case Decl::TemplateTemplateParm:
1681 case Decl::ObjCCategoryImpl:
1682 case Decl::ObjCImplementation:
1683 case Decl::LinkageSpec:
1684 case Decl::ObjCPropertyImpl:
1685 case Decl::FileScopeAsm:
1686 case Decl::StaticAssert:
1687 case Decl::Block:
1688 return C;
1689
1690 // Declaration kinds that don't make any sense here, but are
1691 // nonetheless harmless.
1692 case Decl::TranslationUnit:
1693 case Decl::Template:
1694 case Decl::ObjCContainer:
1695 break;
1696
1697 // Declaration kinds for which the definition is not resolvable.
1698 case Decl::UnresolvedUsingTypename:
1699 case Decl::UnresolvedUsingValue:
1700 break;
1701
1702 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001703 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
1704 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001705
1706 case Decl::NamespaceAlias:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001707 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001708
1709 case Decl::Enum:
1710 case Decl::Record:
1711 case Decl::CXXRecord:
1712 case Decl::ClassTemplateSpecialization:
1713 case Decl::ClassTemplatePartialSpecialization:
Douglas Gregor952b0172010-02-11 01:04:33 +00001714 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001715 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001716 return clang_getNullCursor();
1717
1718 case Decl::Function:
1719 case Decl::CXXMethod:
1720 case Decl::CXXConstructor:
1721 case Decl::CXXDestructor:
1722 case Decl::CXXConversion: {
1723 const FunctionDecl *Def = 0;
1724 if (cast<FunctionDecl>(D)->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001725 return MakeCXCursor(const_cast<FunctionDecl *>(Def), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001726 return clang_getNullCursor();
1727 }
1728
1729 case Decl::Var: {
Sebastian Redl31310a22010-02-01 20:16:42 +00001730 // Ask the variable if it has a definition.
1731 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
1732 return MakeCXCursor(Def, CXXUnit);
1733 return clang_getNullCursor();
Douglas Gregorb6998662010-01-19 19:34:47 +00001734 }
1735
1736 case Decl::FunctionTemplate: {
1737 const FunctionDecl *Def = 0;
1738 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001739 return MakeCXCursor(Def->getDescribedFunctionTemplate(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001740 return clang_getNullCursor();
1741 }
1742
1743 case Decl::ClassTemplate: {
1744 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
Douglas Gregor952b0172010-02-11 01:04:33 +00001745 ->getDefinition())
Douglas Gregorb6998662010-01-19 19:34:47 +00001746 return MakeCXCursor(
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001747 cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
1748 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001749 return clang_getNullCursor();
1750 }
1751
1752 case Decl::Using: {
1753 UsingDecl *Using = cast<UsingDecl>(D);
1754 CXCursor Def = clang_getNullCursor();
1755 for (UsingDecl::shadow_iterator S = Using->shadow_begin(),
1756 SEnd = Using->shadow_end();
1757 S != SEnd; ++S) {
1758 if (Def != clang_getNullCursor()) {
1759 // FIXME: We have no way to return multiple results.
1760 return clang_getNullCursor();
1761 }
1762
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001763 Def = clang_getCursorDefinition(MakeCXCursor((*S)->getTargetDecl(),
1764 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00001765 }
1766
1767 return Def;
1768 }
1769
1770 case Decl::UsingShadow:
1771 return clang_getCursorDefinition(
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001772 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
1773 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00001774
1775 case Decl::ObjCMethod: {
1776 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
1777 if (Method->isThisDeclarationADefinition())
1778 return C;
1779
1780 // Dig out the method definition in the associated
1781 // @implementation, if we have it.
1782 // FIXME: The ASTs should make finding the definition easier.
1783 if (ObjCInterfaceDecl *Class
1784 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
1785 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
1786 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
1787 Method->isInstanceMethod()))
1788 if (Def->isThisDeclarationADefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001789 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001790
1791 return clang_getNullCursor();
1792 }
1793
1794 case Decl::ObjCCategory:
1795 if (ObjCCategoryImplDecl *Impl
1796 = cast<ObjCCategoryDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001797 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001798 return clang_getNullCursor();
1799
1800 case Decl::ObjCProtocol:
1801 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
1802 return C;
1803 return clang_getNullCursor();
1804
1805 case Decl::ObjCInterface:
1806 // There are two notions of a "definition" for an Objective-C
1807 // class: the interface and its implementation. When we resolved a
1808 // reference to an Objective-C class, produce the @interface as
1809 // the definition; when we were provided with the interface,
1810 // produce the @implementation as the definition.
1811 if (WasReference) {
1812 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
1813 return C;
1814 } else if (ObjCImplementationDecl *Impl
1815 = cast<ObjCInterfaceDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001816 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001817 return clang_getNullCursor();
1818
1819 case Decl::ObjCProperty:
1820 // FIXME: We don't really know where to find the
1821 // ObjCPropertyImplDecls that implement this property.
1822 return clang_getNullCursor();
1823
1824 case Decl::ObjCCompatibleAlias:
1825 if (ObjCInterfaceDecl *Class
1826 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
1827 if (!Class->isForwardDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001828 return MakeCXCursor(Class, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001829
1830 return clang_getNullCursor();
1831
1832 case Decl::ObjCForwardProtocol: {
1833 ObjCForwardProtocolDecl *Forward = cast<ObjCForwardProtocolDecl>(D);
1834 if (Forward->protocol_size() == 1)
1835 return clang_getCursorDefinition(
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001836 MakeCXCursor(*Forward->protocol_begin(),
1837 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00001838
1839 // FIXME: Cannot return multiple definitions.
1840 return clang_getNullCursor();
1841 }
1842
1843 case Decl::ObjCClass: {
1844 ObjCClassDecl *Class = cast<ObjCClassDecl>(D);
1845 if (Class->size() == 1) {
1846 ObjCInterfaceDecl *IFace = Class->begin()->getInterface();
1847 if (!IFace->isForwardDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001848 return MakeCXCursor(IFace, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001849 return clang_getNullCursor();
1850 }
1851
1852 // FIXME: Cannot return multiple definitions.
1853 return clang_getNullCursor();
1854 }
1855
1856 case Decl::Friend:
1857 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001858 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00001859 return clang_getNullCursor();
1860
1861 case Decl::FriendTemplate:
1862 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001863 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00001864 return clang_getNullCursor();
1865 }
1866
1867 return clang_getNullCursor();
1868}
1869
1870unsigned clang_isCursorDefinition(CXCursor C) {
1871 if (!clang_isDeclaration(C.kind))
1872 return 0;
1873
1874 return clang_getCursorDefinition(C) == C;
1875}
1876
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001877void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00001878 const char **startBuf,
1879 const char **endBuf,
1880 unsigned *startLine,
1881 unsigned *startColumn,
1882 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001883 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00001884 assert(getCursorDecl(C) && "CXCursor has null decl");
1885 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00001886 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
1887 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekfb480492010-01-13 21:46:36 +00001888
Steve Naroff4ade6d62009-09-23 17:52:52 +00001889 SourceManager &SM = FD->getASTContext().getSourceManager();
1890 *startBuf = SM.getCharacterData(Body->getLBracLoc());
1891 *endBuf = SM.getCharacterData(Body->getRBracLoc());
1892 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
1893 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
1894 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
1895 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
1896}
Ted Kremenekfb480492010-01-13 21:46:36 +00001897
1898} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00001899
Ted Kremenekfb480492010-01-13 21:46:36 +00001900//===----------------------------------------------------------------------===//
Douglas Gregorfc8ea232010-01-26 17:06:03 +00001901// Token-based Operations.
1902//===----------------------------------------------------------------------===//
1903
1904/* CXToken layout:
1905 * int_data[0]: a CXTokenKind
1906 * int_data[1]: starting token location
1907 * int_data[2]: token length
1908 * int_data[3]: reserved
1909 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
1910 * otherwise unused.
1911 */
1912extern "C" {
1913
1914CXTokenKind clang_getTokenKind(CXToken CXTok) {
1915 return static_cast<CXTokenKind>(CXTok.int_data[0]);
1916}
1917
1918CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
1919 switch (clang_getTokenKind(CXTok)) {
1920 case CXToken_Identifier:
1921 case CXToken_Keyword:
1922 // We know we have an IdentifierInfo*, so use that.
1923 return CIndexer::createCXString(
1924 static_cast<IdentifierInfo *>(CXTok.ptr_data)->getNameStart());
1925
1926 case CXToken_Literal: {
1927 // We have stashed the starting pointer in the ptr_data field. Use it.
1928 const char *Text = static_cast<const char *>(CXTok.ptr_data);
1929 return CIndexer::createCXString(llvm::StringRef(Text, CXTok.int_data[2]),
1930 true);
1931 }
1932
1933 case CXToken_Punctuation:
1934 case CXToken_Comment:
1935 break;
1936 }
1937
1938 // We have to find the starting buffer pointer the hard way, by
1939 // deconstructing the source location.
1940 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
1941 if (!CXXUnit)
1942 return CIndexer::createCXString("");
1943
1944 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
1945 std::pair<FileID, unsigned> LocInfo
1946 = CXXUnit->getSourceManager().getDecomposedLoc(Loc);
1947 std::pair<const char *,const char *> Buffer
1948 = CXXUnit->getSourceManager().getBufferData(LocInfo.first);
1949
1950 return CIndexer::createCXString(llvm::StringRef(Buffer.first+LocInfo.second,
1951 CXTok.int_data[2]),
1952 true);
1953}
1954
1955CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
1956 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
1957 if (!CXXUnit)
1958 return clang_getNullLocation();
1959
1960 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
1961 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
1962}
1963
1964CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
1965 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregor5352ac02010-01-28 00:27:43 +00001966 if (!CXXUnit)
1967 return clang_getNullRange();
Douglas Gregorfc8ea232010-01-26 17:06:03 +00001968
1969 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
1970 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
1971}
1972
1973void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
1974 CXToken **Tokens, unsigned *NumTokens) {
1975 if (Tokens)
1976 *Tokens = 0;
1977 if (NumTokens)
1978 *NumTokens = 0;
1979
1980 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
1981 if (!CXXUnit || !Tokens || !NumTokens)
1982 return;
1983
Daniel Dunbar85b988f2010-02-14 08:31:57 +00001984 SourceRange R = cxloc::translateCXSourceRange(Range);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00001985 if (R.isInvalid())
1986 return;
1987
1988 SourceManager &SourceMgr = CXXUnit->getSourceManager();
1989 std::pair<FileID, unsigned> BeginLocInfo
1990 = SourceMgr.getDecomposedLoc(R.getBegin());
1991 std::pair<FileID, unsigned> EndLocInfo
1992 = SourceMgr.getDecomposedLoc(R.getEnd());
1993
1994 // Cannot tokenize across files.
1995 if (BeginLocInfo.first != EndLocInfo.first)
1996 return;
1997
1998 // Create a lexer
1999 std::pair<const char *,const char *> Buffer
2000 = SourceMgr.getBufferData(BeginLocInfo.first);
2001 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
2002 CXXUnit->getASTContext().getLangOptions(),
2003 Buffer.first, Buffer.first + BeginLocInfo.second, Buffer.second);
2004 Lex.SetCommentRetentionState(true);
2005
2006 // Lex tokens until we hit the end of the range.
2007 const char *EffectiveBufferEnd = Buffer.first + EndLocInfo.second;
2008 llvm::SmallVector<CXToken, 32> CXTokens;
2009 Token Tok;
2010 do {
2011 // Lex the next token
2012 Lex.LexFromRawLexer(Tok);
2013 if (Tok.is(tok::eof))
2014 break;
2015
2016 // Initialize the CXToken.
2017 CXToken CXTok;
2018
2019 // - Common fields
2020 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
2021 CXTok.int_data[2] = Tok.getLength();
2022 CXTok.int_data[3] = 0;
2023
2024 // - Kind-specific fields
2025 if (Tok.isLiteral()) {
2026 CXTok.int_data[0] = CXToken_Literal;
2027 CXTok.ptr_data = (void *)Tok.getLiteralData();
2028 } else if (Tok.is(tok::identifier)) {
2029 // Lookup the identifier to determine whether we have a
2030 std::pair<FileID, unsigned> LocInfo
2031 = SourceMgr.getDecomposedLoc(Tok.getLocation());
2032 const char *StartPos
2033 = CXXUnit->getSourceManager().getBufferData(LocInfo.first).first +
2034 LocInfo.second;
2035 IdentifierInfo *II
2036 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok, StartPos);
2037 CXTok.int_data[0] = II->getTokenID() == tok::identifier?
2038 CXToken_Identifier
2039 : CXToken_Keyword;
2040 CXTok.ptr_data = II;
2041 } else if (Tok.is(tok::comment)) {
2042 CXTok.int_data[0] = CXToken_Comment;
2043 CXTok.ptr_data = 0;
2044 } else {
2045 CXTok.int_data[0] = CXToken_Punctuation;
2046 CXTok.ptr_data = 0;
2047 }
2048 CXTokens.push_back(CXTok);
2049 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
2050
2051 if (CXTokens.empty())
2052 return;
2053
2054 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
2055 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
2056 *NumTokens = CXTokens.size();
2057}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002058
2059typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
2060
2061enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
2062 CXCursor parent,
2063 CXClientData client_data) {
2064 AnnotateTokensData *Data = static_cast<AnnotateTokensData *>(client_data);
2065
2066 // We only annotate the locations of declarations, simple
2067 // references, and expressions which directly reference something.
2068 CXCursorKind Kind = clang_getCursorKind(cursor);
2069 if (clang_isDeclaration(Kind) || clang_isReference(Kind)) {
2070 // Okay: We can annotate the location of this declaration with the
2071 // declaration or reference
2072 } else if (clang_isExpression(cursor.kind)) {
2073 if (Kind != CXCursor_DeclRefExpr &&
2074 Kind != CXCursor_MemberRefExpr &&
2075 Kind != CXCursor_ObjCMessageExpr)
2076 return CXChildVisit_Recurse;
2077
2078 CXCursor Referenced = clang_getCursorReferenced(cursor);
2079 if (Referenced == cursor || Referenced == clang_getNullCursor())
2080 return CXChildVisit_Recurse;
2081
2082 // Okay: we can annotate the location of this expression
2083 } else {
2084 // Nothing to annotate
2085 return CXChildVisit_Recurse;
2086 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002087
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002088 CXSourceLocation Loc = clang_getCursorLocation(cursor);
2089 (*Data)[Loc.int_data] = cursor;
2090 return CXChildVisit_Recurse;
2091}
2092
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002093void clang_annotateTokens(CXTranslationUnit TU,
2094 CXToken *Tokens, unsigned NumTokens,
2095 CXCursor *Cursors) {
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002096 if (NumTokens == 0)
2097 return;
2098
2099 // Any token we don't specifically annotate will have a NULL cursor.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002100 for (unsigned I = 0; I != NumTokens; ++I)
2101 Cursors[I] = clang_getNullCursor();
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002102
2103 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2104 if (!CXXUnit || !Tokens)
2105 return;
2106
2107 // Annotate all of the source locations in the region of interest that map
2108 SourceRange RegionOfInterest;
2109 RegionOfInterest.setBegin(
2110 cxloc::translateSourceLocation(clang_getTokenLocation(TU, Tokens[0])));
2111 SourceLocation End
2112 = cxloc::translateSourceLocation(clang_getTokenLocation(TU,
2113 Tokens[NumTokens - 1]));
Daniel Dunbard52864b2010-02-14 10:02:57 +00002114 RegionOfInterest.setEnd(CXXUnit->getPreprocessor().getLocForEndOfToken(End));
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002115 // FIXME: Would be great to have a "hint" cursor, then walk from that
2116 // hint cursor upward until we find a cursor whose source range encloses
2117 // the region of interest, rather than starting from the translation unit.
2118 AnnotateTokensData Annotated;
2119 CXCursor Parent = clang_getTranslationUnitCursor(CXXUnit);
2120 CursorVisitor AnnotateVis(CXXUnit, AnnotateTokensVisitor, &Annotated,
2121 Decl::MaxPCHLevel, RegionOfInterest);
2122 AnnotateVis.VisitChildren(Parent);
2123
2124 for (unsigned I = 0; I != NumTokens; ++I) {
2125 // Determine whether we saw a cursor at this token's location.
2126 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
2127 if (Pos == Annotated.end())
2128 continue;
2129
2130 Cursors[I] = Pos->second;
2131 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002132}
2133
2134void clang_disposeTokens(CXTranslationUnit TU,
2135 CXToken *Tokens, unsigned NumTokens) {
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002136 free(Tokens);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002137}
2138
2139} // end: extern "C"
2140
2141//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00002142// CXString Operations.
2143//===----------------------------------------------------------------------===//
2144
2145extern "C" {
2146const char *clang_getCString(CXString string) {
2147 return string.Spelling;
2148}
2149
2150void clang_disposeString(CXString string) {
2151 if (string.MustFreeString && string.Spelling)
2152 free((void*)string.Spelling);
2153}
Ted Kremenek04bb7162010-01-22 22:44:15 +00002154
Ted Kremenekfb480492010-01-13 21:46:36 +00002155} // end: extern "C"
Ted Kremenek04bb7162010-01-22 22:44:15 +00002156
2157//===----------------------------------------------------------------------===//
2158// Misc. utility functions.
2159//===----------------------------------------------------------------------===//
2160
2161extern "C" {
2162
Ted Kremeneka2a9d6e2010-02-12 22:54:40 +00002163CXString clang_getClangVersion() {
2164 return CIndexer::createCXString(getClangFullVersion(), true);
Ted Kremenek04bb7162010-01-22 22:44:15 +00002165}
2166
2167} // end: extern "C"
2168