blob: b7f028d8ae89f82fb6a3d192675013fc898cab62 [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?");
142 if (SM.isBeforeInTranslationUnit(R1.getEnd(), R2.getBegin()))
143 return RangeBefore;
144 if (SM.isBeforeInTranslationUnit(R2.getEnd(), R1.getBegin()))
145 return RangeAfter;
146 return RangeOverlap;
147}
148
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000149/// \brief Translate a Clang source range into a CIndex source range.
150///
151/// Clang internally represents ranges where the end location points to the
152/// start of the token at the end. However, for external clients it is more
153/// useful to have a CXSourceRange be a proper half-open interval. This routine
154/// does the appropriate translation.
155CXSourceRange cxloc::translateSourceRange(const SourceManager &SM,
156 const LangOptions &LangOpts,
157 SourceRange R) {
158 // FIXME: This is largely copy-paste from
159 // TextDiagnosticPrinter::HighlightRange. When it is clear that this is what
160 // we want the two routines should be refactored.
161
162 // We want the last character in this location, so we will adjust the
163 // instantiation location accordingly.
164
165 // If the location is from a macro instantiation, get the end of the
166 // instantiation range.
167 SourceLocation EndLoc = R.getEnd();
168 SourceLocation InstLoc = SM.getInstantiationLoc(EndLoc);
169 if (EndLoc.isMacroID())
170 InstLoc = SM.getInstantiationRange(EndLoc).second;
171
172 // Measure the length token we're pointing at, so we can adjust the physical
173 // location in the file to point at the last character.
174 //
175 // FIXME: This won't cope with trigraphs or escaped newlines well. For that,
176 // we actually need a preprocessor, which isn't currently available
177 // here. Eventually, we'll switch the pointer data of
178 // CXSourceLocation/CXSourceRange to a translation unit (CXXUnit), so that the
179 // preprocessor will be available here. At that point, we can use
180 // Preprocessor::getLocForEndOfToken().
181 if (InstLoc.isValid()) {
182 unsigned Length = Lexer::MeasureTokenLength(InstLoc, SM, LangOpts);
183 // FIXME: Temporarily represent as closed range to preserve API
184 // compatibility.
185 if (Length) --Length;
186 EndLoc = EndLoc.getFileLocWithOffset(Length);
187 }
188
189 CXSourceRange Result = { { (void *)&SM, (void *)&LangOpts },
190 R.getBegin().getRawEncoding(),
191 EndLoc.getRawEncoding() };
192 return Result;
193}
Douglas Gregor1db19de2010-01-19 21:36:55 +0000194
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000195//===----------------------------------------------------------------------===//
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000196// Cursor visitor.
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000197//===----------------------------------------------------------------------===//
198
Steve Naroff89922f82009-08-31 00:59:03 +0000199namespace {
Ted Kremenekedc8aa62010-01-16 00:36:30 +0000200
Douglas Gregorb1373d02010-01-20 20:59:29 +0000201// Cursor visitor.
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000202class CursorVisitor : public DeclVisitor<CursorVisitor, bool>,
Douglas Gregora59e3902010-01-21 23:27:09 +0000203 public TypeLocVisitor<CursorVisitor, bool>,
204 public StmtVisitor<CursorVisitor, bool>
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000205{
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000206 /// \brief The translation unit we are traversing.
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000207 ASTUnit *TU;
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000208
209 /// \brief The parent cursor whose children we are traversing.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000210 CXCursor Parent;
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000211
212 /// \brief The declaration that serves at the parent of any statement or
213 /// expression nodes.
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000214 Decl *StmtParent;
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000215
216 /// \brief The visitor function.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000217 CXCursorVisitor Visitor;
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000218
219 /// \brief The opaque client data, to be passed along to the visitor.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000220 CXClientData ClientData;
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000221
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000222 // MaxPCHLevel - the maximum PCH level of declarations that we will pass on
223 // to the visitor. Declarations with a PCH level greater than this value will
224 // be suppressed.
225 unsigned MaxPCHLevel;
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000226
227 /// \brief When valid, a source range to which the cursor should restrict
228 /// its search.
229 SourceRange RegionOfInterest;
230
Douglas Gregorb1373d02010-01-20 20:59:29 +0000231 using DeclVisitor<CursorVisitor, bool>::Visit;
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000232 using TypeLocVisitor<CursorVisitor, bool>::Visit;
Douglas Gregora59e3902010-01-21 23:27:09 +0000233 using StmtVisitor<CursorVisitor, bool>::Visit;
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000234
235 /// \brief Determine whether this particular source range comes before, comes
236 /// after, or overlaps the region of interest.
237 ///
238 /// \param R a source range retrieved from the abstract syntax tree.
239 RangeComparisonResult CompareRegionOfInterest(SourceRange R);
240
241 /// \brief Determine whether this particular source range comes before, comes
242 /// after, or overlaps the region of interest.
243 ///
244 /// \param CXR a source range retrieved from a cursor.
245 RangeComparisonResult CompareRegionOfInterest(CXSourceRange CXR);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000246
Steve Naroff89922f82009-08-31 00:59:03 +0000247public:
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000248 CursorVisitor(ASTUnit *TU, CXCursorVisitor Visitor, CXClientData ClientData,
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000249 unsigned MaxPCHLevel,
250 SourceRange RegionOfInterest = SourceRange())
251 : TU(TU), Visitor(Visitor), ClientData(ClientData),
252 MaxPCHLevel(MaxPCHLevel), RegionOfInterest(RegionOfInterest)
Douglas Gregorb1373d02010-01-20 20:59:29 +0000253 {
254 Parent.kind = CXCursor_NoDeclFound;
255 Parent.data[0] = 0;
256 Parent.data[1] = 0;
257 Parent.data[2] = 0;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000258 StmtParent = 0;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000259 }
260
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000261 bool Visit(CXCursor Cursor, bool CheckedRegionOfInterest = false);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000262 bool VisitChildren(CXCursor Parent);
263
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000264 // Declaration visitors
Douglas Gregorb1373d02010-01-20 20:59:29 +0000265 bool VisitDeclContext(DeclContext *DC);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000266 bool VisitTranslationUnitDecl(TranslationUnitDecl *D);
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000267 bool VisitTypedefDecl(TypedefDecl *D);
268 bool VisitTagDecl(TagDecl *D);
269 bool VisitEnumConstantDecl(EnumConstantDecl *D);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000270 bool VisitDeclaratorDecl(DeclaratorDecl *DD);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000271 bool VisitFunctionDecl(FunctionDecl *ND);
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000272 bool VisitFieldDecl(FieldDecl *D);
273 bool VisitVarDecl(VarDecl *);
274 bool VisitObjCMethodDecl(ObjCMethodDecl *ND);
Douglas Gregora59e3902010-01-21 23:27:09 +0000275 bool VisitObjCContainerDecl(ObjCContainerDecl *D);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000276 bool VisitObjCCategoryDecl(ObjCCategoryDecl *ND);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000277 bool VisitObjCProtocolDecl(ObjCProtocolDecl *PID);
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000278 bool VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
279 bool VisitObjCImplDecl(ObjCImplDecl *D);
280 bool VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
281 bool VisitObjCImplementationDecl(ObjCImplementationDecl *D);
282 // FIXME: ObjCPropertyDecl requires TypeSourceInfo, getter/setter locations,
283 // etc.
284 // FIXME: ObjCCompatibleAliasDecl requires aliased-class locations.
285 bool VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D);
286 bool VisitObjCClassDecl(ObjCClassDecl *D);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000287
288 // Type visitors
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000289 // FIXME: QualifiedTypeLoc doesn't provide any location information
290 bool VisitBuiltinTypeLoc(BuiltinTypeLoc TL);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000291 bool VisitTypedefTypeLoc(TypedefTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000292 bool VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL);
293 bool VisitTagTypeLoc(TagTypeLoc TL);
294 // FIXME: TemplateTypeParmTypeLoc doesn't provide any location information
295 bool VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL);
296 bool VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL);
297 bool VisitPointerTypeLoc(PointerTypeLoc TL);
298 bool VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL);
299 bool VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL);
300 bool VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL);
301 bool VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL);
302 bool VisitFunctionTypeLoc(FunctionTypeLoc TL);
303 bool VisitArrayTypeLoc(ArrayTypeLoc TL);
Douglas Gregor2332c112010-01-21 20:48:56 +0000304 // FIXME: Implement for TemplateSpecializationTypeLoc
305 // FIXME: Implement visitors here when the unimplemented TypeLocs get
306 // implemented
307 bool VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL);
308 bool VisitTypeOfTypeLoc(TypeOfTypeLoc TL);
Douglas Gregora59e3902010-01-21 23:27:09 +0000309
310 // Statement visitors
311 bool VisitStmt(Stmt *S);
312 bool VisitDeclStmt(DeclStmt *S);
Douglas Gregorf5bab412010-01-22 01:00:11 +0000313 // FIXME: LabelStmt label?
314 bool VisitIfStmt(IfStmt *S);
315 bool VisitSwitchStmt(SwitchStmt *S);
Douglas Gregor263b47b2010-01-25 16:12:32 +0000316 bool VisitWhileStmt(WhileStmt *S);
317 bool VisitForStmt(ForStmt *S);
Douglas Gregor336fd812010-01-23 00:40:08 +0000318
319 // Expression visitors
320 bool VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E);
321 bool VisitExplicitCastExpr(ExplicitCastExpr *E);
322 bool VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
Steve Naroff89922f82009-08-31 00:59:03 +0000323};
Douglas Gregorb1373d02010-01-20 20:59:29 +0000324
Ted Kremenekab188932010-01-05 19:32:54 +0000325} // end anonymous namespace
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000326
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000327RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
328 assert(RegionOfInterest.isValid() && "RangeCompare called with invalid range");
329 if (R.isInvalid())
330 return RangeOverlap;
331
332 // Move the end of the input range to the end of the last token in that
333 // range.
Douglas Gregor2b37c9e2010-01-29 00:47:48 +0000334 SourceLocation NewEnd
335 = TU->getPreprocessor().getLocForEndOfToken(R.getEnd(), 1);
336 if (NewEnd.isValid())
337 R.setEnd(NewEnd);
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000338 return RangeCompare(TU->getSourceManager(), R, RegionOfInterest);
339}
340
341RangeComparisonResult CursorVisitor::CompareRegionOfInterest(CXSourceRange CXR) {
Ted Kremeneka297de22010-01-25 22:34:44 +0000342 return CompareRegionOfInterest(cxloc::translateSourceRange(CXR));
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000343}
344
Douglas Gregorb1373d02010-01-20 20:59:29 +0000345/// \brief Visit the given cursor and, if requested by the visitor,
346/// its children.
347///
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000348/// \param Cursor the cursor to visit.
349///
350/// \param CheckRegionOfInterest if true, then the caller already checked that
351/// this cursor is within the region of interest.
352///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000353/// \returns true if the visitation should be aborted, false if it
354/// should continue.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000355bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
Douglas Gregorb1373d02010-01-20 20:59:29 +0000356 if (clang_isInvalid(Cursor.kind))
357 return false;
358
359 if (clang_isDeclaration(Cursor.kind)) {
360 Decl *D = getCursorDecl(Cursor);
361 assert(D && "Invalid declaration cursor");
362 if (D->getPCHLevel() > MaxPCHLevel)
363 return false;
364
365 if (D->isImplicit())
366 return false;
367 }
368
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000369 // If we have a range of interest, and this cursor doesn't intersect with it,
370 // we're done.
371 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
372 CXSourceRange Range = clang_getCursorExtent(Cursor);
Ted Kremeneka297de22010-01-25 22:34:44 +0000373 if (cxloc::translateSourceRange(Range).isInvalid() ||
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000374 CompareRegionOfInterest(Range))
375 return false;
376 }
377
Douglas Gregorb1373d02010-01-20 20:59:29 +0000378 switch (Visitor(Cursor, Parent, ClientData)) {
379 case CXChildVisit_Break:
380 return true;
381
382 case CXChildVisit_Continue:
383 return false;
384
385 case CXChildVisit_Recurse:
386 return VisitChildren(Cursor);
387 }
388
Douglas Gregorfd643772010-01-25 16:45:46 +0000389 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000390}
391
392/// \brief Visit the children of the given cursor.
393///
394/// \returns true if the visitation should be aborted, false if it
395/// should continue.
396bool CursorVisitor::VisitChildren(CXCursor Cursor) {
Douglas Gregora59e3902010-01-21 23:27:09 +0000397 if (clang_isReference(Cursor.kind)) {
398 // By definition, references have no children.
399 return false;
400 }
401
Douglas Gregorb1373d02010-01-20 20:59:29 +0000402 // Set the Parent field to Cursor, then back to its old value once we're
403 // done.
404 class SetParentRAII {
405 CXCursor &Parent;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000406 Decl *&StmtParent;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000407 CXCursor OldParent;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000408
Douglas Gregorb1373d02010-01-20 20:59:29 +0000409 public:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000410 SetParentRAII(CXCursor &Parent, Decl *&StmtParent, CXCursor NewParent)
411 : Parent(Parent), StmtParent(StmtParent), OldParent(Parent)
Douglas Gregorb1373d02010-01-20 20:59:29 +0000412 {
413 Parent = NewParent;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000414 if (clang_isDeclaration(Parent.kind))
415 StmtParent = getCursorDecl(Parent);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000416 }
417
418 ~SetParentRAII() {
419 Parent = OldParent;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000420 if (clang_isDeclaration(Parent.kind))
421 StmtParent = getCursorDecl(Parent);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000422 }
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000423 } SetParent(Parent, StmtParent, Cursor);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000424
425 if (clang_isDeclaration(Cursor.kind)) {
426 Decl *D = getCursorDecl(Cursor);
427 assert(D && "Invalid declaration cursor");
428 return Visit(D);
429 }
430
Douglas Gregora59e3902010-01-21 23:27:09 +0000431 if (clang_isStatement(Cursor.kind))
432 return Visit(getCursorStmt(Cursor));
433 if (clang_isExpression(Cursor.kind))
434 return Visit(getCursorExpr(Cursor));
435
Douglas Gregorb1373d02010-01-20 20:59:29 +0000436 if (clang_isTranslationUnit(Cursor.kind)) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000437 ASTUnit *CXXUnit = getCursorASTUnit(Cursor);
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000438 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
439 RegionOfInterest.isInvalid()) {
Douglas Gregor7b691f332010-01-20 21:13:59 +0000440 const std::vector<Decl*> &TLDs = CXXUnit->getTopLevelDecls();
441 for (std::vector<Decl*>::const_iterator it = TLDs.begin(),
442 ie = TLDs.end(); it != ie; ++it) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000443 if (Visit(MakeCXCursor(*it, CXXUnit), true))
Douglas Gregor7b691f332010-01-20 21:13:59 +0000444 return true;
445 }
446 } else {
447 return VisitDeclContext(
Douglas Gregorb1373d02010-01-20 20:59:29 +0000448 CXXUnit->getASTContext().getTranslationUnitDecl());
Douglas Gregor7b691f332010-01-20 21:13:59 +0000449 }
450
451 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000452 }
Douglas Gregora59e3902010-01-21 23:27:09 +0000453
Douglas Gregorb1373d02010-01-20 20:59:29 +0000454 // Nothing to visit at the moment.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000455 return false;
456}
457
Douglas Gregorb1373d02010-01-20 20:59:29 +0000458bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000459 for (DeclContext::decl_iterator
Douglas Gregorb1373d02010-01-20 20:59:29 +0000460 I = DC->decls_begin(), E = DC->decls_end(); I != E; ++I) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000461 if (RegionOfInterest.isValid()) {
462 SourceRange R = (*I)->getSourceRange();
463 if (R.isInvalid())
464 continue;
465
466 switch (CompareRegionOfInterest(R)) {
467 case RangeBefore:
468 // This declaration comes before the region of interest; skip it.
469 continue;
470
471 case RangeAfter:
472 // This declaration comes after the region of interest; we're done.
473 return false;
474
475 case RangeOverlap:
476 // This declaration overlaps the region of interest; visit it.
477 break;
478 }
479 }
480
481 if (Visit(MakeCXCursor(*I, TU), true))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000482 return true;
483 }
484
485 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000486}
487
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000488bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
489 llvm_unreachable("Translation units are visited directly by Visit()");
490 return false;
491}
492
493bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
494 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
495 return Visit(TSInfo->getTypeLoc());
496
497 return false;
498}
499
500bool CursorVisitor::VisitTagDecl(TagDecl *D) {
501 return VisitDeclContext(D);
502}
503
504bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
505 if (Expr *Init = D->getInitExpr())
506 return Visit(MakeCXCursor(Init, StmtParent, TU));
507 return false;
508}
509
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000510bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
511 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
512 if (Visit(TSInfo->getTypeLoc()))
513 return true;
514
515 return false;
516}
517
Douglas Gregorb1373d02010-01-20 20:59:29 +0000518bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000519 if (VisitDeclaratorDecl(ND))
520 return true;
521
Douglas Gregora59e3902010-01-21 23:27:09 +0000522 if (ND->isThisDeclarationADefinition() &&
523 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
524 return true;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000525
526 return false;
527}
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000528
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000529bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
530 if (VisitDeclaratorDecl(D))
531 return true;
532
533 if (Expr *BitWidth = D->getBitWidth())
534 return Visit(MakeCXCursor(BitWidth, StmtParent, TU));
535
536 return false;
537}
538
539bool CursorVisitor::VisitVarDecl(VarDecl *D) {
540 if (VisitDeclaratorDecl(D))
541 return true;
542
543 if (Expr *Init = D->getInit())
544 return Visit(MakeCXCursor(Init, StmtParent, TU));
545
546 return false;
547}
548
549bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
550 // FIXME: We really need a TypeLoc covering Objective-C method declarations.
551 // At the moment, we don't have information about locations in the return
552 // type.
553 for (ObjCMethodDecl::param_iterator P = ND->param_begin(),
554 PEnd = ND->param_end();
555 P != PEnd; ++P) {
556 if (Visit(MakeCXCursor(*P, TU)))
557 return true;
558 }
559
560 if (ND->isThisDeclarationADefinition() &&
561 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
562 return true;
563
564 return false;
565}
566
Douglas Gregora59e3902010-01-21 23:27:09 +0000567bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
568 return VisitDeclContext(D);
569}
570
Douglas Gregorb1373d02010-01-20 20:59:29 +0000571bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000572 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
573 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000574 return true;
575
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000576 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
577 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
578 E = ND->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000579 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000580 return true;
581
Douglas Gregora59e3902010-01-21 23:27:09 +0000582 return VisitObjCContainerDecl(ND);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000583}
584
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000585bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
586 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
587 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
588 E = PID->protocol_end(); I != E; ++I, ++PL)
589 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
590 return true;
591
592 return VisitObjCContainerDecl(PID);
593}
594
Douglas Gregorb1373d02010-01-20 20:59:29 +0000595bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000596 // Issue callbacks for super class.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000597 if (D->getSuperClass() &&
598 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000599 D->getSuperClassLoc(),
600 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000601 return true;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000602
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000603 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
604 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
605 E = D->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000606 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000607 return true;
608
Douglas Gregora59e3902010-01-21 23:27:09 +0000609 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000610}
611
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000612bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
613 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000614}
615
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000616bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
617 if (Visit(MakeCursorObjCClassRef(D->getCategoryDecl()->getClassInterface(),
618 D->getLocation(), TU)))
619 return true;
620
621 return VisitObjCImplDecl(D);
622}
623
624bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
625#if 0
626 // Issue callbacks for super class.
627 // FIXME: No source location information!
628 if (D->getSuperClass() &&
629 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
630 D->getSuperClassLoc(),
631 TU)))
632 return true;
633#endif
634
635 return VisitObjCImplDecl(D);
636}
637
638bool CursorVisitor::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D) {
639 ObjCForwardProtocolDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
640 for (ObjCForwardProtocolDecl::protocol_iterator I = D->protocol_begin(),
641 E = D->protocol_end();
642 I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000643 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000644 return true;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000645
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000646 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000647}
648
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000649bool CursorVisitor::VisitObjCClassDecl(ObjCClassDecl *D) {
650 for (ObjCClassDecl::iterator C = D->begin(), CEnd = D->end(); C != CEnd; ++C)
651 if (Visit(MakeCursorObjCClassRef(C->getInterface(), C->getLocation(), TU)))
652 return true;
653
654 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000655}
656
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000657bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
658 ASTContext &Context = TU->getASTContext();
659
660 // Some builtin types (such as Objective-C's "id", "sel", and
661 // "Class") have associated declarations. Create cursors for those.
662 QualType VisitType;
663 switch (TL.getType()->getAs<BuiltinType>()->getKind()) {
664 case BuiltinType::Void:
665 case BuiltinType::Bool:
666 case BuiltinType::Char_U:
667 case BuiltinType::UChar:
668 case BuiltinType::Char16:
669 case BuiltinType::Char32:
670 case BuiltinType::UShort:
671 case BuiltinType::UInt:
672 case BuiltinType::ULong:
673 case BuiltinType::ULongLong:
674 case BuiltinType::UInt128:
675 case BuiltinType::Char_S:
676 case BuiltinType::SChar:
677 case BuiltinType::WChar:
678 case BuiltinType::Short:
679 case BuiltinType::Int:
680 case BuiltinType::Long:
681 case BuiltinType::LongLong:
682 case BuiltinType::Int128:
683 case BuiltinType::Float:
684 case BuiltinType::Double:
685 case BuiltinType::LongDouble:
686 case BuiltinType::NullPtr:
687 case BuiltinType::Overload:
688 case BuiltinType::Dependent:
689 break;
690
691 case BuiltinType::UndeducedAuto: // FIXME: Deserves a cursor?
692 break;
693
694 case BuiltinType::ObjCId:
695 VisitType = Context.getObjCIdType();
696 break;
697
698 case BuiltinType::ObjCClass:
699 VisitType = Context.getObjCClassType();
700 break;
701
702 case BuiltinType::ObjCSel:
703 VisitType = Context.getObjCSelType();
704 break;
705 }
706
707 if (!VisitType.isNull()) {
708 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
709 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
710 TU));
711 }
712
713 return false;
714}
715
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000716bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
717 return Visit(MakeCursorTypeRef(TL.getTypedefDecl(), TL.getNameLoc(), TU));
718}
719
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000720bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
721 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
722}
723
724bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
725 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
726}
727
728bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
729 if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
730 return true;
731
732 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
733 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
734 TU)))
735 return true;
736 }
737
738 return false;
739}
740
741bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
742 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseTypeLoc()))
743 return true;
744
745 if (TL.hasProtocolsAsWritten()) {
746 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
747 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I),
748 TL.getProtocolLoc(I),
749 TU)))
750 return true;
751 }
752 }
753
754 return false;
755}
756
757bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
758 return Visit(TL.getPointeeLoc());
759}
760
761bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
762 return Visit(TL.getPointeeLoc());
763}
764
765bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
766 return Visit(TL.getPointeeLoc());
767}
768
769bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
770 return Visit(TL.getPointeeLoc());
771}
772
773bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
774 return Visit(TL.getPointeeLoc());
775}
776
777bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
778 if (Visit(TL.getResultLoc()))
779 return true;
780
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000781 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
782 if (Visit(MakeCXCursor(TL.getArg(I), TU)))
783 return true;
784
785 return false;
786}
787
788bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
789 if (Visit(TL.getElementLoc()))
790 return true;
791
792 if (Expr *Size = TL.getSizeExpr())
793 return Visit(MakeCXCursor(Size, StmtParent, TU));
794
795 return false;
796}
797
Douglas Gregor2332c112010-01-21 20:48:56 +0000798bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
799 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
800}
801
802bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
803 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
804 return Visit(TSInfo->getTypeLoc());
805
806 return false;
807}
808
Douglas Gregora59e3902010-01-21 23:27:09 +0000809bool CursorVisitor::VisitStmt(Stmt *S) {
810 for (Stmt::child_iterator Child = S->child_begin(), ChildEnd = S->child_end();
811 Child != ChildEnd; ++Child) {
Daniel Dunbar54d67ca2010-01-25 00:40:30 +0000812 if (*Child && Visit(MakeCXCursor(*Child, StmtParent, TU)))
Douglas Gregora59e3902010-01-21 23:27:09 +0000813 return true;
814 }
815
816 return false;
817}
818
819bool CursorVisitor::VisitDeclStmt(DeclStmt *S) {
820 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
821 D != DEnd; ++D) {
Douglas Gregor263b47b2010-01-25 16:12:32 +0000822 if (*D && Visit(MakeCXCursor(*D, TU)))
Douglas Gregora59e3902010-01-21 23:27:09 +0000823 return true;
824 }
825
826 return false;
827}
828
Douglas Gregorf5bab412010-01-22 01:00:11 +0000829bool CursorVisitor::VisitIfStmt(IfStmt *S) {
830 if (VarDecl *Var = S->getConditionVariable()) {
831 if (Visit(MakeCXCursor(Var, TU)))
832 return true;
Douglas Gregor263b47b2010-01-25 16:12:32 +0000833 }
Douglas Gregorf5bab412010-01-22 01:00:11 +0000834
Douglas Gregor263b47b2010-01-25 16:12:32 +0000835 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
836 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +0000837 if (S->getThen() && Visit(MakeCXCursor(S->getThen(), StmtParent, TU)))
838 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +0000839 if (S->getElse() && Visit(MakeCXCursor(S->getElse(), StmtParent, TU)))
840 return true;
841
842 return false;
843}
844
845bool CursorVisitor::VisitSwitchStmt(SwitchStmt *S) {
846 if (VarDecl *Var = S->getConditionVariable()) {
847 if (Visit(MakeCXCursor(Var, TU)))
848 return true;
Douglas Gregor263b47b2010-01-25 16:12:32 +0000849 }
850
851 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
852 return true;
853 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
854 return true;
855
856 return false;
857}
858
859bool CursorVisitor::VisitWhileStmt(WhileStmt *S) {
860 if (VarDecl *Var = S->getConditionVariable()) {
861 if (Visit(MakeCXCursor(Var, TU)))
862 return true;
863 }
864
865 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
866 return true;
867 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
Douglas Gregorf5bab412010-01-22 01:00:11 +0000868 return true;
869
Douglas Gregor263b47b2010-01-25 16:12:32 +0000870 return false;
871}
872
873bool CursorVisitor::VisitForStmt(ForStmt *S) {
874 if (S->getInit() && Visit(MakeCXCursor(S->getInit(), StmtParent, TU)))
875 return true;
876 if (VarDecl *Var = S->getConditionVariable()) {
877 if (Visit(MakeCXCursor(Var, TU)))
878 return true;
879 }
880
881 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
882 return true;
883 if (S->getInc() && Visit(MakeCXCursor(S->getInc(), StmtParent, TU)))
884 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +0000885 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
886 return true;
887
888 return false;
889}
890
Douglas Gregor336fd812010-01-23 00:40:08 +0000891bool CursorVisitor::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E) {
892 if (E->isArgumentType()) {
893 if (TypeSourceInfo *TSInfo = E->getArgumentTypeInfo())
894 return Visit(TSInfo->getTypeLoc());
895
896 return false;
897 }
898
899 return VisitExpr(E);
900}
901
902bool CursorVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
903 if (TypeSourceInfo *TSInfo = E->getTypeInfoAsWritten())
904 if (Visit(TSInfo->getTypeLoc()))
905 return true;
906
907 return VisitCastExpr(E);
908}
909
910bool CursorVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
911 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
912 if (Visit(TSInfo->getTypeLoc()))
913 return true;
914
915 return VisitExpr(E);
916}
917
Daniel Dunbar140fce22010-01-12 02:34:07 +0000918CXString CIndexer::createCXString(const char *String, bool DupString){
Benjamin Kramer62cf3222009-11-09 19:13:48 +0000919 CXString Str;
920 if (DupString) {
921 Str.Spelling = strdup(String);
922 Str.MustFreeString = 1;
923 } else {
924 Str.Spelling = String;
925 Str.MustFreeString = 0;
926 }
927 return Str;
928}
929
Douglas Gregorfc8ea232010-01-26 17:06:03 +0000930CXString CIndexer::createCXString(llvm::StringRef String, bool DupString) {
931 CXString Result;
932 if (DupString || (!String.empty() && String.data()[String.size()] != 0)) {
933 char *Spelling = (char *)malloc(String.size() + 1);
934 memmove(Spelling, String.data(), String.size());
935 Spelling[String.size()] = 0;
936 Result.Spelling = Spelling;
937 Result.MustFreeString = 1;
938 } else {
939 Result.Spelling = String.data();
940 Result.MustFreeString = 0;
941 }
942 return Result;
943}
944
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000945extern "C" {
Douglas Gregor936ea3b2010-01-28 00:56:43 +0000946CXIndex clang_createIndex(int excludeDeclarationsFromPCH) {
Douglas Gregora030b7c2010-01-22 20:35:53 +0000947 CIndexer *CIdxr = new CIndexer();
Steve Naroffe56b4ba2009-10-20 14:46:24 +0000948 if (excludeDeclarationsFromPCH)
949 CIdxr->setOnlyLocalDecls();
Steve Naroffe56b4ba2009-10-20 14:46:24 +0000950 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +0000951}
952
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000953void clang_disposeIndex(CXIndex CIdx) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +0000954 if (CIdx)
955 delete static_cast<CIndexer *>(CIdx);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +0000956}
957
Daniel Dunbar8506dde2009-12-03 01:54:28 +0000958void clang_setUseExternalASTGeneration(CXIndex CIdx, int value) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +0000959 if (CIdx) {
960 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
961 CXXIdx->setUseExternalASTGeneration(value);
962 }
Daniel Dunbar8506dde2009-12-03 01:54:28 +0000963}
964
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000965CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
Douglas Gregor5352ac02010-01-28 00:27:43 +0000966 const char *ast_filename,
967 CXDiagnosticCallback diag_callback,
968 CXClientData diag_client_data) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +0000969 if (!CIdx)
970 return 0;
971
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000972 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000973
Douglas Gregor5352ac02010-01-28 00:27:43 +0000974 // Configure the diagnostics.
975 DiagnosticOptions DiagOpts;
976 llvm::OwningPtr<Diagnostic> Diags;
977 Diags.reset(CompilerInstance::createDiagnostics(DiagOpts, 0, 0));
978 CIndexDiagnosticClient DiagClient(diag_callback, diag_client_data);
979 Diags->setClient(&DiagClient);
980
981 return ASTUnit::LoadFromPCHFile(ast_filename, *Diags,
Daniel Dunbar5262fda2009-12-03 01:45:44 +0000982 CXXIdx->getOnlyLocalDecls(),
983 /* UseBumpAllocator = */ true);
Steve Naroff600866c2009-08-27 19:51:58 +0000984}
985
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000986CXTranslationUnit
987clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
988 const char *source_filename,
989 int num_command_line_args,
Douglas Gregor4db64a42010-01-23 00:14:00 +0000990 const char **command_line_args,
991 unsigned num_unsaved_files,
Douglas Gregor5352ac02010-01-28 00:27:43 +0000992 struct CXUnsavedFile *unsaved_files,
993 CXDiagnosticCallback diag_callback,
994 CXClientData diag_client_data) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +0000995 if (!CIdx)
996 return 0;
997
Steve Naroffe56b4ba2009-10-20 14:46:24 +0000998 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
999
Douglas Gregor5352ac02010-01-28 00:27:43 +00001000 // Configure the diagnostics.
1001 DiagnosticOptions DiagOpts;
1002 llvm::OwningPtr<Diagnostic> Diags;
1003 Diags.reset(CompilerInstance::createDiagnostics(DiagOpts, 0, 0));
1004 CIndexDiagnosticClient DiagClient(diag_callback, diag_client_data);
1005 Diags->setClient(&DiagClient);
1006
Douglas Gregor4db64a42010-01-23 00:14:00 +00001007 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
1008 for (unsigned I = 0; I != num_unsaved_files; ++I) {
1009 const llvm::MemoryBuffer *Buffer
1010 = llvm::MemoryBuffer::getMemBuffer(unsaved_files[I].Contents,
1011 unsaved_files[I].Contents + unsaved_files[I].Length,
1012 unsaved_files[I].Filename);
1013 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
1014 Buffer));
1015 }
1016
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001017 if (!CXXIdx->getUseExternalASTGeneration()) {
1018 llvm::SmallVector<const char *, 16> Args;
1019
1020 // The 'source_filename' argument is optional. If the caller does not
1021 // specify it then it is assumed that the source file is specified
1022 // in the actual argument list.
1023 if (source_filename)
1024 Args.push_back(source_filename);
1025 Args.insert(Args.end(), command_line_args,
1026 command_line_args + num_command_line_args);
1027
Douglas Gregor5352ac02010-01-28 00:27:43 +00001028 unsigned NumErrors = Diags->getNumErrors();
Ted Kremenek8a8da7d2010-01-06 03:42:32 +00001029
Ted Kremenek29b72842010-01-07 22:49:05 +00001030#ifdef USE_CRASHTRACER
1031 ArgsCrashTracerInfo ACTI(Args);
Ted Kremenek8a8da7d2010-01-06 03:42:32 +00001032#endif
1033
Daniel Dunbar94220972009-12-05 02:17:18 +00001034 llvm::OwningPtr<ASTUnit> Unit(
1035 ASTUnit::LoadFromCommandLine(Args.data(), Args.data() + Args.size(),
Douglas Gregor5352ac02010-01-28 00:27:43 +00001036 *Diags,
Daniel Dunbar869824e2009-12-13 03:46:13 +00001037 CXXIdx->getClangResourcesPath(),
Daniel Dunbar94220972009-12-05 02:17:18 +00001038 CXXIdx->getOnlyLocalDecls(),
Douglas Gregor4db64a42010-01-23 00:14:00 +00001039 /* UseBumpAllocator = */ true,
1040 RemappedFiles.data(),
1041 RemappedFiles.size()));
Ted Kremenek29b72842010-01-07 22:49:05 +00001042
Daniel Dunbar94220972009-12-05 02:17:18 +00001043 // FIXME: Until we have broader testing, just drop the entire AST if we
1044 // encountered an error.
Douglas Gregor5352ac02010-01-28 00:27:43 +00001045 if (NumErrors != Diags->getNumErrors())
Daniel Dunbar94220972009-12-05 02:17:18 +00001046 return 0;
1047
1048 return Unit.take();
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001049 }
1050
Ted Kremenek139ba862009-10-22 00:03:57 +00001051 // Build up the arguments for invoking 'clang'.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001052 std::vector<const char *> argv;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001053
Ted Kremenek139ba862009-10-22 00:03:57 +00001054 // First add the complete path to the 'clang' executable.
1055 llvm::sys::Path ClangPath = static_cast<CIndexer *>(CIdx)->getClangPath();
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00001056 argv.push_back(ClangPath.c_str());
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001057
Ted Kremenek139ba862009-10-22 00:03:57 +00001058 // Add the '-emit-ast' option as our execution mode for 'clang'.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001059 argv.push_back("-emit-ast");
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001060
Ted Kremenek139ba862009-10-22 00:03:57 +00001061 // The 'source_filename' argument is optional. If the caller does not
1062 // specify it then it is assumed that the source file is specified
1063 // in the actual argument list.
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001064 if (source_filename)
1065 argv.push_back(source_filename);
Ted Kremenek139ba862009-10-22 00:03:57 +00001066
Steve Naroff37b5ac22009-10-15 20:50:09 +00001067 // Generate a temporary name for the AST file.
Ted Kremenek139ba862009-10-22 00:03:57 +00001068 argv.push_back("-o");
Steve Naroff37b5ac22009-10-15 20:50:09 +00001069 char astTmpFile[L_tmpnam];
Ted Kremenek74cd0692009-10-15 23:21:22 +00001070 argv.push_back(tmpnam(astTmpFile));
Ted Kremenek139ba862009-10-22 00:03:57 +00001071
Douglas Gregor4db64a42010-01-23 00:14:00 +00001072 // Remap any unsaved files to temporary files.
1073 std::vector<llvm::sys::Path> TemporaryFiles;
1074 std::vector<std::string> RemapArgs;
1075 if (RemapFiles(num_unsaved_files, unsaved_files, RemapArgs, TemporaryFiles))
1076 return 0;
1077
1078 // The pointers into the elements of RemapArgs are stable because we
1079 // won't be adding anything to RemapArgs after this point.
1080 for (unsigned i = 0, e = RemapArgs.size(); i != e; ++i)
1081 argv.push_back(RemapArgs[i].c_str());
1082
Ted Kremenek139ba862009-10-22 00:03:57 +00001083 // Process the compiler options, stripping off '-o', '-c', '-fsyntax-only'.
1084 for (int i = 0; i < num_command_line_args; ++i)
1085 if (const char *arg = command_line_args[i]) {
1086 if (strcmp(arg, "-o") == 0) {
1087 ++i; // Also skip the matching argument.
1088 continue;
1089 }
1090 if (strcmp(arg, "-emit-ast") == 0 ||
1091 strcmp(arg, "-c") == 0 ||
1092 strcmp(arg, "-fsyntax-only") == 0) {
1093 continue;
1094 }
1095
1096 // Keep the argument.
1097 argv.push_back(arg);
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001098 }
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001099
Douglas Gregord93256e2010-01-28 06:00:51 +00001100 // Generate a temporary name for the diagnostics file.
1101 char tmpFileResults[L_tmpnam];
1102 char *tmpResultsFileName = tmpnam(tmpFileResults);
1103 llvm::sys::Path DiagnosticsFile(tmpResultsFileName);
1104 TemporaryFiles.push_back(DiagnosticsFile);
1105 argv.push_back("-fdiagnostics-binary");
1106
Ted Kremenek139ba862009-10-22 00:03:57 +00001107 // Add the null terminator.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001108 argv.push_back(NULL);
1109
Ted Kremenekfeb15e32009-10-26 22:14:08 +00001110 // Invoke 'clang'.
1111 llvm::sys::Path DevNull; // leave empty, causes redirection to /dev/null
1112 // on Unix or NUL (Windows).
Ted Kremenek379afec2009-10-22 03:24:01 +00001113 std::string ErrMsg;
Douglas Gregord93256e2010-01-28 06:00:51 +00001114 const llvm::sys::Path *Redirects[] = { &DevNull, &DevNull, &DiagnosticsFile,
1115 NULL };
Ted Kremenek379afec2009-10-22 03:24:01 +00001116 llvm::sys::Program::ExecuteAndWait(ClangPath, &argv[0], /* env */ NULL,
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001117 /* redirects */ &Redirects[0],
Ted Kremenek379afec2009-10-22 03:24:01 +00001118 /* secondsToWait */ 0, /* memoryLimits */ 0, &ErrMsg);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001119
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001120 if (!ErrMsg.empty()) {
1121 std::string AllArgs;
Ted Kremenek379afec2009-10-22 03:24:01 +00001122 for (std::vector<const char*>::iterator I = argv.begin(), E = argv.end();
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001123 I != E; ++I) {
1124 AllArgs += ' ';
Ted Kremenek779e5f42009-10-26 22:08:39 +00001125 if (*I)
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001126 AllArgs += *I;
Ted Kremenek779e5f42009-10-26 22:08:39 +00001127 }
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001128
1129 Diags->Report(diag::err_fe_clang) << AllArgs << ErrMsg;
Ted Kremenek379afec2009-10-22 03:24:01 +00001130 }
Benjamin Kramer0829a832009-10-18 11:19:36 +00001131
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001132 // FIXME: Parse the (redirected) standard error to emit diagnostics.
1133
Douglas Gregor5352ac02010-01-28 00:27:43 +00001134 ASTUnit *ATU = ASTUnit::LoadFromPCHFile(astTmpFile, *Diags,
Douglas Gregor4db64a42010-01-23 00:14:00 +00001135 CXXIdx->getOnlyLocalDecls(),
1136 /* UseBumpAllocator = */ true,
1137 RemappedFiles.data(),
1138 RemappedFiles.size());
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001139 if (ATU)
1140 ATU->unlinkTemporaryFile();
Douglas Gregor4db64a42010-01-23 00:14:00 +00001141
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00001142 // FIXME: Currently we don't report diagnostics on invalid ASTs.
1143 if (ATU)
1144 ReportSerializedDiagnostics(DiagnosticsFile, *Diags,
1145 num_unsaved_files, unsaved_files,
1146 ATU->getASTContext().getLangOptions());
Douglas Gregord93256e2010-01-28 06:00:51 +00001147
Douglas Gregor4db64a42010-01-23 00:14:00 +00001148 for (unsigned i = 0, e = TemporaryFiles.size(); i != e; ++i)
1149 TemporaryFiles[i].eraseFromDisk();
1150
Steve Naroffe19944c2009-10-15 22:23:48 +00001151 return ATU;
Steve Naroff5b7d8e22009-10-15 20:04:39 +00001152}
1153
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001154void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001155 if (CTUnit)
1156 delete static_cast<ASTUnit *>(CTUnit);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00001157}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001158
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001159CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001160 if (!CTUnit)
1161 return CIndexer::createCXString("");
1162
Steve Naroff77accc12009-09-03 18:19:54 +00001163 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit);
Ted Kremenek4b333d22010-01-12 00:36:38 +00001164 return CIndexer::createCXString(CXXUnit->getOriginalSourceFileName().c_str(),
1165 true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +00001166}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +00001167
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001168CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001169 CXCursor Result = { CXCursor_TranslationUnit, { 0, 0, TU } };
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001170 return Result;
1171}
1172
Ted Kremenekfb480492010-01-13 21:46:36 +00001173} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +00001174
Ted Kremenekfb480492010-01-13 21:46:36 +00001175//===----------------------------------------------------------------------===//
Douglas Gregor1db19de2010-01-19 21:36:55 +00001176// CXSourceLocation and CXSourceRange Operations.
1177//===----------------------------------------------------------------------===//
1178
Douglas Gregorb9790342010-01-22 21:44:22 +00001179extern "C" {
1180CXSourceLocation clang_getNullLocation() {
Douglas Gregor5352ac02010-01-28 00:27:43 +00001181 CXSourceLocation Result = { { 0, 0 }, 0 };
Douglas Gregorb9790342010-01-22 21:44:22 +00001182 return Result;
1183}
1184
1185unsigned clang_equalLocations(CXSourceLocation loc1, CXSourceLocation loc2) {
Daniel Dunbar90a6b9e2010-01-30 23:58:27 +00001186 return (loc1.ptr_data[0] == loc2.ptr_data[0] &&
1187 loc1.ptr_data[1] == loc2.ptr_data[1] &&
1188 loc1.int_data == loc2.int_data);
Douglas Gregorb9790342010-01-22 21:44:22 +00001189}
1190
1191CXSourceLocation clang_getLocation(CXTranslationUnit tu,
1192 CXFile file,
1193 unsigned line,
1194 unsigned column) {
1195 if (!tu)
1196 return clang_getNullLocation();
1197
1198 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
1199 SourceLocation SLoc
1200 = CXXUnit->getSourceManager().getLocation(
1201 static_cast<const FileEntry *>(file),
1202 line, column);
1203
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00001204 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
Douglas Gregorb9790342010-01-22 21:44:22 +00001205}
1206
Douglas Gregor5352ac02010-01-28 00:27:43 +00001207CXSourceRange clang_getNullRange() {
1208 CXSourceRange Result = { { 0, 0 }, 0, 0 };
1209 return Result;
1210}
Douglas Gregorb9790342010-01-22 21:44:22 +00001211
Douglas Gregor5352ac02010-01-28 00:27:43 +00001212CXSourceRange clang_getRange(CXSourceLocation begin, CXSourceLocation end) {
1213 if (begin.ptr_data[0] != end.ptr_data[0] ||
1214 begin.ptr_data[1] != end.ptr_data[1])
1215 return clang_getNullRange();
1216
1217 CXSourceRange Result = { { begin.ptr_data[0], begin.ptr_data[1] },
1218 begin.int_data, end.int_data };
Douglas Gregorb9790342010-01-22 21:44:22 +00001219 return Result;
1220}
1221
Douglas Gregor46766dc2010-01-26 19:19:08 +00001222void clang_getInstantiationLocation(CXSourceLocation location,
1223 CXFile *file,
1224 unsigned *line,
1225 unsigned *column,
1226 unsigned *offset) {
Douglas Gregor1db19de2010-01-19 21:36:55 +00001227 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
1228
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00001229 if (!location.ptr_data[0] || Loc.isInvalid()) {
Douglas Gregor46766dc2010-01-26 19:19:08 +00001230 if (file)
1231 *file = 0;
1232 if (line)
1233 *line = 0;
1234 if (column)
1235 *column = 0;
1236 if (offset)
1237 *offset = 0;
1238 return;
1239 }
1240
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00001241 const SourceManager &SM =
1242 *static_cast<const SourceManager*>(location.ptr_data[0]);
Douglas Gregor1db19de2010-01-19 21:36:55 +00001243 SourceLocation InstLoc = SM.getInstantiationLoc(Loc);
Douglas Gregor1db19de2010-01-19 21:36:55 +00001244
1245 if (file)
1246 *file = (void *)SM.getFileEntryForID(SM.getFileID(InstLoc));
1247 if (line)
1248 *line = SM.getInstantiationLineNumber(InstLoc);
1249 if (column)
1250 *column = SM.getInstantiationColumnNumber(InstLoc);
Douglas Gregore69517c2010-01-26 03:07:15 +00001251 if (offset)
Douglas Gregor46766dc2010-01-26 19:19:08 +00001252 *offset = SM.getDecomposedLoc(InstLoc).second;
Douglas Gregore69517c2010-01-26 03:07:15 +00001253}
1254
Douglas Gregor1db19de2010-01-19 21:36:55 +00001255CXSourceLocation clang_getRangeStart(CXSourceRange range) {
Douglas Gregor5352ac02010-01-28 00:27:43 +00001256 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
1257 range.begin_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00001258 return Result;
1259}
1260
1261CXSourceLocation clang_getRangeEnd(CXSourceRange range) {
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00001262 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00001263 range.end_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00001264 return Result;
1265}
1266
Douglas Gregorb9790342010-01-22 21:44:22 +00001267} // end: extern "C"
1268
Douglas Gregor1db19de2010-01-19 21:36:55 +00001269//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00001270// CXFile Operations.
1271//===----------------------------------------------------------------------===//
1272
1273extern "C" {
Steve Naroff88145032009-10-27 14:35:18 +00001274const char *clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00001275 if (!SFile)
1276 return 0;
1277
Steve Naroff88145032009-10-27 14:35:18 +00001278 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
1279 return FEnt->getName();
1280}
1281
1282time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00001283 if (!SFile)
1284 return 0;
1285
Steve Naroff88145032009-10-27 14:35:18 +00001286 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
1287 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +00001288}
Douglas Gregorb9790342010-01-22 21:44:22 +00001289
1290CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
1291 if (!tu)
1292 return 0;
1293
1294 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
1295
1296 FileManager &FMgr = CXXUnit->getFileManager();
1297 const FileEntry *File = FMgr.getFile(file_name, file_name+strlen(file_name));
1298 return const_cast<FileEntry *>(File);
1299}
1300
Ted Kremenekfb480492010-01-13 21:46:36 +00001301} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +00001302
Ted Kremenekfb480492010-01-13 21:46:36 +00001303//===----------------------------------------------------------------------===//
1304// CXCursor Operations.
1305//===----------------------------------------------------------------------===//
1306
Ted Kremenekfb480492010-01-13 21:46:36 +00001307static Decl *getDeclFromExpr(Stmt *E) {
1308 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
1309 return RefExpr->getDecl();
1310 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
1311 return ME->getMemberDecl();
1312 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
1313 return RE->getDecl();
1314
1315 if (CallExpr *CE = dyn_cast<CallExpr>(E))
1316 return getDeclFromExpr(CE->getCallee());
1317 if (CastExpr *CE = dyn_cast<CastExpr>(E))
1318 return getDeclFromExpr(CE->getSubExpr());
1319 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
1320 return OME->getMethodDecl();
1321
1322 return 0;
1323}
1324
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00001325static SourceLocation getLocationFromExpr(Expr *E) {
1326 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
1327 return /*FIXME:*/Msg->getLeftLoc();
1328 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
1329 return DRE->getLocation();
1330 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
1331 return Member->getMemberLoc();
1332 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
1333 return Ivar->getLocation();
1334 return E->getLocStart();
1335}
1336
Ted Kremenekfb480492010-01-13 21:46:36 +00001337extern "C" {
Douglas Gregorb1373d02010-01-20 20:59:29 +00001338
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001339unsigned clang_visitChildren(CXCursor parent,
Douglas Gregorb1373d02010-01-20 20:59:29 +00001340 CXCursorVisitor visitor,
1341 CXClientData client_data) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001342 ASTUnit *CXXUnit = getCursorASTUnit(parent);
Douglas Gregorb1373d02010-01-20 20:59:29 +00001343
1344 unsigned PCHLevel = Decl::MaxPCHLevel;
1345
1346 // Set the PCHLevel to filter out unwanted decls if requested.
1347 if (CXXUnit->getOnlyLocalDecls()) {
1348 PCHLevel = 0;
1349
1350 // If the main input was an AST, bump the level.
1351 if (CXXUnit->isMainFileAST())
1352 ++PCHLevel;
1353 }
1354
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001355 CursorVisitor CursorVis(CXXUnit, visitor, client_data, PCHLevel);
Douglas Gregorb1373d02010-01-20 20:59:29 +00001356 return CursorVis.VisitChildren(parent);
1357}
1358
Douglas Gregor78205d42010-01-20 21:45:58 +00001359static CXString getDeclSpelling(Decl *D) {
1360 NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
1361 if (!ND)
1362 return CIndexer::createCXString("");
1363
1364 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
1365 return CIndexer::createCXString(OMD->getSelector().getAsString().c_str(),
1366 true);
1367
1368 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
1369 // No, this isn't the same as the code below. getIdentifier() is non-virtual
1370 // and returns different names. NamedDecl returns the class name and
1371 // ObjCCategoryImplDecl returns the category name.
1372 return CIndexer::createCXString(CIMP->getIdentifier()->getNameStart());
1373
1374 if (ND->getIdentifier())
1375 return CIndexer::createCXString(ND->getIdentifier()->getNameStart());
1376
1377 return CIndexer::createCXString("");
1378}
1379
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001380CXString clang_getCursorSpelling(CXCursor C) {
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001381 if (clang_isTranslationUnit(C.kind))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001382 return clang_getTranslationUnitSpelling(C.data[2]);
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001383
Steve Narofff334b4e2009-09-02 18:26:48 +00001384 if (clang_isReference(C.kind)) {
1385 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00001386 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +00001387 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
1388 return CIndexer::createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00001389 }
1390 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +00001391 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
1392 return CIndexer::createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00001393 }
1394 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +00001395 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +00001396 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenek4b333d22010-01-12 00:36:38 +00001397 return CIndexer::createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00001398 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001399 case CXCursor_TypeRef: {
1400 TypeDecl *Type = getCursorTypeRef(C).first;
1401 assert(Type && "Missing type decl");
1402
1403 return CIndexer::createCXString(
1404 getCursorContext(C).getTypeDeclType(Type).getAsString().c_str(),
1405 true);
1406 }
1407
Daniel Dunbaracca7252009-11-30 20:42:49 +00001408 default:
Ted Kremenek4b333d22010-01-12 00:36:38 +00001409 return CIndexer::createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +00001410 }
1411 }
Douglas Gregor97b98722010-01-19 23:20:36 +00001412
1413 if (clang_isExpression(C.kind)) {
1414 Decl *D = getDeclFromExpr(getCursorExpr(C));
1415 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +00001416 return getDeclSpelling(D);
Douglas Gregor97b98722010-01-19 23:20:36 +00001417 return CIndexer::createCXString("");
1418 }
1419
Douglas Gregor60cbfac2010-01-25 16:56:17 +00001420 if (clang_isDeclaration(C.kind))
1421 return getDeclSpelling(getCursorDecl(C));
1422
1423 return CIndexer::createCXString("");
Steve Narofff334b4e2009-09-02 18:26:48 +00001424}
1425
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001426const char *clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00001427 switch (Kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00001428 case CXCursor_FunctionDecl: return "FunctionDecl";
1429 case CXCursor_TypedefDecl: return "TypedefDecl";
1430 case CXCursor_EnumDecl: return "EnumDecl";
1431 case CXCursor_EnumConstantDecl: return "EnumConstantDecl";
1432 case CXCursor_StructDecl: return "StructDecl";
1433 case CXCursor_UnionDecl: return "UnionDecl";
1434 case CXCursor_ClassDecl: return "ClassDecl";
1435 case CXCursor_FieldDecl: return "FieldDecl";
1436 case CXCursor_VarDecl: return "VarDecl";
1437 case CXCursor_ParmDecl: return "ParmDecl";
1438 case CXCursor_ObjCInterfaceDecl: return "ObjCInterfaceDecl";
1439 case CXCursor_ObjCCategoryDecl: return "ObjCCategoryDecl";
1440 case CXCursor_ObjCProtocolDecl: return "ObjCProtocolDecl";
1441 case CXCursor_ObjCPropertyDecl: return "ObjCPropertyDecl";
1442 case CXCursor_ObjCIvarDecl: return "ObjCIvarDecl";
1443 case CXCursor_ObjCInstanceMethodDecl: return "ObjCInstanceMethodDecl";
1444 case CXCursor_ObjCClassMethodDecl: return "ObjCClassMethodDecl";
Douglas Gregorb6998662010-01-19 19:34:47 +00001445 case CXCursor_ObjCImplementationDecl: return "ObjCImplementationDecl";
1446 case CXCursor_ObjCCategoryImplDecl: return "ObjCCategoryImplDecl";
Douglas Gregor30122132010-01-19 22:07:56 +00001447 case CXCursor_UnexposedDecl: return "UnexposedDecl";
Daniel Dunbaracca7252009-11-30 20:42:49 +00001448 case CXCursor_ObjCSuperClassRef: return "ObjCSuperClassRef";
1449 case CXCursor_ObjCProtocolRef: return "ObjCProtocolRef";
1450 case CXCursor_ObjCClassRef: return "ObjCClassRef";
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001451 case CXCursor_TypeRef: return "TypeRef";
Douglas Gregor97b98722010-01-19 23:20:36 +00001452 case CXCursor_UnexposedExpr: return "UnexposedExpr";
1453 case CXCursor_DeclRefExpr: return "DeclRefExpr";
1454 case CXCursor_MemberRefExpr: return "MemberRefExpr";
1455 case CXCursor_CallExpr: return "CallExpr";
1456 case CXCursor_ObjCMessageExpr: return "ObjCMessageExpr";
1457 case CXCursor_UnexposedStmt: return "UnexposedStmt";
Daniel Dunbaracca7252009-11-30 20:42:49 +00001458 case CXCursor_InvalidFile: return "InvalidFile";
1459 case CXCursor_NoDeclFound: return "NoDeclFound";
1460 case CXCursor_NotImplemented: return "NotImplemented";
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001461 case CXCursor_TranslationUnit: return "TranslationUnit";
Steve Naroff89922f82009-08-31 00:59:03 +00001462 }
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00001463
1464 llvm_unreachable("Unhandled CXCursorKind");
1465 return NULL;
Steve Naroff600866c2009-08-27 19:51:58 +00001466}
Steve Naroff89922f82009-08-31 00:59:03 +00001467
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001468enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
1469 CXCursor parent,
1470 CXClientData client_data) {
1471 CXCursor *BestCursor = static_cast<CXCursor *>(client_data);
1472 *BestCursor = cursor;
1473 return CXChildVisit_Recurse;
1474}
1475
Douglas Gregorb9790342010-01-22 21:44:22 +00001476CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
1477 if (!TU)
Ted Kremenekf4629892010-01-14 01:51:23 +00001478 return clang_getNullCursor();
Ted Kremenekf4629892010-01-14 01:51:23 +00001479
Douglas Gregorb9790342010-01-22 21:44:22 +00001480 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
1481
Ted Kremeneka297de22010-01-25 22:34:44 +00001482 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001483 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
1484 if (SLoc.isValid()) {
1485 SourceRange RegionOfInterest(SLoc,
1486 CXXUnit->getPreprocessor().getLocForEndOfToken(SLoc, 1));
1487
1488 // FIXME: Would be great to have a "hint" cursor, then walk from that
1489 // hint cursor upward until we find a cursor whose source range encloses
1490 // the region of interest, rather than starting from the translation unit.
1491 CXCursor Parent = clang_getTranslationUnitCursor(CXXUnit);
1492 CursorVisitor CursorVis(CXXUnit, GetCursorVisitor, &Result,
1493 Decl::MaxPCHLevel, RegionOfInterest);
1494 CursorVis.VisitChildren(Parent);
Steve Naroff77128dd2009-09-15 20:25:34 +00001495 }
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001496 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00001497}
1498
Ted Kremenek73885552009-11-17 19:28:59 +00001499CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00001500 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00001501}
1502
1503unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00001504 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00001505}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001506
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001507unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00001508 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
1509}
1510
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001511unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +00001512 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
1513}
Steve Naroff2d4d6292009-08-31 14:26:51 +00001514
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001515unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00001516 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
1517}
1518
Douglas Gregor97b98722010-01-19 23:20:36 +00001519unsigned clang_isExpression(enum CXCursorKind K) {
1520 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
1521}
1522
1523unsigned clang_isStatement(enum CXCursorKind K) {
1524 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
1525}
1526
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001527unsigned clang_isTranslationUnit(enum CXCursorKind K) {
1528 return K == CXCursor_TranslationUnit;
1529}
1530
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001531CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00001532 return C.kind;
1533}
1534
Douglas Gregor98258af2010-01-18 22:46:11 +00001535CXSourceLocation clang_getCursorLocation(CXCursor C) {
1536 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00001537 switch (C.kind) {
1538 case CXCursor_ObjCSuperClassRef: {
1539 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1540 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001541 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001542 }
1543
1544 case CXCursor_ObjCProtocolRef: {
1545 std::pair<ObjCProtocolDecl *, SourceLocation> P
1546 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001547 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001548 }
1549
1550 case CXCursor_ObjCClassRef: {
1551 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1552 = getCursorObjCClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001553 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001554 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001555
1556 case CXCursor_TypeRef: {
1557 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001558 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001559 }
Douglas Gregorf46034a2010-01-18 23:41:10 +00001560
Douglas Gregorf46034a2010-01-18 23:41:10 +00001561 default:
1562 // FIXME: Need a way to enumerate all non-reference cases.
1563 llvm_unreachable("Missed a reference kind");
1564 }
Douglas Gregor98258af2010-01-18 22:46:11 +00001565 }
Douglas Gregor97b98722010-01-19 23:20:36 +00001566
1567 if (clang_isExpression(C.kind))
Ted Kremeneka297de22010-01-25 22:34:44 +00001568 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00001569 getLocationFromExpr(getCursorExpr(C)));
1570
Douglas Gregor5352ac02010-01-28 00:27:43 +00001571 if (!getCursorDecl(C))
1572 return clang_getNullLocation();
Douglas Gregor98258af2010-01-18 22:46:11 +00001573
Douglas Gregorf46034a2010-01-18 23:41:10 +00001574 Decl *D = getCursorDecl(C);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001575 SourceLocation Loc = D->getLocation();
1576 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
1577 Loc = Class->getClassLoc();
Ted Kremeneka297de22010-01-25 22:34:44 +00001578 return cxloc::translateSourceLocation(D->getASTContext(), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00001579}
Douglas Gregora7bde202010-01-19 00:34:46 +00001580
1581CXSourceRange clang_getCursorExtent(CXCursor C) {
1582 if (clang_isReference(C.kind)) {
1583 switch (C.kind) {
1584 case CXCursor_ObjCSuperClassRef: {
1585 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1586 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001587 return cxloc::translateSourceRange(P.first->getASTContext(), P.second);
Douglas Gregora7bde202010-01-19 00:34:46 +00001588 }
1589
1590 case CXCursor_ObjCProtocolRef: {
1591 std::pair<ObjCProtocolDecl *, SourceLocation> P
1592 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001593 return cxloc::translateSourceRange(P.first->getASTContext(), P.second);
Douglas Gregora7bde202010-01-19 00:34:46 +00001594 }
1595
1596 case CXCursor_ObjCClassRef: {
1597 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1598 = getCursorObjCClassRef(C);
1599
Ted Kremeneka297de22010-01-25 22:34:44 +00001600 return cxloc::translateSourceRange(P.first->getASTContext(), P.second);
Douglas Gregora7bde202010-01-19 00:34:46 +00001601 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001602
1603 case CXCursor_TypeRef: {
1604 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001605 return cxloc::translateSourceRange(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001606 }
Douglas Gregora7bde202010-01-19 00:34:46 +00001607
Douglas Gregora7bde202010-01-19 00:34:46 +00001608 default:
1609 // FIXME: Need a way to enumerate all non-reference cases.
1610 llvm_unreachable("Missed a reference kind");
1611 }
1612 }
Douglas Gregor97b98722010-01-19 23:20:36 +00001613
1614 if (clang_isExpression(C.kind))
Ted Kremeneka297de22010-01-25 22:34:44 +00001615 return cxloc::translateSourceRange(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00001616 getCursorExpr(C)->getSourceRange());
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001617
1618 if (clang_isStatement(C.kind))
Ted Kremeneka297de22010-01-25 22:34:44 +00001619 return cxloc::translateSourceRange(getCursorContext(C),
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001620 getCursorStmt(C)->getSourceRange());
Douglas Gregora7bde202010-01-19 00:34:46 +00001621
Douglas Gregor5352ac02010-01-28 00:27:43 +00001622 if (!getCursorDecl(C))
1623 return clang_getNullRange();
Douglas Gregora7bde202010-01-19 00:34:46 +00001624
1625 Decl *D = getCursorDecl(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001626 return cxloc::translateSourceRange(D->getASTContext(), D->getSourceRange());
Douglas Gregora7bde202010-01-19 00:34:46 +00001627}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001628
1629CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001630 if (clang_isInvalid(C.kind))
1631 return clang_getNullCursor();
1632
1633 ASTUnit *CXXUnit = getCursorASTUnit(C);
Douglas Gregorb6998662010-01-19 19:34:47 +00001634 if (clang_isDeclaration(C.kind))
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001635 return C;
Douglas Gregor98258af2010-01-18 22:46:11 +00001636
Douglas Gregor97b98722010-01-19 23:20:36 +00001637 if (clang_isExpression(C.kind)) {
1638 Decl *D = getDeclFromExpr(getCursorExpr(C));
1639 if (D)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001640 return MakeCXCursor(D, CXXUnit);
Douglas Gregor97b98722010-01-19 23:20:36 +00001641 return clang_getNullCursor();
1642 }
1643
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001644 if (!clang_isReference(C.kind))
1645 return clang_getNullCursor();
1646
1647 switch (C.kind) {
1648 case CXCursor_ObjCSuperClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001649 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, CXXUnit);
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001650
1651 case CXCursor_ObjCProtocolRef: {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001652 return MakeCXCursor(getCursorObjCProtocolRef(C).first, CXXUnit);
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001653
1654 case CXCursor_ObjCClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001655 return MakeCXCursor(getCursorObjCClassRef(C).first, CXXUnit);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001656
1657 case CXCursor_TypeRef:
1658 return MakeCXCursor(getCursorTypeRef(C).first, CXXUnit);
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001659
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001660 default:
1661 // We would prefer to enumerate all non-reference cursor kinds here.
1662 llvm_unreachable("Unhandled reference cursor kind");
1663 break;
1664 }
1665 }
1666
1667 return clang_getNullCursor();
1668}
1669
Douglas Gregorb6998662010-01-19 19:34:47 +00001670CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001671 if (clang_isInvalid(C.kind))
1672 return clang_getNullCursor();
1673
1674 ASTUnit *CXXUnit = getCursorASTUnit(C);
1675
Douglas Gregorb6998662010-01-19 19:34:47 +00001676 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00001677 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00001678 C = clang_getCursorReferenced(C);
1679 WasReference = true;
1680 }
1681
1682 if (!clang_isDeclaration(C.kind))
1683 return clang_getNullCursor();
1684
1685 Decl *D = getCursorDecl(C);
1686 if (!D)
1687 return clang_getNullCursor();
1688
1689 switch (D->getKind()) {
1690 // Declaration kinds that don't really separate the notions of
1691 // declaration and definition.
1692 case Decl::Namespace:
1693 case Decl::Typedef:
1694 case Decl::TemplateTypeParm:
1695 case Decl::EnumConstant:
1696 case Decl::Field:
1697 case Decl::ObjCIvar:
1698 case Decl::ObjCAtDefsField:
1699 case Decl::ImplicitParam:
1700 case Decl::ParmVar:
1701 case Decl::NonTypeTemplateParm:
1702 case Decl::TemplateTemplateParm:
1703 case Decl::ObjCCategoryImpl:
1704 case Decl::ObjCImplementation:
1705 case Decl::LinkageSpec:
1706 case Decl::ObjCPropertyImpl:
1707 case Decl::FileScopeAsm:
1708 case Decl::StaticAssert:
1709 case Decl::Block:
1710 return C;
1711
1712 // Declaration kinds that don't make any sense here, but are
1713 // nonetheless harmless.
1714 case Decl::TranslationUnit:
1715 case Decl::Template:
1716 case Decl::ObjCContainer:
1717 break;
1718
1719 // Declaration kinds for which the definition is not resolvable.
1720 case Decl::UnresolvedUsingTypename:
1721 case Decl::UnresolvedUsingValue:
1722 break;
1723
1724 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001725 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
1726 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001727
1728 case Decl::NamespaceAlias:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001729 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001730
1731 case Decl::Enum:
1732 case Decl::Record:
1733 case Decl::CXXRecord:
1734 case Decl::ClassTemplateSpecialization:
1735 case Decl::ClassTemplatePartialSpecialization:
Douglas Gregor952b0172010-02-11 01:04:33 +00001736 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001737 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001738 return clang_getNullCursor();
1739
1740 case Decl::Function:
1741 case Decl::CXXMethod:
1742 case Decl::CXXConstructor:
1743 case Decl::CXXDestructor:
1744 case Decl::CXXConversion: {
1745 const FunctionDecl *Def = 0;
1746 if (cast<FunctionDecl>(D)->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001747 return MakeCXCursor(const_cast<FunctionDecl *>(Def), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001748 return clang_getNullCursor();
1749 }
1750
1751 case Decl::Var: {
Sebastian Redl31310a22010-02-01 20:16:42 +00001752 // Ask the variable if it has a definition.
1753 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
1754 return MakeCXCursor(Def, CXXUnit);
1755 return clang_getNullCursor();
Douglas Gregorb6998662010-01-19 19:34:47 +00001756 }
1757
1758 case Decl::FunctionTemplate: {
1759 const FunctionDecl *Def = 0;
1760 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001761 return MakeCXCursor(Def->getDescribedFunctionTemplate(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001762 return clang_getNullCursor();
1763 }
1764
1765 case Decl::ClassTemplate: {
1766 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
Douglas Gregor952b0172010-02-11 01:04:33 +00001767 ->getDefinition())
Douglas Gregorb6998662010-01-19 19:34:47 +00001768 return MakeCXCursor(
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001769 cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
1770 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001771 return clang_getNullCursor();
1772 }
1773
1774 case Decl::Using: {
1775 UsingDecl *Using = cast<UsingDecl>(D);
1776 CXCursor Def = clang_getNullCursor();
1777 for (UsingDecl::shadow_iterator S = Using->shadow_begin(),
1778 SEnd = Using->shadow_end();
1779 S != SEnd; ++S) {
1780 if (Def != clang_getNullCursor()) {
1781 // FIXME: We have no way to return multiple results.
1782 return clang_getNullCursor();
1783 }
1784
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001785 Def = clang_getCursorDefinition(MakeCXCursor((*S)->getTargetDecl(),
1786 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00001787 }
1788
1789 return Def;
1790 }
1791
1792 case Decl::UsingShadow:
1793 return clang_getCursorDefinition(
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001794 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
1795 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00001796
1797 case Decl::ObjCMethod: {
1798 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
1799 if (Method->isThisDeclarationADefinition())
1800 return C;
1801
1802 // Dig out the method definition in the associated
1803 // @implementation, if we have it.
1804 // FIXME: The ASTs should make finding the definition easier.
1805 if (ObjCInterfaceDecl *Class
1806 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
1807 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
1808 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
1809 Method->isInstanceMethod()))
1810 if (Def->isThisDeclarationADefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001811 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001812
1813 return clang_getNullCursor();
1814 }
1815
1816 case Decl::ObjCCategory:
1817 if (ObjCCategoryImplDecl *Impl
1818 = cast<ObjCCategoryDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001819 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001820 return clang_getNullCursor();
1821
1822 case Decl::ObjCProtocol:
1823 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
1824 return C;
1825 return clang_getNullCursor();
1826
1827 case Decl::ObjCInterface:
1828 // There are two notions of a "definition" for an Objective-C
1829 // class: the interface and its implementation. When we resolved a
1830 // reference to an Objective-C class, produce the @interface as
1831 // the definition; when we were provided with the interface,
1832 // produce the @implementation as the definition.
1833 if (WasReference) {
1834 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
1835 return C;
1836 } else if (ObjCImplementationDecl *Impl
1837 = cast<ObjCInterfaceDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001838 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001839 return clang_getNullCursor();
1840
1841 case Decl::ObjCProperty:
1842 // FIXME: We don't really know where to find the
1843 // ObjCPropertyImplDecls that implement this property.
1844 return clang_getNullCursor();
1845
1846 case Decl::ObjCCompatibleAlias:
1847 if (ObjCInterfaceDecl *Class
1848 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
1849 if (!Class->isForwardDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001850 return MakeCXCursor(Class, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001851
1852 return clang_getNullCursor();
1853
1854 case Decl::ObjCForwardProtocol: {
1855 ObjCForwardProtocolDecl *Forward = cast<ObjCForwardProtocolDecl>(D);
1856 if (Forward->protocol_size() == 1)
1857 return clang_getCursorDefinition(
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001858 MakeCXCursor(*Forward->protocol_begin(),
1859 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00001860
1861 // FIXME: Cannot return multiple definitions.
1862 return clang_getNullCursor();
1863 }
1864
1865 case Decl::ObjCClass: {
1866 ObjCClassDecl *Class = cast<ObjCClassDecl>(D);
1867 if (Class->size() == 1) {
1868 ObjCInterfaceDecl *IFace = Class->begin()->getInterface();
1869 if (!IFace->isForwardDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001870 return MakeCXCursor(IFace, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001871 return clang_getNullCursor();
1872 }
1873
1874 // FIXME: Cannot return multiple definitions.
1875 return clang_getNullCursor();
1876 }
1877
1878 case Decl::Friend:
1879 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001880 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00001881 return clang_getNullCursor();
1882
1883 case Decl::FriendTemplate:
1884 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001885 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00001886 return clang_getNullCursor();
1887 }
1888
1889 return clang_getNullCursor();
1890}
1891
1892unsigned clang_isCursorDefinition(CXCursor C) {
1893 if (!clang_isDeclaration(C.kind))
1894 return 0;
1895
1896 return clang_getCursorDefinition(C) == C;
1897}
1898
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001899void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00001900 const char **startBuf,
1901 const char **endBuf,
1902 unsigned *startLine,
1903 unsigned *startColumn,
1904 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001905 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00001906 assert(getCursorDecl(C) && "CXCursor has null decl");
1907 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00001908 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
1909 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekfb480492010-01-13 21:46:36 +00001910
Steve Naroff4ade6d62009-09-23 17:52:52 +00001911 SourceManager &SM = FD->getASTContext().getSourceManager();
1912 *startBuf = SM.getCharacterData(Body->getLBracLoc());
1913 *endBuf = SM.getCharacterData(Body->getRBracLoc());
1914 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
1915 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
1916 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
1917 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
1918}
Ted Kremenekfb480492010-01-13 21:46:36 +00001919
1920} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00001921
Ted Kremenekfb480492010-01-13 21:46:36 +00001922//===----------------------------------------------------------------------===//
Douglas Gregorfc8ea232010-01-26 17:06:03 +00001923// Token-based Operations.
1924//===----------------------------------------------------------------------===//
1925
1926/* CXToken layout:
1927 * int_data[0]: a CXTokenKind
1928 * int_data[1]: starting token location
1929 * int_data[2]: token length
1930 * int_data[3]: reserved
1931 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
1932 * otherwise unused.
1933 */
1934extern "C" {
1935
1936CXTokenKind clang_getTokenKind(CXToken CXTok) {
1937 return static_cast<CXTokenKind>(CXTok.int_data[0]);
1938}
1939
1940CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
1941 switch (clang_getTokenKind(CXTok)) {
1942 case CXToken_Identifier:
1943 case CXToken_Keyword:
1944 // We know we have an IdentifierInfo*, so use that.
1945 return CIndexer::createCXString(
1946 static_cast<IdentifierInfo *>(CXTok.ptr_data)->getNameStart());
1947
1948 case CXToken_Literal: {
1949 // We have stashed the starting pointer in the ptr_data field. Use it.
1950 const char *Text = static_cast<const char *>(CXTok.ptr_data);
1951 return CIndexer::createCXString(llvm::StringRef(Text, CXTok.int_data[2]),
1952 true);
1953 }
1954
1955 case CXToken_Punctuation:
1956 case CXToken_Comment:
1957 break;
1958 }
1959
1960 // We have to find the starting buffer pointer the hard way, by
1961 // deconstructing the source location.
1962 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
1963 if (!CXXUnit)
1964 return CIndexer::createCXString("");
1965
1966 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
1967 std::pair<FileID, unsigned> LocInfo
1968 = CXXUnit->getSourceManager().getDecomposedLoc(Loc);
1969 std::pair<const char *,const char *> Buffer
1970 = CXXUnit->getSourceManager().getBufferData(LocInfo.first);
1971
1972 return CIndexer::createCXString(llvm::StringRef(Buffer.first+LocInfo.second,
1973 CXTok.int_data[2]),
1974 true);
1975}
1976
1977CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
1978 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
1979 if (!CXXUnit)
1980 return clang_getNullLocation();
1981
1982 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
1983 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
1984}
1985
1986CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
1987 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregor5352ac02010-01-28 00:27:43 +00001988 if (!CXXUnit)
1989 return clang_getNullRange();
Douglas Gregorfc8ea232010-01-26 17:06:03 +00001990
1991 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
1992 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
1993}
1994
1995void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
1996 CXToken **Tokens, unsigned *NumTokens) {
1997 if (Tokens)
1998 *Tokens = 0;
1999 if (NumTokens)
2000 *NumTokens = 0;
2001
2002 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2003 if (!CXXUnit || !Tokens || !NumTokens)
2004 return;
2005
2006 SourceRange R = cxloc::translateSourceRange(Range);
2007 if (R.isInvalid())
2008 return;
2009
2010 SourceManager &SourceMgr = CXXUnit->getSourceManager();
2011 std::pair<FileID, unsigned> BeginLocInfo
2012 = SourceMgr.getDecomposedLoc(R.getBegin());
2013 std::pair<FileID, unsigned> EndLocInfo
2014 = SourceMgr.getDecomposedLoc(R.getEnd());
2015
2016 // Cannot tokenize across files.
2017 if (BeginLocInfo.first != EndLocInfo.first)
2018 return;
2019
2020 // Create a lexer
2021 std::pair<const char *,const char *> Buffer
2022 = SourceMgr.getBufferData(BeginLocInfo.first);
2023 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
2024 CXXUnit->getASTContext().getLangOptions(),
2025 Buffer.first, Buffer.first + BeginLocInfo.second, Buffer.second);
2026 Lex.SetCommentRetentionState(true);
2027
2028 // Lex tokens until we hit the end of the range.
2029 const char *EffectiveBufferEnd = Buffer.first + EndLocInfo.second;
2030 llvm::SmallVector<CXToken, 32> CXTokens;
2031 Token Tok;
2032 do {
2033 // Lex the next token
2034 Lex.LexFromRawLexer(Tok);
2035 if (Tok.is(tok::eof))
2036 break;
2037
2038 // Initialize the CXToken.
2039 CXToken CXTok;
2040
2041 // - Common fields
2042 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
2043 CXTok.int_data[2] = Tok.getLength();
2044 CXTok.int_data[3] = 0;
2045
2046 // - Kind-specific fields
2047 if (Tok.isLiteral()) {
2048 CXTok.int_data[0] = CXToken_Literal;
2049 CXTok.ptr_data = (void *)Tok.getLiteralData();
2050 } else if (Tok.is(tok::identifier)) {
2051 // Lookup the identifier to determine whether we have a
2052 std::pair<FileID, unsigned> LocInfo
2053 = SourceMgr.getDecomposedLoc(Tok.getLocation());
2054 const char *StartPos
2055 = CXXUnit->getSourceManager().getBufferData(LocInfo.first).first +
2056 LocInfo.second;
2057 IdentifierInfo *II
2058 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok, StartPos);
2059 CXTok.int_data[0] = II->getTokenID() == tok::identifier?
2060 CXToken_Identifier
2061 : CXToken_Keyword;
2062 CXTok.ptr_data = II;
2063 } else if (Tok.is(tok::comment)) {
2064 CXTok.int_data[0] = CXToken_Comment;
2065 CXTok.ptr_data = 0;
2066 } else {
2067 CXTok.int_data[0] = CXToken_Punctuation;
2068 CXTok.ptr_data = 0;
2069 }
2070 CXTokens.push_back(CXTok);
2071 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
2072
2073 if (CXTokens.empty())
2074 return;
2075
2076 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
2077 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
2078 *NumTokens = CXTokens.size();
2079}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002080
2081typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
2082
2083enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
2084 CXCursor parent,
2085 CXClientData client_data) {
2086 AnnotateTokensData *Data = static_cast<AnnotateTokensData *>(client_data);
2087
2088 // We only annotate the locations of declarations, simple
2089 // references, and expressions which directly reference something.
2090 CXCursorKind Kind = clang_getCursorKind(cursor);
2091 if (clang_isDeclaration(Kind) || clang_isReference(Kind)) {
2092 // Okay: We can annotate the location of this declaration with the
2093 // declaration or reference
2094 } else if (clang_isExpression(cursor.kind)) {
2095 if (Kind != CXCursor_DeclRefExpr &&
2096 Kind != CXCursor_MemberRefExpr &&
2097 Kind != CXCursor_ObjCMessageExpr)
2098 return CXChildVisit_Recurse;
2099
2100 CXCursor Referenced = clang_getCursorReferenced(cursor);
2101 if (Referenced == cursor || Referenced == clang_getNullCursor())
2102 return CXChildVisit_Recurse;
2103
2104 // Okay: we can annotate the location of this expression
2105 } else {
2106 // Nothing to annotate
2107 return CXChildVisit_Recurse;
2108 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002109
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002110 CXSourceLocation Loc = clang_getCursorLocation(cursor);
2111 (*Data)[Loc.int_data] = cursor;
2112 return CXChildVisit_Recurse;
2113}
2114
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002115void clang_annotateTokens(CXTranslationUnit TU,
2116 CXToken *Tokens, unsigned NumTokens,
2117 CXCursor *Cursors) {
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002118 if (NumTokens == 0)
2119 return;
2120
2121 // Any token we don't specifically annotate will have a NULL cursor.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002122 for (unsigned I = 0; I != NumTokens; ++I)
2123 Cursors[I] = clang_getNullCursor();
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002124
2125 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2126 if (!CXXUnit || !Tokens)
2127 return;
2128
2129 // Annotate all of the source locations in the region of interest that map
2130 SourceRange RegionOfInterest;
2131 RegionOfInterest.setBegin(
2132 cxloc::translateSourceLocation(clang_getTokenLocation(TU, Tokens[0])));
2133 SourceLocation End
2134 = cxloc::translateSourceLocation(clang_getTokenLocation(TU,
2135 Tokens[NumTokens - 1]));
2136 RegionOfInterest.setEnd(CXXUnit->getPreprocessor().getLocForEndOfToken(End,
2137 1));
2138 // FIXME: Would be great to have a "hint" cursor, then walk from that
2139 // hint cursor upward until we find a cursor whose source range encloses
2140 // the region of interest, rather than starting from the translation unit.
2141 AnnotateTokensData Annotated;
2142 CXCursor Parent = clang_getTranslationUnitCursor(CXXUnit);
2143 CursorVisitor AnnotateVis(CXXUnit, AnnotateTokensVisitor, &Annotated,
2144 Decl::MaxPCHLevel, RegionOfInterest);
2145 AnnotateVis.VisitChildren(Parent);
2146
2147 for (unsigned I = 0; I != NumTokens; ++I) {
2148 // Determine whether we saw a cursor at this token's location.
2149 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
2150 if (Pos == Annotated.end())
2151 continue;
2152
2153 Cursors[I] = Pos->second;
2154 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002155}
2156
2157void clang_disposeTokens(CXTranslationUnit TU,
2158 CXToken *Tokens, unsigned NumTokens) {
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002159 free(Tokens);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002160}
2161
2162} // end: extern "C"
2163
2164//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00002165// CXString Operations.
2166//===----------------------------------------------------------------------===//
2167
2168extern "C" {
2169const char *clang_getCString(CXString string) {
2170 return string.Spelling;
2171}
2172
2173void clang_disposeString(CXString string) {
2174 if (string.MustFreeString && string.Spelling)
2175 free((void*)string.Spelling);
2176}
Ted Kremenek04bb7162010-01-22 22:44:15 +00002177
Ted Kremenekfb480492010-01-13 21:46:36 +00002178} // end: extern "C"
Ted Kremenek04bb7162010-01-22 22:44:15 +00002179
2180//===----------------------------------------------------------------------===//
2181// Misc. utility functions.
2182//===----------------------------------------------------------------------===//
2183
2184extern "C" {
2185
Ted Kremeneka2a9d6e2010-02-12 22:54:40 +00002186CXString clang_getClangVersion() {
2187 return CIndexer::createCXString(getClangFullVersion(), true);
Ted Kremenek04bb7162010-01-22 22:44:15 +00002188}
2189
2190} // end: extern "C"
2191