blob: bd897d9eb3cad671ff21ab9cf93b97dc7bffa5eb [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
Steve Naroff89922f82009-08-31 00:59:03 +0000241public:
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000242 CursorVisitor(ASTUnit *TU, CXCursorVisitor Visitor, CXClientData ClientData,
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000243 unsigned MaxPCHLevel,
244 SourceRange RegionOfInterest = SourceRange())
245 : TU(TU), Visitor(Visitor), ClientData(ClientData),
246 MaxPCHLevel(MaxPCHLevel), RegionOfInterest(RegionOfInterest)
Douglas Gregorb1373d02010-01-20 20:59:29 +0000247 {
248 Parent.kind = CXCursor_NoDeclFound;
249 Parent.data[0] = 0;
250 Parent.data[1] = 0;
251 Parent.data[2] = 0;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000252 StmtParent = 0;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000253 }
254
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000255 bool Visit(CXCursor Cursor, bool CheckedRegionOfInterest = false);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000256 bool VisitChildren(CXCursor Parent);
257
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000258 // Declaration visitors
Douglas Gregorb1373d02010-01-20 20:59:29 +0000259 bool VisitDeclContext(DeclContext *DC);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000260 bool VisitTranslationUnitDecl(TranslationUnitDecl *D);
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000261 bool VisitTypedefDecl(TypedefDecl *D);
262 bool VisitTagDecl(TagDecl *D);
263 bool VisitEnumConstantDecl(EnumConstantDecl *D);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000264 bool VisitDeclaratorDecl(DeclaratorDecl *DD);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000265 bool VisitFunctionDecl(FunctionDecl *ND);
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000266 bool VisitFieldDecl(FieldDecl *D);
267 bool VisitVarDecl(VarDecl *);
268 bool VisitObjCMethodDecl(ObjCMethodDecl *ND);
Douglas Gregora59e3902010-01-21 23:27:09 +0000269 bool VisitObjCContainerDecl(ObjCContainerDecl *D);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000270 bool VisitObjCCategoryDecl(ObjCCategoryDecl *ND);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000271 bool VisitObjCProtocolDecl(ObjCProtocolDecl *PID);
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000272 bool VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
273 bool VisitObjCImplDecl(ObjCImplDecl *D);
274 bool VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
275 bool VisitObjCImplementationDecl(ObjCImplementationDecl *D);
276 // FIXME: ObjCPropertyDecl requires TypeSourceInfo, getter/setter locations,
277 // etc.
278 // FIXME: ObjCCompatibleAliasDecl requires aliased-class locations.
279 bool VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D);
280 bool VisitObjCClassDecl(ObjCClassDecl *D);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000281
282 // Type visitors
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000283 // FIXME: QualifiedTypeLoc doesn't provide any location information
284 bool VisitBuiltinTypeLoc(BuiltinTypeLoc TL);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000285 bool VisitTypedefTypeLoc(TypedefTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000286 bool VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL);
287 bool VisitTagTypeLoc(TagTypeLoc TL);
288 // FIXME: TemplateTypeParmTypeLoc doesn't provide any location information
289 bool VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL);
290 bool VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL);
291 bool VisitPointerTypeLoc(PointerTypeLoc TL);
292 bool VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL);
293 bool VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL);
294 bool VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL);
295 bool VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL);
296 bool VisitFunctionTypeLoc(FunctionTypeLoc TL);
297 bool VisitArrayTypeLoc(ArrayTypeLoc TL);
Douglas Gregor2332c112010-01-21 20:48:56 +0000298 // FIXME: Implement for TemplateSpecializationTypeLoc
299 // FIXME: Implement visitors here when the unimplemented TypeLocs get
300 // implemented
301 bool VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL);
302 bool VisitTypeOfTypeLoc(TypeOfTypeLoc TL);
Douglas Gregora59e3902010-01-21 23:27:09 +0000303
304 // Statement visitors
305 bool VisitStmt(Stmt *S);
306 bool VisitDeclStmt(DeclStmt *S);
Douglas Gregorf5bab412010-01-22 01:00:11 +0000307 // FIXME: LabelStmt label?
308 bool VisitIfStmt(IfStmt *S);
309 bool VisitSwitchStmt(SwitchStmt *S);
Douglas Gregor263b47b2010-01-25 16:12:32 +0000310 bool VisitWhileStmt(WhileStmt *S);
311 bool VisitForStmt(ForStmt *S);
Douglas Gregor336fd812010-01-23 00:40:08 +0000312
313 // Expression visitors
314 bool VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E);
315 bool VisitExplicitCastExpr(ExplicitCastExpr *E);
316 bool VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
Steve Naroff89922f82009-08-31 00:59:03 +0000317};
Douglas Gregorb1373d02010-01-20 20:59:29 +0000318
Ted Kremenekab188932010-01-05 19:32:54 +0000319} // end anonymous namespace
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000320
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000321RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
322 assert(RegionOfInterest.isValid() && "RangeCompare called with invalid range");
323 if (R.isInvalid())
324 return RangeOverlap;
325
326 // Move the end of the input range to the end of the last token in that
327 // range.
Douglas Gregor2b37c9e2010-01-29 00:47:48 +0000328 SourceLocation NewEnd
329 = TU->getPreprocessor().getLocForEndOfToken(R.getEnd(), 1);
330 if (NewEnd.isValid())
331 R.setEnd(NewEnd);
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000332 return RangeCompare(TU->getSourceManager(), R, RegionOfInterest);
333}
334
Douglas Gregorb1373d02010-01-20 20:59:29 +0000335/// \brief Visit the given cursor and, if requested by the visitor,
336/// its children.
337///
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000338/// \param Cursor the cursor to visit.
339///
340/// \param CheckRegionOfInterest if true, then the caller already checked that
341/// this cursor is within the region of interest.
342///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000343/// \returns true if the visitation should be aborted, false if it
344/// should continue.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000345bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
Douglas Gregorb1373d02010-01-20 20:59:29 +0000346 if (clang_isInvalid(Cursor.kind))
347 return false;
348
349 if (clang_isDeclaration(Cursor.kind)) {
350 Decl *D = getCursorDecl(Cursor);
351 assert(D && "Invalid declaration cursor");
352 if (D->getPCHLevel() > MaxPCHLevel)
353 return false;
354
355 if (D->isImplicit())
356 return false;
357 }
358
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000359 // If we have a range of interest, and this cursor doesn't intersect with it,
360 // we're done.
361 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
Daniel Dunbarf408f322010-02-14 08:32:05 +0000362 SourceRange Range =
363 cxloc::translateCXSourceRange(clang_getCursorExtent(Cursor));
364 if (Range.isInvalid() || CompareRegionOfInterest(Range))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000365 return false;
366 }
367
Douglas Gregorb1373d02010-01-20 20:59:29 +0000368 switch (Visitor(Cursor, Parent, ClientData)) {
369 case CXChildVisit_Break:
370 return true;
371
372 case CXChildVisit_Continue:
373 return false;
374
375 case CXChildVisit_Recurse:
376 return VisitChildren(Cursor);
377 }
378
Douglas Gregorfd643772010-01-25 16:45:46 +0000379 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000380}
381
382/// \brief Visit the children of the given cursor.
383///
384/// \returns true if the visitation should be aborted, false if it
385/// should continue.
386bool CursorVisitor::VisitChildren(CXCursor Cursor) {
Douglas Gregora59e3902010-01-21 23:27:09 +0000387 if (clang_isReference(Cursor.kind)) {
388 // By definition, references have no children.
389 return false;
390 }
391
Douglas Gregorb1373d02010-01-20 20:59:29 +0000392 // Set the Parent field to Cursor, then back to its old value once we're
393 // done.
394 class SetParentRAII {
395 CXCursor &Parent;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000396 Decl *&StmtParent;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000397 CXCursor OldParent;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000398
Douglas Gregorb1373d02010-01-20 20:59:29 +0000399 public:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000400 SetParentRAII(CXCursor &Parent, Decl *&StmtParent, CXCursor NewParent)
401 : Parent(Parent), StmtParent(StmtParent), OldParent(Parent)
Douglas Gregorb1373d02010-01-20 20:59:29 +0000402 {
403 Parent = NewParent;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000404 if (clang_isDeclaration(Parent.kind))
405 StmtParent = getCursorDecl(Parent);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000406 }
407
408 ~SetParentRAII() {
409 Parent = OldParent;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000410 if (clang_isDeclaration(Parent.kind))
411 StmtParent = getCursorDecl(Parent);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000412 }
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000413 } SetParent(Parent, StmtParent, Cursor);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000414
415 if (clang_isDeclaration(Cursor.kind)) {
416 Decl *D = getCursorDecl(Cursor);
417 assert(D && "Invalid declaration cursor");
418 return Visit(D);
419 }
420
Douglas Gregora59e3902010-01-21 23:27:09 +0000421 if (clang_isStatement(Cursor.kind))
422 return Visit(getCursorStmt(Cursor));
423 if (clang_isExpression(Cursor.kind))
424 return Visit(getCursorExpr(Cursor));
425
Douglas Gregorb1373d02010-01-20 20:59:29 +0000426 if (clang_isTranslationUnit(Cursor.kind)) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000427 ASTUnit *CXXUnit = getCursorASTUnit(Cursor);
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000428 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
429 RegionOfInterest.isInvalid()) {
Douglas Gregor7b691f332010-01-20 21:13:59 +0000430 const std::vector<Decl*> &TLDs = CXXUnit->getTopLevelDecls();
431 for (std::vector<Decl*>::const_iterator it = TLDs.begin(),
432 ie = TLDs.end(); it != ie; ++it) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000433 if (Visit(MakeCXCursor(*it, CXXUnit), true))
Douglas Gregor7b691f332010-01-20 21:13:59 +0000434 return true;
435 }
436 } else {
437 return VisitDeclContext(
Douglas Gregorb1373d02010-01-20 20:59:29 +0000438 CXXUnit->getASTContext().getTranslationUnitDecl());
Douglas Gregor7b691f332010-01-20 21:13:59 +0000439 }
440
441 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000442 }
Douglas Gregora59e3902010-01-21 23:27:09 +0000443
Douglas Gregorb1373d02010-01-20 20:59:29 +0000444 // Nothing to visit at the moment.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000445 return false;
446}
447
Douglas Gregorb1373d02010-01-20 20:59:29 +0000448bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000449 for (DeclContext::decl_iterator
Douglas Gregorb1373d02010-01-20 20:59:29 +0000450 I = DC->decls_begin(), E = DC->decls_end(); I != E; ++I) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000451 if (RegionOfInterest.isValid()) {
452 SourceRange R = (*I)->getSourceRange();
453 if (R.isInvalid())
454 continue;
455
456 switch (CompareRegionOfInterest(R)) {
457 case RangeBefore:
458 // This declaration comes before the region of interest; skip it.
459 continue;
460
461 case RangeAfter:
462 // This declaration comes after the region of interest; we're done.
463 return false;
464
465 case RangeOverlap:
466 // This declaration overlaps the region of interest; visit it.
467 break;
468 }
469 }
470
471 if (Visit(MakeCXCursor(*I, TU), true))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000472 return true;
473 }
474
475 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000476}
477
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000478bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
479 llvm_unreachable("Translation units are visited directly by Visit()");
480 return false;
481}
482
483bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
484 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
485 return Visit(TSInfo->getTypeLoc());
486
487 return false;
488}
489
490bool CursorVisitor::VisitTagDecl(TagDecl *D) {
491 return VisitDeclContext(D);
492}
493
494bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
495 if (Expr *Init = D->getInitExpr())
496 return Visit(MakeCXCursor(Init, StmtParent, TU));
497 return false;
498}
499
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000500bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
501 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
502 if (Visit(TSInfo->getTypeLoc()))
503 return true;
504
505 return false;
506}
507
Douglas Gregorb1373d02010-01-20 20:59:29 +0000508bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000509 if (VisitDeclaratorDecl(ND))
510 return true;
511
Douglas Gregora59e3902010-01-21 23:27:09 +0000512 if (ND->isThisDeclarationADefinition() &&
513 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
514 return true;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000515
516 return false;
517}
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000518
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000519bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
520 if (VisitDeclaratorDecl(D))
521 return true;
522
523 if (Expr *BitWidth = D->getBitWidth())
524 return Visit(MakeCXCursor(BitWidth, StmtParent, TU));
525
526 return false;
527}
528
529bool CursorVisitor::VisitVarDecl(VarDecl *D) {
530 if (VisitDeclaratorDecl(D))
531 return true;
532
533 if (Expr *Init = D->getInit())
534 return Visit(MakeCXCursor(Init, StmtParent, TU));
535
536 return false;
537}
538
539bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
540 // FIXME: We really need a TypeLoc covering Objective-C method declarations.
541 // At the moment, we don't have information about locations in the return
542 // type.
543 for (ObjCMethodDecl::param_iterator P = ND->param_begin(),
544 PEnd = ND->param_end();
545 P != PEnd; ++P) {
546 if (Visit(MakeCXCursor(*P, TU)))
547 return true;
548 }
549
550 if (ND->isThisDeclarationADefinition() &&
551 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
552 return true;
553
554 return false;
555}
556
Douglas Gregora59e3902010-01-21 23:27:09 +0000557bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
558 return VisitDeclContext(D);
559}
560
Douglas Gregorb1373d02010-01-20 20:59:29 +0000561bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000562 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
563 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000564 return true;
565
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000566 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
567 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
568 E = ND->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000569 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000570 return true;
571
Douglas Gregora59e3902010-01-21 23:27:09 +0000572 return VisitObjCContainerDecl(ND);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000573}
574
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000575bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
576 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
577 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
578 E = PID->protocol_end(); I != E; ++I, ++PL)
579 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
580 return true;
581
582 return VisitObjCContainerDecl(PID);
583}
584
Douglas Gregorb1373d02010-01-20 20:59:29 +0000585bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000586 // Issue callbacks for super class.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000587 if (D->getSuperClass() &&
588 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000589 D->getSuperClassLoc(),
590 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000591 return true;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000592
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000593 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
594 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
595 E = D->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000596 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000597 return true;
598
Douglas Gregora59e3902010-01-21 23:27:09 +0000599 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000600}
601
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000602bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
603 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000604}
605
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000606bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
607 if (Visit(MakeCursorObjCClassRef(D->getCategoryDecl()->getClassInterface(),
608 D->getLocation(), TU)))
609 return true;
610
611 return VisitObjCImplDecl(D);
612}
613
614bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
615#if 0
616 // Issue callbacks for super class.
617 // FIXME: No source location information!
618 if (D->getSuperClass() &&
619 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
620 D->getSuperClassLoc(),
621 TU)))
622 return true;
623#endif
624
625 return VisitObjCImplDecl(D);
626}
627
628bool CursorVisitor::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D) {
629 ObjCForwardProtocolDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
630 for (ObjCForwardProtocolDecl::protocol_iterator I = D->protocol_begin(),
631 E = D->protocol_end();
632 I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000633 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000634 return true;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000635
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000636 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000637}
638
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000639bool CursorVisitor::VisitObjCClassDecl(ObjCClassDecl *D) {
640 for (ObjCClassDecl::iterator C = D->begin(), CEnd = D->end(); C != CEnd; ++C)
641 if (Visit(MakeCursorObjCClassRef(C->getInterface(), C->getLocation(), TU)))
642 return true;
643
644 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000645}
646
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000647bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
648 ASTContext &Context = TU->getASTContext();
649
650 // Some builtin types (such as Objective-C's "id", "sel", and
651 // "Class") have associated declarations. Create cursors for those.
652 QualType VisitType;
653 switch (TL.getType()->getAs<BuiltinType>()->getKind()) {
654 case BuiltinType::Void:
655 case BuiltinType::Bool:
656 case BuiltinType::Char_U:
657 case BuiltinType::UChar:
658 case BuiltinType::Char16:
659 case BuiltinType::Char32:
660 case BuiltinType::UShort:
661 case BuiltinType::UInt:
662 case BuiltinType::ULong:
663 case BuiltinType::ULongLong:
664 case BuiltinType::UInt128:
665 case BuiltinType::Char_S:
666 case BuiltinType::SChar:
667 case BuiltinType::WChar:
668 case BuiltinType::Short:
669 case BuiltinType::Int:
670 case BuiltinType::Long:
671 case BuiltinType::LongLong:
672 case BuiltinType::Int128:
673 case BuiltinType::Float:
674 case BuiltinType::Double:
675 case BuiltinType::LongDouble:
676 case BuiltinType::NullPtr:
677 case BuiltinType::Overload:
678 case BuiltinType::Dependent:
679 break;
680
681 case BuiltinType::UndeducedAuto: // FIXME: Deserves a cursor?
682 break;
683
684 case BuiltinType::ObjCId:
685 VisitType = Context.getObjCIdType();
686 break;
687
688 case BuiltinType::ObjCClass:
689 VisitType = Context.getObjCClassType();
690 break;
691
692 case BuiltinType::ObjCSel:
693 VisitType = Context.getObjCSelType();
694 break;
695 }
696
697 if (!VisitType.isNull()) {
698 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
699 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
700 TU));
701 }
702
703 return false;
704}
705
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000706bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
707 return Visit(MakeCursorTypeRef(TL.getTypedefDecl(), TL.getNameLoc(), TU));
708}
709
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000710bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
711 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
712}
713
714bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
715 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
716}
717
718bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
719 if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
720 return true;
721
722 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
723 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
724 TU)))
725 return true;
726 }
727
728 return false;
729}
730
731bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
732 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseTypeLoc()))
733 return true;
734
735 if (TL.hasProtocolsAsWritten()) {
736 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
737 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I),
738 TL.getProtocolLoc(I),
739 TU)))
740 return true;
741 }
742 }
743
744 return false;
745}
746
747bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
748 return Visit(TL.getPointeeLoc());
749}
750
751bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
752 return Visit(TL.getPointeeLoc());
753}
754
755bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
756 return Visit(TL.getPointeeLoc());
757}
758
759bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
760 return Visit(TL.getPointeeLoc());
761}
762
763bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
764 return Visit(TL.getPointeeLoc());
765}
766
767bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
768 if (Visit(TL.getResultLoc()))
769 return true;
770
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000771 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
772 if (Visit(MakeCXCursor(TL.getArg(I), TU)))
773 return true;
774
775 return false;
776}
777
778bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
779 if (Visit(TL.getElementLoc()))
780 return true;
781
782 if (Expr *Size = TL.getSizeExpr())
783 return Visit(MakeCXCursor(Size, StmtParent, TU));
784
785 return false;
786}
787
Douglas Gregor2332c112010-01-21 20:48:56 +0000788bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
789 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
790}
791
792bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
793 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
794 return Visit(TSInfo->getTypeLoc());
795
796 return false;
797}
798
Douglas Gregora59e3902010-01-21 23:27:09 +0000799bool CursorVisitor::VisitStmt(Stmt *S) {
800 for (Stmt::child_iterator Child = S->child_begin(), ChildEnd = S->child_end();
801 Child != ChildEnd; ++Child) {
Daniel Dunbar54d67ca2010-01-25 00:40:30 +0000802 if (*Child && Visit(MakeCXCursor(*Child, StmtParent, TU)))
Douglas Gregora59e3902010-01-21 23:27:09 +0000803 return true;
804 }
805
806 return false;
807}
808
809bool CursorVisitor::VisitDeclStmt(DeclStmt *S) {
810 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
811 D != DEnd; ++D) {
Douglas Gregor263b47b2010-01-25 16:12:32 +0000812 if (*D && Visit(MakeCXCursor(*D, TU)))
Douglas Gregora59e3902010-01-21 23:27:09 +0000813 return true;
814 }
815
816 return false;
817}
818
Douglas Gregorf5bab412010-01-22 01:00:11 +0000819bool CursorVisitor::VisitIfStmt(IfStmt *S) {
820 if (VarDecl *Var = S->getConditionVariable()) {
821 if (Visit(MakeCXCursor(Var, TU)))
822 return true;
Douglas Gregor263b47b2010-01-25 16:12:32 +0000823 }
Douglas Gregorf5bab412010-01-22 01:00:11 +0000824
Douglas Gregor263b47b2010-01-25 16:12:32 +0000825 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
826 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +0000827 if (S->getThen() && Visit(MakeCXCursor(S->getThen(), StmtParent, TU)))
828 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +0000829 if (S->getElse() && Visit(MakeCXCursor(S->getElse(), StmtParent, TU)))
830 return true;
831
832 return false;
833}
834
835bool CursorVisitor::VisitSwitchStmt(SwitchStmt *S) {
836 if (VarDecl *Var = S->getConditionVariable()) {
837 if (Visit(MakeCXCursor(Var, TU)))
838 return true;
Douglas Gregor263b47b2010-01-25 16:12:32 +0000839 }
840
841 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
842 return true;
843 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
844 return true;
845
846 return false;
847}
848
849bool CursorVisitor::VisitWhileStmt(WhileStmt *S) {
850 if (VarDecl *Var = S->getConditionVariable()) {
851 if (Visit(MakeCXCursor(Var, TU)))
852 return true;
853 }
854
855 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
856 return true;
857 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
Douglas Gregorf5bab412010-01-22 01:00:11 +0000858 return true;
859
Douglas Gregor263b47b2010-01-25 16:12:32 +0000860 return false;
861}
862
863bool CursorVisitor::VisitForStmt(ForStmt *S) {
864 if (S->getInit() && Visit(MakeCXCursor(S->getInit(), StmtParent, TU)))
865 return true;
866 if (VarDecl *Var = S->getConditionVariable()) {
867 if (Visit(MakeCXCursor(Var, TU)))
868 return true;
869 }
870
871 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
872 return true;
873 if (S->getInc() && Visit(MakeCXCursor(S->getInc(), StmtParent, TU)))
874 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +0000875 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
876 return true;
877
878 return false;
879}
880
Douglas Gregor336fd812010-01-23 00:40:08 +0000881bool CursorVisitor::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E) {
882 if (E->isArgumentType()) {
883 if (TypeSourceInfo *TSInfo = E->getArgumentTypeInfo())
884 return Visit(TSInfo->getTypeLoc());
885
886 return false;
887 }
888
889 return VisitExpr(E);
890}
891
892bool CursorVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
893 if (TypeSourceInfo *TSInfo = E->getTypeInfoAsWritten())
894 if (Visit(TSInfo->getTypeLoc()))
895 return true;
896
897 return VisitCastExpr(E);
898}
899
900bool CursorVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
901 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
902 if (Visit(TSInfo->getTypeLoc()))
903 return true;
904
905 return VisitExpr(E);
906}
907
Daniel Dunbar140fce22010-01-12 02:34:07 +0000908CXString CIndexer::createCXString(const char *String, bool DupString){
Benjamin Kramer62cf3222009-11-09 19:13:48 +0000909 CXString Str;
910 if (DupString) {
911 Str.Spelling = strdup(String);
912 Str.MustFreeString = 1;
913 } else {
914 Str.Spelling = String;
915 Str.MustFreeString = 0;
916 }
917 return Str;
918}
919
Douglas Gregorfc8ea232010-01-26 17:06:03 +0000920CXString CIndexer::createCXString(llvm::StringRef String, bool DupString) {
921 CXString Result;
922 if (DupString || (!String.empty() && String.data()[String.size()] != 0)) {
923 char *Spelling = (char *)malloc(String.size() + 1);
924 memmove(Spelling, String.data(), String.size());
925 Spelling[String.size()] = 0;
926 Result.Spelling = Spelling;
927 Result.MustFreeString = 1;
928 } else {
929 Result.Spelling = String.data();
930 Result.MustFreeString = 0;
931 }
932 return Result;
933}
934
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000935extern "C" {
Douglas Gregor936ea3b2010-01-28 00:56:43 +0000936CXIndex clang_createIndex(int excludeDeclarationsFromPCH) {
Douglas Gregora030b7c2010-01-22 20:35:53 +0000937 CIndexer *CIdxr = new CIndexer();
Steve Naroffe56b4ba2009-10-20 14:46:24 +0000938 if (excludeDeclarationsFromPCH)
939 CIdxr->setOnlyLocalDecls();
Steve Naroffe56b4ba2009-10-20 14:46:24 +0000940 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +0000941}
942
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000943void clang_disposeIndex(CXIndex CIdx) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +0000944 if (CIdx)
945 delete static_cast<CIndexer *>(CIdx);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +0000946}
947
Daniel Dunbar8506dde2009-12-03 01:54:28 +0000948void clang_setUseExternalASTGeneration(CXIndex CIdx, int value) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +0000949 if (CIdx) {
950 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
951 CXXIdx->setUseExternalASTGeneration(value);
952 }
Daniel Dunbar8506dde2009-12-03 01:54:28 +0000953}
954
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000955CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
Douglas Gregor5352ac02010-01-28 00:27:43 +0000956 const char *ast_filename,
957 CXDiagnosticCallback diag_callback,
958 CXClientData diag_client_data) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +0000959 if (!CIdx)
960 return 0;
961
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000962 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000963
Douglas Gregor5352ac02010-01-28 00:27:43 +0000964 // Configure the diagnostics.
965 DiagnosticOptions DiagOpts;
966 llvm::OwningPtr<Diagnostic> Diags;
967 Diags.reset(CompilerInstance::createDiagnostics(DiagOpts, 0, 0));
968 CIndexDiagnosticClient DiagClient(diag_callback, diag_client_data);
969 Diags->setClient(&DiagClient);
970
971 return ASTUnit::LoadFromPCHFile(ast_filename, *Diags,
Daniel Dunbar5262fda2009-12-03 01:45:44 +0000972 CXXIdx->getOnlyLocalDecls(),
973 /* UseBumpAllocator = */ true);
Steve Naroff600866c2009-08-27 19:51:58 +0000974}
975
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000976CXTranslationUnit
977clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
978 const char *source_filename,
979 int num_command_line_args,
Douglas Gregor4db64a42010-01-23 00:14:00 +0000980 const char **command_line_args,
981 unsigned num_unsaved_files,
Douglas Gregor5352ac02010-01-28 00:27:43 +0000982 struct CXUnsavedFile *unsaved_files,
983 CXDiagnosticCallback diag_callback,
984 CXClientData diag_client_data) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +0000985 if (!CIdx)
986 return 0;
987
Steve Naroffe56b4ba2009-10-20 14:46:24 +0000988 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
989
Douglas Gregor5352ac02010-01-28 00:27:43 +0000990 // Configure the diagnostics.
991 DiagnosticOptions DiagOpts;
992 llvm::OwningPtr<Diagnostic> Diags;
993 Diags.reset(CompilerInstance::createDiagnostics(DiagOpts, 0, 0));
994 CIndexDiagnosticClient DiagClient(diag_callback, diag_client_data);
995 Diags->setClient(&DiagClient);
996
Douglas Gregor4db64a42010-01-23 00:14:00 +0000997 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
998 for (unsigned I = 0; I != num_unsaved_files; ++I) {
999 const llvm::MemoryBuffer *Buffer
1000 = llvm::MemoryBuffer::getMemBuffer(unsaved_files[I].Contents,
1001 unsaved_files[I].Contents + unsaved_files[I].Length,
1002 unsaved_files[I].Filename);
1003 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
1004 Buffer));
1005 }
1006
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001007 if (!CXXIdx->getUseExternalASTGeneration()) {
1008 llvm::SmallVector<const char *, 16> Args;
1009
1010 // The 'source_filename' argument is optional. If the caller does not
1011 // specify it then it is assumed that the source file is specified
1012 // in the actual argument list.
1013 if (source_filename)
1014 Args.push_back(source_filename);
1015 Args.insert(Args.end(), command_line_args,
1016 command_line_args + num_command_line_args);
1017
Douglas Gregor5352ac02010-01-28 00:27:43 +00001018 unsigned NumErrors = Diags->getNumErrors();
Ted Kremenek8a8da7d2010-01-06 03:42:32 +00001019
Ted Kremenek29b72842010-01-07 22:49:05 +00001020#ifdef USE_CRASHTRACER
1021 ArgsCrashTracerInfo ACTI(Args);
Ted Kremenek8a8da7d2010-01-06 03:42:32 +00001022#endif
1023
Daniel Dunbar94220972009-12-05 02:17:18 +00001024 llvm::OwningPtr<ASTUnit> Unit(
1025 ASTUnit::LoadFromCommandLine(Args.data(), Args.data() + Args.size(),
Douglas Gregor5352ac02010-01-28 00:27:43 +00001026 *Diags,
Daniel Dunbar869824e2009-12-13 03:46:13 +00001027 CXXIdx->getClangResourcesPath(),
Daniel Dunbar94220972009-12-05 02:17:18 +00001028 CXXIdx->getOnlyLocalDecls(),
Douglas Gregor4db64a42010-01-23 00:14:00 +00001029 /* UseBumpAllocator = */ true,
1030 RemappedFiles.data(),
1031 RemappedFiles.size()));
Ted Kremenek29b72842010-01-07 22:49:05 +00001032
Daniel Dunbar94220972009-12-05 02:17:18 +00001033 // FIXME: Until we have broader testing, just drop the entire AST if we
1034 // encountered an error.
Douglas Gregor5352ac02010-01-28 00:27:43 +00001035 if (NumErrors != Diags->getNumErrors())
Daniel Dunbar94220972009-12-05 02:17:18 +00001036 return 0;
1037
1038 return Unit.take();
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001039 }
1040
Ted Kremenek139ba862009-10-22 00:03:57 +00001041 // Build up the arguments for invoking 'clang'.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001042 std::vector<const char *> argv;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001043
Ted Kremenek139ba862009-10-22 00:03:57 +00001044 // First add the complete path to the 'clang' executable.
1045 llvm::sys::Path ClangPath = static_cast<CIndexer *>(CIdx)->getClangPath();
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00001046 argv.push_back(ClangPath.c_str());
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001047
Ted Kremenek139ba862009-10-22 00:03:57 +00001048 // Add the '-emit-ast' option as our execution mode for 'clang'.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001049 argv.push_back("-emit-ast");
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001050
Ted Kremenek139ba862009-10-22 00:03:57 +00001051 // The 'source_filename' argument is optional. If the caller does not
1052 // specify it then it is assumed that the source file is specified
1053 // in the actual argument list.
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001054 if (source_filename)
1055 argv.push_back(source_filename);
Ted Kremenek139ba862009-10-22 00:03:57 +00001056
Steve Naroff37b5ac22009-10-15 20:50:09 +00001057 // Generate a temporary name for the AST file.
Ted Kremenek139ba862009-10-22 00:03:57 +00001058 argv.push_back("-o");
Steve Naroff37b5ac22009-10-15 20:50:09 +00001059 char astTmpFile[L_tmpnam];
Ted Kremenek74cd0692009-10-15 23:21:22 +00001060 argv.push_back(tmpnam(astTmpFile));
Ted Kremenek139ba862009-10-22 00:03:57 +00001061
Douglas Gregor4db64a42010-01-23 00:14:00 +00001062 // Remap any unsaved files to temporary files.
1063 std::vector<llvm::sys::Path> TemporaryFiles;
1064 std::vector<std::string> RemapArgs;
1065 if (RemapFiles(num_unsaved_files, unsaved_files, RemapArgs, TemporaryFiles))
1066 return 0;
1067
1068 // The pointers into the elements of RemapArgs are stable because we
1069 // won't be adding anything to RemapArgs after this point.
1070 for (unsigned i = 0, e = RemapArgs.size(); i != e; ++i)
1071 argv.push_back(RemapArgs[i].c_str());
1072
Ted Kremenek139ba862009-10-22 00:03:57 +00001073 // Process the compiler options, stripping off '-o', '-c', '-fsyntax-only'.
1074 for (int i = 0; i < num_command_line_args; ++i)
1075 if (const char *arg = command_line_args[i]) {
1076 if (strcmp(arg, "-o") == 0) {
1077 ++i; // Also skip the matching argument.
1078 continue;
1079 }
1080 if (strcmp(arg, "-emit-ast") == 0 ||
1081 strcmp(arg, "-c") == 0 ||
1082 strcmp(arg, "-fsyntax-only") == 0) {
1083 continue;
1084 }
1085
1086 // Keep the argument.
1087 argv.push_back(arg);
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001088 }
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001089
Douglas Gregord93256e2010-01-28 06:00:51 +00001090 // Generate a temporary name for the diagnostics file.
1091 char tmpFileResults[L_tmpnam];
1092 char *tmpResultsFileName = tmpnam(tmpFileResults);
1093 llvm::sys::Path DiagnosticsFile(tmpResultsFileName);
1094 TemporaryFiles.push_back(DiagnosticsFile);
1095 argv.push_back("-fdiagnostics-binary");
1096
Ted Kremenek139ba862009-10-22 00:03:57 +00001097 // Add the null terminator.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001098 argv.push_back(NULL);
1099
Ted Kremenekfeb15e32009-10-26 22:14:08 +00001100 // Invoke 'clang'.
1101 llvm::sys::Path DevNull; // leave empty, causes redirection to /dev/null
1102 // on Unix or NUL (Windows).
Ted Kremenek379afec2009-10-22 03:24:01 +00001103 std::string ErrMsg;
Douglas Gregord93256e2010-01-28 06:00:51 +00001104 const llvm::sys::Path *Redirects[] = { &DevNull, &DevNull, &DiagnosticsFile,
1105 NULL };
Ted Kremenek379afec2009-10-22 03:24:01 +00001106 llvm::sys::Program::ExecuteAndWait(ClangPath, &argv[0], /* env */ NULL,
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001107 /* redirects */ &Redirects[0],
Ted Kremenek379afec2009-10-22 03:24:01 +00001108 /* secondsToWait */ 0, /* memoryLimits */ 0, &ErrMsg);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001109
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001110 if (!ErrMsg.empty()) {
1111 std::string AllArgs;
Ted Kremenek379afec2009-10-22 03:24:01 +00001112 for (std::vector<const char*>::iterator I = argv.begin(), E = argv.end();
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001113 I != E; ++I) {
1114 AllArgs += ' ';
Ted Kremenek779e5f42009-10-26 22:08:39 +00001115 if (*I)
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001116 AllArgs += *I;
Ted Kremenek779e5f42009-10-26 22:08:39 +00001117 }
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001118
1119 Diags->Report(diag::err_fe_clang) << AllArgs << ErrMsg;
Ted Kremenek379afec2009-10-22 03:24:01 +00001120 }
Benjamin Kramer0829a832009-10-18 11:19:36 +00001121
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001122 // FIXME: Parse the (redirected) standard error to emit diagnostics.
1123
Douglas Gregor5352ac02010-01-28 00:27:43 +00001124 ASTUnit *ATU = ASTUnit::LoadFromPCHFile(astTmpFile, *Diags,
Douglas Gregor4db64a42010-01-23 00:14:00 +00001125 CXXIdx->getOnlyLocalDecls(),
1126 /* UseBumpAllocator = */ true,
1127 RemappedFiles.data(),
1128 RemappedFiles.size());
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001129 if (ATU)
1130 ATU->unlinkTemporaryFile();
Douglas Gregor4db64a42010-01-23 00:14:00 +00001131
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00001132 // FIXME: Currently we don't report diagnostics on invalid ASTs.
1133 if (ATU)
1134 ReportSerializedDiagnostics(DiagnosticsFile, *Diags,
1135 num_unsaved_files, unsaved_files,
1136 ATU->getASTContext().getLangOptions());
Douglas Gregord93256e2010-01-28 06:00:51 +00001137
Douglas Gregor4db64a42010-01-23 00:14:00 +00001138 for (unsigned i = 0, e = TemporaryFiles.size(); i != e; ++i)
1139 TemporaryFiles[i].eraseFromDisk();
1140
Steve Naroffe19944c2009-10-15 22:23:48 +00001141 return ATU;
Steve Naroff5b7d8e22009-10-15 20:04:39 +00001142}
1143
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001144void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001145 if (CTUnit)
1146 delete static_cast<ASTUnit *>(CTUnit);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00001147}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001148
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001149CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001150 if (!CTUnit)
1151 return CIndexer::createCXString("");
1152
Steve Naroff77accc12009-09-03 18:19:54 +00001153 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit);
Ted Kremenek4b333d22010-01-12 00:36:38 +00001154 return CIndexer::createCXString(CXXUnit->getOriginalSourceFileName().c_str(),
1155 true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +00001156}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +00001157
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001158CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001159 CXCursor Result = { CXCursor_TranslationUnit, { 0, 0, TU } };
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001160 return Result;
1161}
1162
Ted Kremenekfb480492010-01-13 21:46:36 +00001163} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +00001164
Ted Kremenekfb480492010-01-13 21:46:36 +00001165//===----------------------------------------------------------------------===//
Douglas Gregor1db19de2010-01-19 21:36:55 +00001166// CXSourceLocation and CXSourceRange Operations.
1167//===----------------------------------------------------------------------===//
1168
Douglas Gregorb9790342010-01-22 21:44:22 +00001169extern "C" {
1170CXSourceLocation clang_getNullLocation() {
Douglas Gregor5352ac02010-01-28 00:27:43 +00001171 CXSourceLocation Result = { { 0, 0 }, 0 };
Douglas Gregorb9790342010-01-22 21:44:22 +00001172 return Result;
1173}
1174
1175unsigned clang_equalLocations(CXSourceLocation loc1, CXSourceLocation loc2) {
Daniel Dunbar90a6b9e2010-01-30 23:58:27 +00001176 return (loc1.ptr_data[0] == loc2.ptr_data[0] &&
1177 loc1.ptr_data[1] == loc2.ptr_data[1] &&
1178 loc1.int_data == loc2.int_data);
Douglas Gregorb9790342010-01-22 21:44:22 +00001179}
1180
1181CXSourceLocation clang_getLocation(CXTranslationUnit tu,
1182 CXFile file,
1183 unsigned line,
1184 unsigned column) {
1185 if (!tu)
1186 return clang_getNullLocation();
1187
1188 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
1189 SourceLocation SLoc
1190 = CXXUnit->getSourceManager().getLocation(
1191 static_cast<const FileEntry *>(file),
1192 line, column);
1193
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00001194 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
Douglas Gregorb9790342010-01-22 21:44:22 +00001195}
1196
Douglas Gregor5352ac02010-01-28 00:27:43 +00001197CXSourceRange clang_getNullRange() {
1198 CXSourceRange Result = { { 0, 0 }, 0, 0 };
1199 return Result;
1200}
Douglas Gregorb9790342010-01-22 21:44:22 +00001201
Douglas Gregor5352ac02010-01-28 00:27:43 +00001202CXSourceRange clang_getRange(CXSourceLocation begin, CXSourceLocation end) {
1203 if (begin.ptr_data[0] != end.ptr_data[0] ||
1204 begin.ptr_data[1] != end.ptr_data[1])
1205 return clang_getNullRange();
1206
1207 CXSourceRange Result = { { begin.ptr_data[0], begin.ptr_data[1] },
1208 begin.int_data, end.int_data };
Douglas Gregorb9790342010-01-22 21:44:22 +00001209 return Result;
1210}
1211
Douglas Gregor46766dc2010-01-26 19:19:08 +00001212void clang_getInstantiationLocation(CXSourceLocation location,
1213 CXFile *file,
1214 unsigned *line,
1215 unsigned *column,
1216 unsigned *offset) {
Douglas Gregor1db19de2010-01-19 21:36:55 +00001217 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
1218
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00001219 if (!location.ptr_data[0] || Loc.isInvalid()) {
Douglas Gregor46766dc2010-01-26 19:19:08 +00001220 if (file)
1221 *file = 0;
1222 if (line)
1223 *line = 0;
1224 if (column)
1225 *column = 0;
1226 if (offset)
1227 *offset = 0;
1228 return;
1229 }
1230
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00001231 const SourceManager &SM =
1232 *static_cast<const SourceManager*>(location.ptr_data[0]);
Douglas Gregor1db19de2010-01-19 21:36:55 +00001233 SourceLocation InstLoc = SM.getInstantiationLoc(Loc);
Douglas Gregor1db19de2010-01-19 21:36:55 +00001234
1235 if (file)
1236 *file = (void *)SM.getFileEntryForID(SM.getFileID(InstLoc));
1237 if (line)
1238 *line = SM.getInstantiationLineNumber(InstLoc);
1239 if (column)
1240 *column = SM.getInstantiationColumnNumber(InstLoc);
Douglas Gregore69517c2010-01-26 03:07:15 +00001241 if (offset)
Douglas Gregor46766dc2010-01-26 19:19:08 +00001242 *offset = SM.getDecomposedLoc(InstLoc).second;
Douglas Gregore69517c2010-01-26 03:07:15 +00001243}
1244
Douglas Gregor1db19de2010-01-19 21:36:55 +00001245CXSourceLocation clang_getRangeStart(CXSourceRange range) {
Douglas Gregor5352ac02010-01-28 00:27:43 +00001246 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
1247 range.begin_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00001248 return Result;
1249}
1250
1251CXSourceLocation clang_getRangeEnd(CXSourceRange range) {
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00001252 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00001253 range.end_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00001254 return Result;
1255}
1256
Douglas Gregorb9790342010-01-22 21:44:22 +00001257} // end: extern "C"
1258
Douglas Gregor1db19de2010-01-19 21:36:55 +00001259//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00001260// CXFile Operations.
1261//===----------------------------------------------------------------------===//
1262
1263extern "C" {
Steve Naroff88145032009-10-27 14:35:18 +00001264const char *clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00001265 if (!SFile)
1266 return 0;
1267
Steve Naroff88145032009-10-27 14:35:18 +00001268 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
1269 return FEnt->getName();
1270}
1271
1272time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00001273 if (!SFile)
1274 return 0;
1275
Steve Naroff88145032009-10-27 14:35:18 +00001276 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
1277 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +00001278}
Douglas Gregorb9790342010-01-22 21:44:22 +00001279
1280CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
1281 if (!tu)
1282 return 0;
1283
1284 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
1285
1286 FileManager &FMgr = CXXUnit->getFileManager();
1287 const FileEntry *File = FMgr.getFile(file_name, file_name+strlen(file_name));
1288 return const_cast<FileEntry *>(File);
1289}
1290
Ted Kremenekfb480492010-01-13 21:46:36 +00001291} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +00001292
Ted Kremenekfb480492010-01-13 21:46:36 +00001293//===----------------------------------------------------------------------===//
1294// CXCursor Operations.
1295//===----------------------------------------------------------------------===//
1296
Ted Kremenekfb480492010-01-13 21:46:36 +00001297static Decl *getDeclFromExpr(Stmt *E) {
1298 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
1299 return RefExpr->getDecl();
1300 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
1301 return ME->getMemberDecl();
1302 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
1303 return RE->getDecl();
1304
1305 if (CallExpr *CE = dyn_cast<CallExpr>(E))
1306 return getDeclFromExpr(CE->getCallee());
1307 if (CastExpr *CE = dyn_cast<CastExpr>(E))
1308 return getDeclFromExpr(CE->getSubExpr());
1309 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
1310 return OME->getMethodDecl();
1311
1312 return 0;
1313}
1314
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00001315static SourceLocation getLocationFromExpr(Expr *E) {
1316 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
1317 return /*FIXME:*/Msg->getLeftLoc();
1318 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
1319 return DRE->getLocation();
1320 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
1321 return Member->getMemberLoc();
1322 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
1323 return Ivar->getLocation();
1324 return E->getLocStart();
1325}
1326
Ted Kremenekfb480492010-01-13 21:46:36 +00001327extern "C" {
Douglas Gregorb1373d02010-01-20 20:59:29 +00001328
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001329unsigned clang_visitChildren(CXCursor parent,
Douglas Gregorb1373d02010-01-20 20:59:29 +00001330 CXCursorVisitor visitor,
1331 CXClientData client_data) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001332 ASTUnit *CXXUnit = getCursorASTUnit(parent);
Douglas Gregorb1373d02010-01-20 20:59:29 +00001333
1334 unsigned PCHLevel = Decl::MaxPCHLevel;
1335
1336 // Set the PCHLevel to filter out unwanted decls if requested.
1337 if (CXXUnit->getOnlyLocalDecls()) {
1338 PCHLevel = 0;
1339
1340 // If the main input was an AST, bump the level.
1341 if (CXXUnit->isMainFileAST())
1342 ++PCHLevel;
1343 }
1344
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001345 CursorVisitor CursorVis(CXXUnit, visitor, client_data, PCHLevel);
Douglas Gregorb1373d02010-01-20 20:59:29 +00001346 return CursorVis.VisitChildren(parent);
1347}
1348
Douglas Gregor78205d42010-01-20 21:45:58 +00001349static CXString getDeclSpelling(Decl *D) {
1350 NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
1351 if (!ND)
1352 return CIndexer::createCXString("");
1353
1354 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
1355 return CIndexer::createCXString(OMD->getSelector().getAsString().c_str(),
1356 true);
1357
1358 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
1359 // No, this isn't the same as the code below. getIdentifier() is non-virtual
1360 // and returns different names. NamedDecl returns the class name and
1361 // ObjCCategoryImplDecl returns the category name.
1362 return CIndexer::createCXString(CIMP->getIdentifier()->getNameStart());
1363
1364 if (ND->getIdentifier())
1365 return CIndexer::createCXString(ND->getIdentifier()->getNameStart());
1366
1367 return CIndexer::createCXString("");
1368}
1369
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001370CXString clang_getCursorSpelling(CXCursor C) {
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001371 if (clang_isTranslationUnit(C.kind))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001372 return clang_getTranslationUnitSpelling(C.data[2]);
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001373
Steve Narofff334b4e2009-09-02 18:26:48 +00001374 if (clang_isReference(C.kind)) {
1375 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00001376 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +00001377 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
1378 return CIndexer::createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00001379 }
1380 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +00001381 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
1382 return CIndexer::createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00001383 }
1384 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +00001385 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +00001386 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenek4b333d22010-01-12 00:36:38 +00001387 return CIndexer::createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00001388 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001389 case CXCursor_TypeRef: {
1390 TypeDecl *Type = getCursorTypeRef(C).first;
1391 assert(Type && "Missing type decl");
1392
1393 return CIndexer::createCXString(
1394 getCursorContext(C).getTypeDeclType(Type).getAsString().c_str(),
1395 true);
1396 }
1397
Daniel Dunbaracca7252009-11-30 20:42:49 +00001398 default:
Ted Kremenek4b333d22010-01-12 00:36:38 +00001399 return CIndexer::createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +00001400 }
1401 }
Douglas Gregor97b98722010-01-19 23:20:36 +00001402
1403 if (clang_isExpression(C.kind)) {
1404 Decl *D = getDeclFromExpr(getCursorExpr(C));
1405 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +00001406 return getDeclSpelling(D);
Douglas Gregor97b98722010-01-19 23:20:36 +00001407 return CIndexer::createCXString("");
1408 }
1409
Douglas Gregor60cbfac2010-01-25 16:56:17 +00001410 if (clang_isDeclaration(C.kind))
1411 return getDeclSpelling(getCursorDecl(C));
1412
1413 return CIndexer::createCXString("");
Steve Narofff334b4e2009-09-02 18:26:48 +00001414}
1415
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001416const char *clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00001417 switch (Kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00001418 case CXCursor_FunctionDecl: return "FunctionDecl";
1419 case CXCursor_TypedefDecl: return "TypedefDecl";
1420 case CXCursor_EnumDecl: return "EnumDecl";
1421 case CXCursor_EnumConstantDecl: return "EnumConstantDecl";
1422 case CXCursor_StructDecl: return "StructDecl";
1423 case CXCursor_UnionDecl: return "UnionDecl";
1424 case CXCursor_ClassDecl: return "ClassDecl";
1425 case CXCursor_FieldDecl: return "FieldDecl";
1426 case CXCursor_VarDecl: return "VarDecl";
1427 case CXCursor_ParmDecl: return "ParmDecl";
1428 case CXCursor_ObjCInterfaceDecl: return "ObjCInterfaceDecl";
1429 case CXCursor_ObjCCategoryDecl: return "ObjCCategoryDecl";
1430 case CXCursor_ObjCProtocolDecl: return "ObjCProtocolDecl";
1431 case CXCursor_ObjCPropertyDecl: return "ObjCPropertyDecl";
1432 case CXCursor_ObjCIvarDecl: return "ObjCIvarDecl";
1433 case CXCursor_ObjCInstanceMethodDecl: return "ObjCInstanceMethodDecl";
1434 case CXCursor_ObjCClassMethodDecl: return "ObjCClassMethodDecl";
Douglas Gregorb6998662010-01-19 19:34:47 +00001435 case CXCursor_ObjCImplementationDecl: return "ObjCImplementationDecl";
1436 case CXCursor_ObjCCategoryImplDecl: return "ObjCCategoryImplDecl";
Douglas Gregor30122132010-01-19 22:07:56 +00001437 case CXCursor_UnexposedDecl: return "UnexposedDecl";
Daniel Dunbaracca7252009-11-30 20:42:49 +00001438 case CXCursor_ObjCSuperClassRef: return "ObjCSuperClassRef";
1439 case CXCursor_ObjCProtocolRef: return "ObjCProtocolRef";
1440 case CXCursor_ObjCClassRef: return "ObjCClassRef";
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001441 case CXCursor_TypeRef: return "TypeRef";
Douglas Gregor97b98722010-01-19 23:20:36 +00001442 case CXCursor_UnexposedExpr: return "UnexposedExpr";
1443 case CXCursor_DeclRefExpr: return "DeclRefExpr";
1444 case CXCursor_MemberRefExpr: return "MemberRefExpr";
1445 case CXCursor_CallExpr: return "CallExpr";
1446 case CXCursor_ObjCMessageExpr: return "ObjCMessageExpr";
1447 case CXCursor_UnexposedStmt: return "UnexposedStmt";
Daniel Dunbaracca7252009-11-30 20:42:49 +00001448 case CXCursor_InvalidFile: return "InvalidFile";
1449 case CXCursor_NoDeclFound: return "NoDeclFound";
1450 case CXCursor_NotImplemented: return "NotImplemented";
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001451 case CXCursor_TranslationUnit: return "TranslationUnit";
Steve Naroff89922f82009-08-31 00:59:03 +00001452 }
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00001453
1454 llvm_unreachable("Unhandled CXCursorKind");
1455 return NULL;
Steve Naroff600866c2009-08-27 19:51:58 +00001456}
Steve Naroff89922f82009-08-31 00:59:03 +00001457
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001458enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
1459 CXCursor parent,
1460 CXClientData client_data) {
1461 CXCursor *BestCursor = static_cast<CXCursor *>(client_data);
1462 *BestCursor = cursor;
1463 return CXChildVisit_Recurse;
1464}
1465
Douglas Gregorb9790342010-01-22 21:44:22 +00001466CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
1467 if (!TU)
Ted Kremenekf4629892010-01-14 01:51:23 +00001468 return clang_getNullCursor();
Ted Kremenekf4629892010-01-14 01:51:23 +00001469
Douglas Gregorb9790342010-01-22 21:44:22 +00001470 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
1471
Ted Kremeneka297de22010-01-25 22:34:44 +00001472 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001473 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
1474 if (SLoc.isValid()) {
1475 SourceRange RegionOfInterest(SLoc,
1476 CXXUnit->getPreprocessor().getLocForEndOfToken(SLoc, 1));
1477
1478 // FIXME: Would be great to have a "hint" cursor, then walk from that
1479 // hint cursor upward until we find a cursor whose source range encloses
1480 // the region of interest, rather than starting from the translation unit.
1481 CXCursor Parent = clang_getTranslationUnitCursor(CXXUnit);
1482 CursorVisitor CursorVis(CXXUnit, GetCursorVisitor, &Result,
1483 Decl::MaxPCHLevel, RegionOfInterest);
1484 CursorVis.VisitChildren(Parent);
Steve Naroff77128dd2009-09-15 20:25:34 +00001485 }
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001486 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00001487}
1488
Ted Kremenek73885552009-11-17 19:28:59 +00001489CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00001490 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00001491}
1492
1493unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00001494 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00001495}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001496
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001497unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00001498 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
1499}
1500
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001501unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +00001502 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
1503}
Steve Naroff2d4d6292009-08-31 14:26:51 +00001504
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001505unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00001506 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
1507}
1508
Douglas Gregor97b98722010-01-19 23:20:36 +00001509unsigned clang_isExpression(enum CXCursorKind K) {
1510 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
1511}
1512
1513unsigned clang_isStatement(enum CXCursorKind K) {
1514 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
1515}
1516
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001517unsigned clang_isTranslationUnit(enum CXCursorKind K) {
1518 return K == CXCursor_TranslationUnit;
1519}
1520
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001521CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00001522 return C.kind;
1523}
1524
Douglas Gregor98258af2010-01-18 22:46:11 +00001525CXSourceLocation clang_getCursorLocation(CXCursor C) {
1526 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00001527 switch (C.kind) {
1528 case CXCursor_ObjCSuperClassRef: {
1529 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1530 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001531 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001532 }
1533
1534 case CXCursor_ObjCProtocolRef: {
1535 std::pair<ObjCProtocolDecl *, SourceLocation> P
1536 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001537 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001538 }
1539
1540 case CXCursor_ObjCClassRef: {
1541 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1542 = getCursorObjCClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001543 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001544 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001545
1546 case CXCursor_TypeRef: {
1547 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001548 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001549 }
Douglas Gregorf46034a2010-01-18 23:41:10 +00001550
Douglas Gregorf46034a2010-01-18 23:41:10 +00001551 default:
1552 // FIXME: Need a way to enumerate all non-reference cases.
1553 llvm_unreachable("Missed a reference kind");
1554 }
Douglas Gregor98258af2010-01-18 22:46:11 +00001555 }
Douglas Gregor97b98722010-01-19 23:20:36 +00001556
1557 if (clang_isExpression(C.kind))
Ted Kremeneka297de22010-01-25 22:34:44 +00001558 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00001559 getLocationFromExpr(getCursorExpr(C)));
1560
Douglas Gregor5352ac02010-01-28 00:27:43 +00001561 if (!getCursorDecl(C))
1562 return clang_getNullLocation();
Douglas Gregor98258af2010-01-18 22:46:11 +00001563
Douglas Gregorf46034a2010-01-18 23:41:10 +00001564 Decl *D = getCursorDecl(C);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001565 SourceLocation Loc = D->getLocation();
1566 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
1567 Loc = Class->getClassLoc();
Ted Kremeneka297de22010-01-25 22:34:44 +00001568 return cxloc::translateSourceLocation(D->getASTContext(), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00001569}
Douglas Gregora7bde202010-01-19 00:34:46 +00001570
1571CXSourceRange clang_getCursorExtent(CXCursor C) {
1572 if (clang_isReference(C.kind)) {
1573 switch (C.kind) {
1574 case CXCursor_ObjCSuperClassRef: {
1575 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1576 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001577 return cxloc::translateSourceRange(P.first->getASTContext(), P.second);
Douglas Gregora7bde202010-01-19 00:34:46 +00001578 }
1579
1580 case CXCursor_ObjCProtocolRef: {
1581 std::pair<ObjCProtocolDecl *, SourceLocation> P
1582 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001583 return cxloc::translateSourceRange(P.first->getASTContext(), P.second);
Douglas Gregora7bde202010-01-19 00:34:46 +00001584 }
1585
1586 case CXCursor_ObjCClassRef: {
1587 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1588 = getCursorObjCClassRef(C);
1589
Ted Kremeneka297de22010-01-25 22:34:44 +00001590 return cxloc::translateSourceRange(P.first->getASTContext(), P.second);
Douglas Gregora7bde202010-01-19 00:34:46 +00001591 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001592
1593 case CXCursor_TypeRef: {
1594 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001595 return cxloc::translateSourceRange(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001596 }
Douglas Gregora7bde202010-01-19 00:34:46 +00001597
Douglas Gregora7bde202010-01-19 00:34:46 +00001598 default:
1599 // FIXME: Need a way to enumerate all non-reference cases.
1600 llvm_unreachable("Missed a reference kind");
1601 }
1602 }
Douglas Gregor97b98722010-01-19 23:20:36 +00001603
1604 if (clang_isExpression(C.kind))
Ted Kremeneka297de22010-01-25 22:34:44 +00001605 return cxloc::translateSourceRange(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00001606 getCursorExpr(C)->getSourceRange());
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001607
1608 if (clang_isStatement(C.kind))
Ted Kremeneka297de22010-01-25 22:34:44 +00001609 return cxloc::translateSourceRange(getCursorContext(C),
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001610 getCursorStmt(C)->getSourceRange());
Douglas Gregora7bde202010-01-19 00:34:46 +00001611
Douglas Gregor5352ac02010-01-28 00:27:43 +00001612 if (!getCursorDecl(C))
1613 return clang_getNullRange();
Douglas Gregora7bde202010-01-19 00:34:46 +00001614
1615 Decl *D = getCursorDecl(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001616 return cxloc::translateSourceRange(D->getASTContext(), D->getSourceRange());
Douglas Gregora7bde202010-01-19 00:34:46 +00001617}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001618
1619CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001620 if (clang_isInvalid(C.kind))
1621 return clang_getNullCursor();
1622
1623 ASTUnit *CXXUnit = getCursorASTUnit(C);
Douglas Gregorb6998662010-01-19 19:34:47 +00001624 if (clang_isDeclaration(C.kind))
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001625 return C;
Douglas Gregor98258af2010-01-18 22:46:11 +00001626
Douglas Gregor97b98722010-01-19 23:20:36 +00001627 if (clang_isExpression(C.kind)) {
1628 Decl *D = getDeclFromExpr(getCursorExpr(C));
1629 if (D)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001630 return MakeCXCursor(D, CXXUnit);
Douglas Gregor97b98722010-01-19 23:20:36 +00001631 return clang_getNullCursor();
1632 }
1633
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001634 if (!clang_isReference(C.kind))
1635 return clang_getNullCursor();
1636
1637 switch (C.kind) {
1638 case CXCursor_ObjCSuperClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001639 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, CXXUnit);
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001640
1641 case CXCursor_ObjCProtocolRef: {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001642 return MakeCXCursor(getCursorObjCProtocolRef(C).first, CXXUnit);
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001643
1644 case CXCursor_ObjCClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001645 return MakeCXCursor(getCursorObjCClassRef(C).first, CXXUnit);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001646
1647 case CXCursor_TypeRef:
1648 return MakeCXCursor(getCursorTypeRef(C).first, CXXUnit);
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001649
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001650 default:
1651 // We would prefer to enumerate all non-reference cursor kinds here.
1652 llvm_unreachable("Unhandled reference cursor kind");
1653 break;
1654 }
1655 }
1656
1657 return clang_getNullCursor();
1658}
1659
Douglas Gregorb6998662010-01-19 19:34:47 +00001660CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001661 if (clang_isInvalid(C.kind))
1662 return clang_getNullCursor();
1663
1664 ASTUnit *CXXUnit = getCursorASTUnit(C);
1665
Douglas Gregorb6998662010-01-19 19:34:47 +00001666 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00001667 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00001668 C = clang_getCursorReferenced(C);
1669 WasReference = true;
1670 }
1671
1672 if (!clang_isDeclaration(C.kind))
1673 return clang_getNullCursor();
1674
1675 Decl *D = getCursorDecl(C);
1676 if (!D)
1677 return clang_getNullCursor();
1678
1679 switch (D->getKind()) {
1680 // Declaration kinds that don't really separate the notions of
1681 // declaration and definition.
1682 case Decl::Namespace:
1683 case Decl::Typedef:
1684 case Decl::TemplateTypeParm:
1685 case Decl::EnumConstant:
1686 case Decl::Field:
1687 case Decl::ObjCIvar:
1688 case Decl::ObjCAtDefsField:
1689 case Decl::ImplicitParam:
1690 case Decl::ParmVar:
1691 case Decl::NonTypeTemplateParm:
1692 case Decl::TemplateTemplateParm:
1693 case Decl::ObjCCategoryImpl:
1694 case Decl::ObjCImplementation:
1695 case Decl::LinkageSpec:
1696 case Decl::ObjCPropertyImpl:
1697 case Decl::FileScopeAsm:
1698 case Decl::StaticAssert:
1699 case Decl::Block:
1700 return C;
1701
1702 // Declaration kinds that don't make any sense here, but are
1703 // nonetheless harmless.
1704 case Decl::TranslationUnit:
1705 case Decl::Template:
1706 case Decl::ObjCContainer:
1707 break;
1708
1709 // Declaration kinds for which the definition is not resolvable.
1710 case Decl::UnresolvedUsingTypename:
1711 case Decl::UnresolvedUsingValue:
1712 break;
1713
1714 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001715 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
1716 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001717
1718 case Decl::NamespaceAlias:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001719 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001720
1721 case Decl::Enum:
1722 case Decl::Record:
1723 case Decl::CXXRecord:
1724 case Decl::ClassTemplateSpecialization:
1725 case Decl::ClassTemplatePartialSpecialization:
Douglas Gregor952b0172010-02-11 01:04:33 +00001726 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001727 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001728 return clang_getNullCursor();
1729
1730 case Decl::Function:
1731 case Decl::CXXMethod:
1732 case Decl::CXXConstructor:
1733 case Decl::CXXDestructor:
1734 case Decl::CXXConversion: {
1735 const FunctionDecl *Def = 0;
1736 if (cast<FunctionDecl>(D)->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001737 return MakeCXCursor(const_cast<FunctionDecl *>(Def), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001738 return clang_getNullCursor();
1739 }
1740
1741 case Decl::Var: {
Sebastian Redl31310a22010-02-01 20:16:42 +00001742 // Ask the variable if it has a definition.
1743 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
1744 return MakeCXCursor(Def, CXXUnit);
1745 return clang_getNullCursor();
Douglas Gregorb6998662010-01-19 19:34:47 +00001746 }
1747
1748 case Decl::FunctionTemplate: {
1749 const FunctionDecl *Def = 0;
1750 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001751 return MakeCXCursor(Def->getDescribedFunctionTemplate(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001752 return clang_getNullCursor();
1753 }
1754
1755 case Decl::ClassTemplate: {
1756 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
Douglas Gregor952b0172010-02-11 01:04:33 +00001757 ->getDefinition())
Douglas Gregorb6998662010-01-19 19:34:47 +00001758 return MakeCXCursor(
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001759 cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
1760 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001761 return clang_getNullCursor();
1762 }
1763
1764 case Decl::Using: {
1765 UsingDecl *Using = cast<UsingDecl>(D);
1766 CXCursor Def = clang_getNullCursor();
1767 for (UsingDecl::shadow_iterator S = Using->shadow_begin(),
1768 SEnd = Using->shadow_end();
1769 S != SEnd; ++S) {
1770 if (Def != clang_getNullCursor()) {
1771 // FIXME: We have no way to return multiple results.
1772 return clang_getNullCursor();
1773 }
1774
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001775 Def = clang_getCursorDefinition(MakeCXCursor((*S)->getTargetDecl(),
1776 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00001777 }
1778
1779 return Def;
1780 }
1781
1782 case Decl::UsingShadow:
1783 return clang_getCursorDefinition(
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001784 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
1785 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00001786
1787 case Decl::ObjCMethod: {
1788 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
1789 if (Method->isThisDeclarationADefinition())
1790 return C;
1791
1792 // Dig out the method definition in the associated
1793 // @implementation, if we have it.
1794 // FIXME: The ASTs should make finding the definition easier.
1795 if (ObjCInterfaceDecl *Class
1796 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
1797 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
1798 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
1799 Method->isInstanceMethod()))
1800 if (Def->isThisDeclarationADefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001801 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001802
1803 return clang_getNullCursor();
1804 }
1805
1806 case Decl::ObjCCategory:
1807 if (ObjCCategoryImplDecl *Impl
1808 = cast<ObjCCategoryDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001809 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001810 return clang_getNullCursor();
1811
1812 case Decl::ObjCProtocol:
1813 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
1814 return C;
1815 return clang_getNullCursor();
1816
1817 case Decl::ObjCInterface:
1818 // There are two notions of a "definition" for an Objective-C
1819 // class: the interface and its implementation. When we resolved a
1820 // reference to an Objective-C class, produce the @interface as
1821 // the definition; when we were provided with the interface,
1822 // produce the @implementation as the definition.
1823 if (WasReference) {
1824 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
1825 return C;
1826 } else if (ObjCImplementationDecl *Impl
1827 = cast<ObjCInterfaceDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001828 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001829 return clang_getNullCursor();
1830
1831 case Decl::ObjCProperty:
1832 // FIXME: We don't really know where to find the
1833 // ObjCPropertyImplDecls that implement this property.
1834 return clang_getNullCursor();
1835
1836 case Decl::ObjCCompatibleAlias:
1837 if (ObjCInterfaceDecl *Class
1838 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
1839 if (!Class->isForwardDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001840 return MakeCXCursor(Class, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001841
1842 return clang_getNullCursor();
1843
1844 case Decl::ObjCForwardProtocol: {
1845 ObjCForwardProtocolDecl *Forward = cast<ObjCForwardProtocolDecl>(D);
1846 if (Forward->protocol_size() == 1)
1847 return clang_getCursorDefinition(
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001848 MakeCXCursor(*Forward->protocol_begin(),
1849 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00001850
1851 // FIXME: Cannot return multiple definitions.
1852 return clang_getNullCursor();
1853 }
1854
1855 case Decl::ObjCClass: {
1856 ObjCClassDecl *Class = cast<ObjCClassDecl>(D);
1857 if (Class->size() == 1) {
1858 ObjCInterfaceDecl *IFace = Class->begin()->getInterface();
1859 if (!IFace->isForwardDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001860 return MakeCXCursor(IFace, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001861 return clang_getNullCursor();
1862 }
1863
1864 // FIXME: Cannot return multiple definitions.
1865 return clang_getNullCursor();
1866 }
1867
1868 case Decl::Friend:
1869 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001870 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00001871 return clang_getNullCursor();
1872
1873 case Decl::FriendTemplate:
1874 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001875 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00001876 return clang_getNullCursor();
1877 }
1878
1879 return clang_getNullCursor();
1880}
1881
1882unsigned clang_isCursorDefinition(CXCursor C) {
1883 if (!clang_isDeclaration(C.kind))
1884 return 0;
1885
1886 return clang_getCursorDefinition(C) == C;
1887}
1888
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001889void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00001890 const char **startBuf,
1891 const char **endBuf,
1892 unsigned *startLine,
1893 unsigned *startColumn,
1894 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001895 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00001896 assert(getCursorDecl(C) && "CXCursor has null decl");
1897 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00001898 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
1899 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekfb480492010-01-13 21:46:36 +00001900
Steve Naroff4ade6d62009-09-23 17:52:52 +00001901 SourceManager &SM = FD->getASTContext().getSourceManager();
1902 *startBuf = SM.getCharacterData(Body->getLBracLoc());
1903 *endBuf = SM.getCharacterData(Body->getRBracLoc());
1904 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
1905 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
1906 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
1907 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
1908}
Ted Kremenekfb480492010-01-13 21:46:36 +00001909
1910} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00001911
Ted Kremenekfb480492010-01-13 21:46:36 +00001912//===----------------------------------------------------------------------===//
Douglas Gregorfc8ea232010-01-26 17:06:03 +00001913// Token-based Operations.
1914//===----------------------------------------------------------------------===//
1915
1916/* CXToken layout:
1917 * int_data[0]: a CXTokenKind
1918 * int_data[1]: starting token location
1919 * int_data[2]: token length
1920 * int_data[3]: reserved
1921 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
1922 * otherwise unused.
1923 */
1924extern "C" {
1925
1926CXTokenKind clang_getTokenKind(CXToken CXTok) {
1927 return static_cast<CXTokenKind>(CXTok.int_data[0]);
1928}
1929
1930CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
1931 switch (clang_getTokenKind(CXTok)) {
1932 case CXToken_Identifier:
1933 case CXToken_Keyword:
1934 // We know we have an IdentifierInfo*, so use that.
1935 return CIndexer::createCXString(
1936 static_cast<IdentifierInfo *>(CXTok.ptr_data)->getNameStart());
1937
1938 case CXToken_Literal: {
1939 // We have stashed the starting pointer in the ptr_data field. Use it.
1940 const char *Text = static_cast<const char *>(CXTok.ptr_data);
1941 return CIndexer::createCXString(llvm::StringRef(Text, CXTok.int_data[2]),
1942 true);
1943 }
1944
1945 case CXToken_Punctuation:
1946 case CXToken_Comment:
1947 break;
1948 }
1949
1950 // We have to find the starting buffer pointer the hard way, by
1951 // deconstructing the source location.
1952 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
1953 if (!CXXUnit)
1954 return CIndexer::createCXString("");
1955
1956 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
1957 std::pair<FileID, unsigned> LocInfo
1958 = CXXUnit->getSourceManager().getDecomposedLoc(Loc);
1959 std::pair<const char *,const char *> Buffer
1960 = CXXUnit->getSourceManager().getBufferData(LocInfo.first);
1961
1962 return CIndexer::createCXString(llvm::StringRef(Buffer.first+LocInfo.second,
1963 CXTok.int_data[2]),
1964 true);
1965}
1966
1967CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
1968 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
1969 if (!CXXUnit)
1970 return clang_getNullLocation();
1971
1972 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
1973 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
1974}
1975
1976CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
1977 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregor5352ac02010-01-28 00:27:43 +00001978 if (!CXXUnit)
1979 return clang_getNullRange();
Douglas Gregorfc8ea232010-01-26 17:06:03 +00001980
1981 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
1982 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
1983}
1984
1985void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
1986 CXToken **Tokens, unsigned *NumTokens) {
1987 if (Tokens)
1988 *Tokens = 0;
1989 if (NumTokens)
1990 *NumTokens = 0;
1991
1992 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
1993 if (!CXXUnit || !Tokens || !NumTokens)
1994 return;
1995
Daniel Dunbar85b988f2010-02-14 08:31:57 +00001996 SourceRange R = cxloc::translateCXSourceRange(Range);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00001997 if (R.isInvalid())
1998 return;
1999
2000 SourceManager &SourceMgr = CXXUnit->getSourceManager();
2001 std::pair<FileID, unsigned> BeginLocInfo
2002 = SourceMgr.getDecomposedLoc(R.getBegin());
2003 std::pair<FileID, unsigned> EndLocInfo
2004 = SourceMgr.getDecomposedLoc(R.getEnd());
2005
2006 // Cannot tokenize across files.
2007 if (BeginLocInfo.first != EndLocInfo.first)
2008 return;
2009
2010 // Create a lexer
2011 std::pair<const char *,const char *> Buffer
2012 = SourceMgr.getBufferData(BeginLocInfo.first);
2013 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
2014 CXXUnit->getASTContext().getLangOptions(),
2015 Buffer.first, Buffer.first + BeginLocInfo.second, Buffer.second);
2016 Lex.SetCommentRetentionState(true);
2017
2018 // Lex tokens until we hit the end of the range.
2019 const char *EffectiveBufferEnd = Buffer.first + EndLocInfo.second;
2020 llvm::SmallVector<CXToken, 32> CXTokens;
2021 Token Tok;
2022 do {
2023 // Lex the next token
2024 Lex.LexFromRawLexer(Tok);
2025 if (Tok.is(tok::eof))
2026 break;
2027
2028 // Initialize the CXToken.
2029 CXToken CXTok;
2030
2031 // - Common fields
2032 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
2033 CXTok.int_data[2] = Tok.getLength();
2034 CXTok.int_data[3] = 0;
2035
2036 // - Kind-specific fields
2037 if (Tok.isLiteral()) {
2038 CXTok.int_data[0] = CXToken_Literal;
2039 CXTok.ptr_data = (void *)Tok.getLiteralData();
2040 } else if (Tok.is(tok::identifier)) {
2041 // Lookup the identifier to determine whether we have a
2042 std::pair<FileID, unsigned> LocInfo
2043 = SourceMgr.getDecomposedLoc(Tok.getLocation());
2044 const char *StartPos
2045 = CXXUnit->getSourceManager().getBufferData(LocInfo.first).first +
2046 LocInfo.second;
2047 IdentifierInfo *II
2048 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok, StartPos);
2049 CXTok.int_data[0] = II->getTokenID() == tok::identifier?
2050 CXToken_Identifier
2051 : CXToken_Keyword;
2052 CXTok.ptr_data = II;
2053 } else if (Tok.is(tok::comment)) {
2054 CXTok.int_data[0] = CXToken_Comment;
2055 CXTok.ptr_data = 0;
2056 } else {
2057 CXTok.int_data[0] = CXToken_Punctuation;
2058 CXTok.ptr_data = 0;
2059 }
2060 CXTokens.push_back(CXTok);
2061 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
2062
2063 if (CXTokens.empty())
2064 return;
2065
2066 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
2067 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
2068 *NumTokens = CXTokens.size();
2069}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002070
2071typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
2072
2073enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
2074 CXCursor parent,
2075 CXClientData client_data) {
2076 AnnotateTokensData *Data = static_cast<AnnotateTokensData *>(client_data);
2077
2078 // We only annotate the locations of declarations, simple
2079 // references, and expressions which directly reference something.
2080 CXCursorKind Kind = clang_getCursorKind(cursor);
2081 if (clang_isDeclaration(Kind) || clang_isReference(Kind)) {
2082 // Okay: We can annotate the location of this declaration with the
2083 // declaration or reference
2084 } else if (clang_isExpression(cursor.kind)) {
2085 if (Kind != CXCursor_DeclRefExpr &&
2086 Kind != CXCursor_MemberRefExpr &&
2087 Kind != CXCursor_ObjCMessageExpr)
2088 return CXChildVisit_Recurse;
2089
2090 CXCursor Referenced = clang_getCursorReferenced(cursor);
2091 if (Referenced == cursor || Referenced == clang_getNullCursor())
2092 return CXChildVisit_Recurse;
2093
2094 // Okay: we can annotate the location of this expression
2095 } else {
2096 // Nothing to annotate
2097 return CXChildVisit_Recurse;
2098 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002099
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002100 CXSourceLocation Loc = clang_getCursorLocation(cursor);
2101 (*Data)[Loc.int_data] = cursor;
2102 return CXChildVisit_Recurse;
2103}
2104
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002105void clang_annotateTokens(CXTranslationUnit TU,
2106 CXToken *Tokens, unsigned NumTokens,
2107 CXCursor *Cursors) {
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002108 if (NumTokens == 0)
2109 return;
2110
2111 // Any token we don't specifically annotate will have a NULL cursor.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002112 for (unsigned I = 0; I != NumTokens; ++I)
2113 Cursors[I] = clang_getNullCursor();
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002114
2115 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2116 if (!CXXUnit || !Tokens)
2117 return;
2118
2119 // Annotate all of the source locations in the region of interest that map
2120 SourceRange RegionOfInterest;
2121 RegionOfInterest.setBegin(
2122 cxloc::translateSourceLocation(clang_getTokenLocation(TU, Tokens[0])));
2123 SourceLocation End
2124 = cxloc::translateSourceLocation(clang_getTokenLocation(TU,
2125 Tokens[NumTokens - 1]));
2126 RegionOfInterest.setEnd(CXXUnit->getPreprocessor().getLocForEndOfToken(End,
2127 1));
2128 // FIXME: Would be great to have a "hint" cursor, then walk from that
2129 // hint cursor upward until we find a cursor whose source range encloses
2130 // the region of interest, rather than starting from the translation unit.
2131 AnnotateTokensData Annotated;
2132 CXCursor Parent = clang_getTranslationUnitCursor(CXXUnit);
2133 CursorVisitor AnnotateVis(CXXUnit, AnnotateTokensVisitor, &Annotated,
2134 Decl::MaxPCHLevel, RegionOfInterest);
2135 AnnotateVis.VisitChildren(Parent);
2136
2137 for (unsigned I = 0; I != NumTokens; ++I) {
2138 // Determine whether we saw a cursor at this token's location.
2139 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
2140 if (Pos == Annotated.end())
2141 continue;
2142
2143 Cursors[I] = Pos->second;
2144 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002145}
2146
2147void clang_disposeTokens(CXTranslationUnit TU,
2148 CXToken *Tokens, unsigned NumTokens) {
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002149 free(Tokens);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002150}
2151
2152} // end: extern "C"
2153
2154//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00002155// CXString Operations.
2156//===----------------------------------------------------------------------===//
2157
2158extern "C" {
2159const char *clang_getCString(CXString string) {
2160 return string.Spelling;
2161}
2162
2163void clang_disposeString(CXString string) {
2164 if (string.MustFreeString && string.Spelling)
2165 free((void*)string.Spelling);
2166}
Ted Kremenek04bb7162010-01-22 22:44:15 +00002167
Ted Kremenekfb480492010-01-13 21:46:36 +00002168} // end: extern "C"
Ted Kremenek04bb7162010-01-22 22:44:15 +00002169
2170//===----------------------------------------------------------------------===//
2171// Misc. utility functions.
2172//===----------------------------------------------------------------------===//
2173
2174extern "C" {
2175
Ted Kremeneka2a9d6e2010-02-12 22:54:40 +00002176CXString clang_getClangVersion() {
2177 return CIndexer::createCXString(getClangFullVersion(), true);
Ted Kremenek04bb7162010-01-22 22:44:15 +00002178}
2179
2180} // end: extern "C"
2181