blob: 44efba7568a6b3614cf78975fc9348115bcda647 [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;
Ted Kremenekee4db4f2010-02-17 00:41:08 +000036using namespace clang::cxstring;
Steve Naroff50398192009-08-28 15:28:48 +000037using namespace idx;
38
Ted Kremenek8a8da7d2010-01-06 03:42:32 +000039//===----------------------------------------------------------------------===//
40// Crash Reporting.
41//===----------------------------------------------------------------------===//
42
43#ifdef __APPLE__
Ted Kremenek29b72842010-01-07 22:49:05 +000044#ifndef NDEBUG
45#define USE_CRASHTRACER
Ted Kremenek8a8da7d2010-01-06 03:42:32 +000046#include "clang/Analysis/Support/SaveAndRestore.h"
47// Integrate with crash reporter.
48extern "C" const char *__crashreporter_info__;
Ted Kremenek29b72842010-01-07 22:49:05 +000049#define NUM_CRASH_STRINGS 16
50static unsigned crashtracer_counter = 0;
Ted Kremenek254ba7c2010-01-07 23:13:53 +000051static unsigned crashtracer_counter_id[NUM_CRASH_STRINGS] = { 0 };
Ted Kremenek29b72842010-01-07 22:49:05 +000052static const char *crashtracer_strings[NUM_CRASH_STRINGS] = { 0 };
53static const char *agg_crashtracer_strings[NUM_CRASH_STRINGS] = { 0 };
54
55static unsigned SetCrashTracerInfo(const char *str,
56 llvm::SmallString<1024> &AggStr) {
57
Ted Kremenek254ba7c2010-01-07 23:13:53 +000058 unsigned slot = 0;
Ted Kremenek29b72842010-01-07 22:49:05 +000059 while (crashtracer_strings[slot]) {
60 if (++slot == NUM_CRASH_STRINGS)
61 slot = 0;
62 }
63 crashtracer_strings[slot] = str;
Ted Kremenek254ba7c2010-01-07 23:13:53 +000064 crashtracer_counter_id[slot] = ++crashtracer_counter;
Ted Kremenek29b72842010-01-07 22:49:05 +000065
66 // We need to create an aggregate string because multiple threads
67 // may be in this method at one time. The crash reporter string
68 // will attempt to overapproximate the set of in-flight invocations
69 // of this function. Race conditions can still cause this goal
70 // to not be achieved.
71 {
72 llvm::raw_svector_ostream Out(AggStr);
73 for (unsigned i = 0; i < NUM_CRASH_STRINGS; ++i)
74 if (crashtracer_strings[i]) Out << crashtracer_strings[i] << '\n';
75 }
76 __crashreporter_info__ = agg_crashtracer_strings[slot] = AggStr.c_str();
77 return slot;
78}
79
80static void ResetCrashTracerInfo(unsigned slot) {
Ted Kremenek254ba7c2010-01-07 23:13:53 +000081 unsigned max_slot = 0;
82 unsigned max_value = 0;
83
84 crashtracer_strings[slot] = agg_crashtracer_strings[slot] = 0;
85
86 for (unsigned i = 0 ; i < NUM_CRASH_STRINGS; ++i)
87 if (agg_crashtracer_strings[i] &&
88 crashtracer_counter_id[i] > max_value) {
89 max_slot = i;
90 max_value = crashtracer_counter_id[i];
Ted Kremenek29b72842010-01-07 22:49:05 +000091 }
Ted Kremenek254ba7c2010-01-07 23:13:53 +000092
93 __crashreporter_info__ = agg_crashtracer_strings[max_slot];
Ted Kremenek29b72842010-01-07 22:49:05 +000094}
95
96namespace {
97class ArgsCrashTracerInfo {
98 llvm::SmallString<1024> CrashString;
99 llvm::SmallString<1024> AggregateString;
100 unsigned crashtracerSlot;
101public:
102 ArgsCrashTracerInfo(llvm::SmallVectorImpl<const char*> &Args)
103 : crashtracerSlot(0)
104 {
105 {
106 llvm::raw_svector_ostream Out(CrashString);
107 Out << "ClangCIndex [createTranslationUnitFromSourceFile]: clang";
108 for (llvm::SmallVectorImpl<const char*>::iterator I=Args.begin(),
109 E=Args.end(); I!=E; ++I)
110 Out << ' ' << *I;
111 }
112 crashtracerSlot = SetCrashTracerInfo(CrashString.c_str(),
113 AggregateString);
114 }
115
116 ~ArgsCrashTracerInfo() {
117 ResetCrashTracerInfo(crashtracerSlot);
118 }
119};
120}
121#endif
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000122#endif
123
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000124/// \brief The result of comparing two source ranges.
125enum RangeComparisonResult {
126 /// \brief Either the ranges overlap or one of the ranges is invalid.
127 RangeOverlap,
128
129 /// \brief The first range ends before the second range starts.
130 RangeBefore,
131
132 /// \brief The first range starts after the second range ends.
133 RangeAfter
134};
135
136/// \brief Compare two source ranges to determine their relative position in
137/// the translation unit.
138static RangeComparisonResult RangeCompare(SourceManager &SM,
139 SourceRange R1,
140 SourceRange R2) {
141 assert(R1.isValid() && "First range is invalid?");
142 assert(R2.isValid() && "Second range is invalid?");
Daniel Dunbard52864b2010-02-14 10:02:57 +0000143 if (R1.getEnd() == R2.getBegin() ||
144 SM.isBeforeInTranslationUnit(R1.getEnd(), R2.getBegin()))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000145 return RangeBefore;
Daniel Dunbard52864b2010-02-14 10:02:57 +0000146 if (R2.getEnd() == R1.getBegin() ||
147 SM.isBeforeInTranslationUnit(R2.getEnd(), R1.getBegin()))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000148 return RangeAfter;
149 return RangeOverlap;
150}
151
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000152/// \brief Translate a Clang source range into a CIndex source range.
153///
154/// Clang internally represents ranges where the end location points to the
155/// start of the token at the end. However, for external clients it is more
156/// useful to have a CXSourceRange be a proper half-open interval. This routine
157/// does the appropriate translation.
158CXSourceRange cxloc::translateSourceRange(const SourceManager &SM,
159 const LangOptions &LangOpts,
160 SourceRange R) {
161 // FIXME: This is largely copy-paste from
162 // TextDiagnosticPrinter::HighlightRange. When it is clear that this is what
163 // we want the two routines should be refactored.
164
165 // We want the last character in this location, so we will adjust the
166 // instantiation location accordingly.
167
168 // If the location is from a macro instantiation, get the end of the
169 // instantiation range.
170 SourceLocation EndLoc = R.getEnd();
171 SourceLocation InstLoc = SM.getInstantiationLoc(EndLoc);
172 if (EndLoc.isMacroID())
173 InstLoc = SM.getInstantiationRange(EndLoc).second;
174
175 // Measure the length token we're pointing at, so we can adjust the physical
176 // location in the file to point at the last character.
177 //
178 // FIXME: This won't cope with trigraphs or escaped newlines well. For that,
179 // we actually need a preprocessor, which isn't currently available
180 // here. Eventually, we'll switch the pointer data of
181 // CXSourceLocation/CXSourceRange to a translation unit (CXXUnit), so that the
182 // preprocessor will be available here. At that point, we can use
183 // Preprocessor::getLocForEndOfToken().
184 if (InstLoc.isValid()) {
185 unsigned Length = Lexer::MeasureTokenLength(InstLoc, SM, LangOpts);
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000186 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 ///
Daniel Dunbard52864b2010-02-14 10:02:57 +0000238 /// \param R a half-open source range retrieved from the abstract syntax tree.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000239 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) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000322 return RangeCompare(TU->getSourceManager(), R, RegionOfInterest);
323}
324
Douglas Gregorb1373d02010-01-20 20:59:29 +0000325/// \brief Visit the given cursor and, if requested by the visitor,
326/// its children.
327///
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000328/// \param Cursor the cursor to visit.
329///
330/// \param CheckRegionOfInterest if true, then the caller already checked that
331/// this cursor is within the region of interest.
332///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000333/// \returns true if the visitation should be aborted, false if it
334/// should continue.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000335bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
Douglas Gregorb1373d02010-01-20 20:59:29 +0000336 if (clang_isInvalid(Cursor.kind))
337 return false;
338
339 if (clang_isDeclaration(Cursor.kind)) {
340 Decl *D = getCursorDecl(Cursor);
341 assert(D && "Invalid declaration cursor");
342 if (D->getPCHLevel() > MaxPCHLevel)
343 return false;
344
345 if (D->isImplicit())
346 return false;
347 }
348
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000349 // If we have a range of interest, and this cursor doesn't intersect with it,
350 // we're done.
351 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
Daniel Dunbarf408f322010-02-14 08:32:05 +0000352 SourceRange Range =
353 cxloc::translateCXSourceRange(clang_getCursorExtent(Cursor));
354 if (Range.isInvalid() || CompareRegionOfInterest(Range))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000355 return false;
356 }
357
Douglas Gregorb1373d02010-01-20 20:59:29 +0000358 switch (Visitor(Cursor, Parent, ClientData)) {
359 case CXChildVisit_Break:
360 return true;
361
362 case CXChildVisit_Continue:
363 return false;
364
365 case CXChildVisit_Recurse:
366 return VisitChildren(Cursor);
367 }
368
Douglas Gregorfd643772010-01-25 16:45:46 +0000369 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000370}
371
372/// \brief Visit the children of the given cursor.
373///
374/// \returns true if the visitation should be aborted, false if it
375/// should continue.
376bool CursorVisitor::VisitChildren(CXCursor Cursor) {
Douglas Gregora59e3902010-01-21 23:27:09 +0000377 if (clang_isReference(Cursor.kind)) {
378 // By definition, references have no children.
379 return false;
380 }
381
Douglas Gregorb1373d02010-01-20 20:59:29 +0000382 // Set the Parent field to Cursor, then back to its old value once we're
383 // done.
384 class SetParentRAII {
385 CXCursor &Parent;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000386 Decl *&StmtParent;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000387 CXCursor OldParent;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000388
Douglas Gregorb1373d02010-01-20 20:59:29 +0000389 public:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000390 SetParentRAII(CXCursor &Parent, Decl *&StmtParent, CXCursor NewParent)
391 : Parent(Parent), StmtParent(StmtParent), OldParent(Parent)
Douglas Gregorb1373d02010-01-20 20:59:29 +0000392 {
393 Parent = NewParent;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000394 if (clang_isDeclaration(Parent.kind))
395 StmtParent = getCursorDecl(Parent);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000396 }
397
398 ~SetParentRAII() {
399 Parent = OldParent;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000400 if (clang_isDeclaration(Parent.kind))
401 StmtParent = getCursorDecl(Parent);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000402 }
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000403 } SetParent(Parent, StmtParent, Cursor);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000404
405 if (clang_isDeclaration(Cursor.kind)) {
406 Decl *D = getCursorDecl(Cursor);
407 assert(D && "Invalid declaration cursor");
408 return Visit(D);
409 }
410
Douglas Gregora59e3902010-01-21 23:27:09 +0000411 if (clang_isStatement(Cursor.kind))
412 return Visit(getCursorStmt(Cursor));
413 if (clang_isExpression(Cursor.kind))
414 return Visit(getCursorExpr(Cursor));
415
Douglas Gregorb1373d02010-01-20 20:59:29 +0000416 if (clang_isTranslationUnit(Cursor.kind)) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000417 ASTUnit *CXXUnit = getCursorASTUnit(Cursor);
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000418 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
419 RegionOfInterest.isInvalid()) {
Douglas Gregor7b691f332010-01-20 21:13:59 +0000420 const std::vector<Decl*> &TLDs = CXXUnit->getTopLevelDecls();
421 for (std::vector<Decl*>::const_iterator it = TLDs.begin(),
422 ie = TLDs.end(); it != ie; ++it) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000423 if (Visit(MakeCXCursor(*it, CXXUnit), true))
Douglas Gregor7b691f332010-01-20 21:13:59 +0000424 return true;
425 }
426 } else {
427 return VisitDeclContext(
Douglas Gregorb1373d02010-01-20 20:59:29 +0000428 CXXUnit->getASTContext().getTranslationUnitDecl());
Douglas Gregor7b691f332010-01-20 21:13:59 +0000429 }
430
431 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000432 }
Douglas Gregora59e3902010-01-21 23:27:09 +0000433
Douglas Gregorb1373d02010-01-20 20:59:29 +0000434 // Nothing to visit at the moment.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000435 return false;
436}
437
Douglas Gregorb1373d02010-01-20 20:59:29 +0000438bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000439 for (DeclContext::decl_iterator
Douglas Gregorb1373d02010-01-20 20:59:29 +0000440 I = DC->decls_begin(), E = DC->decls_end(); I != E; ++I) {
Daniel Dunbard52864b2010-02-14 10:02:57 +0000441 CXCursor Cursor = MakeCXCursor(*I, TU);
442
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000443 if (RegionOfInterest.isValid()) {
Daniel Dunbard52864b2010-02-14 10:02:57 +0000444 SourceRange Range =
445 cxloc::translateCXSourceRange(clang_getCursorExtent(Cursor));
446 if (Range.isInvalid())
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000447 continue;
Daniel Dunbard52864b2010-02-14 10:02:57 +0000448
449 switch (CompareRegionOfInterest(Range)) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000450 case RangeBefore:
451 // This declaration comes before the region of interest; skip it.
452 continue;
453
454 case RangeAfter:
455 // This declaration comes after the region of interest; we're done.
456 return false;
457
458 case RangeOverlap:
459 // This declaration overlaps the region of interest; visit it.
460 break;
461 }
462 }
463
Daniel Dunbard52864b2010-02-14 10:02:57 +0000464 if (Visit(Cursor, true))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000465 return true;
466 }
467
468 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000469}
470
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000471bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
472 llvm_unreachable("Translation units are visited directly by Visit()");
473 return false;
474}
475
476bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
477 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
478 return Visit(TSInfo->getTypeLoc());
479
480 return false;
481}
482
483bool CursorVisitor::VisitTagDecl(TagDecl *D) {
484 return VisitDeclContext(D);
485}
486
487bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
488 if (Expr *Init = D->getInitExpr())
489 return Visit(MakeCXCursor(Init, StmtParent, TU));
490 return false;
491}
492
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000493bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
494 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
495 if (Visit(TSInfo->getTypeLoc()))
496 return true;
497
498 return false;
499}
500
Douglas Gregorb1373d02010-01-20 20:59:29 +0000501bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000502 if (VisitDeclaratorDecl(ND))
503 return true;
504
Douglas Gregora59e3902010-01-21 23:27:09 +0000505 if (ND->isThisDeclarationADefinition() &&
506 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
507 return true;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000508
509 return false;
510}
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000511
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000512bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
513 if (VisitDeclaratorDecl(D))
514 return true;
515
516 if (Expr *BitWidth = D->getBitWidth())
517 return Visit(MakeCXCursor(BitWidth, StmtParent, TU));
518
519 return false;
520}
521
522bool CursorVisitor::VisitVarDecl(VarDecl *D) {
523 if (VisitDeclaratorDecl(D))
524 return true;
525
526 if (Expr *Init = D->getInit())
527 return Visit(MakeCXCursor(Init, StmtParent, TU));
528
529 return false;
530}
531
532bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
533 // FIXME: We really need a TypeLoc covering Objective-C method declarations.
534 // At the moment, we don't have information about locations in the return
535 // type.
536 for (ObjCMethodDecl::param_iterator P = ND->param_begin(),
537 PEnd = ND->param_end();
538 P != PEnd; ++P) {
539 if (Visit(MakeCXCursor(*P, TU)))
540 return true;
541 }
542
543 if (ND->isThisDeclarationADefinition() &&
544 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
545 return true;
546
547 return false;
548}
549
Douglas Gregora59e3902010-01-21 23:27:09 +0000550bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
551 return VisitDeclContext(D);
552}
553
Douglas Gregorb1373d02010-01-20 20:59:29 +0000554bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000555 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
556 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000557 return true;
558
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000559 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
560 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
561 E = ND->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000562 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000563 return true;
564
Douglas Gregora59e3902010-01-21 23:27:09 +0000565 return VisitObjCContainerDecl(ND);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000566}
567
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000568bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
569 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
570 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
571 E = PID->protocol_end(); I != E; ++I, ++PL)
572 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
573 return true;
574
575 return VisitObjCContainerDecl(PID);
576}
577
Douglas Gregorb1373d02010-01-20 20:59:29 +0000578bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000579 // Issue callbacks for super class.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000580 if (D->getSuperClass() &&
581 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000582 D->getSuperClassLoc(),
583 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000584 return true;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000585
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000586 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
587 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
588 E = D->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000589 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000590 return true;
591
Douglas Gregora59e3902010-01-21 23:27:09 +0000592 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000593}
594
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000595bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
596 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000597}
598
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000599bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
600 if (Visit(MakeCursorObjCClassRef(D->getCategoryDecl()->getClassInterface(),
601 D->getLocation(), TU)))
602 return true;
603
604 return VisitObjCImplDecl(D);
605}
606
607bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
608#if 0
609 // Issue callbacks for super class.
610 // FIXME: No source location information!
611 if (D->getSuperClass() &&
612 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
613 D->getSuperClassLoc(),
614 TU)))
615 return true;
616#endif
617
618 return VisitObjCImplDecl(D);
619}
620
621bool CursorVisitor::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D) {
622 ObjCForwardProtocolDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
623 for (ObjCForwardProtocolDecl::protocol_iterator I = D->protocol_begin(),
624 E = D->protocol_end();
625 I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000626 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000627 return true;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000628
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000629 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000630}
631
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000632bool CursorVisitor::VisitObjCClassDecl(ObjCClassDecl *D) {
633 for (ObjCClassDecl::iterator C = D->begin(), CEnd = D->end(); C != CEnd; ++C)
634 if (Visit(MakeCursorObjCClassRef(C->getInterface(), C->getLocation(), TU)))
635 return true;
636
637 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000638}
639
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000640bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
641 ASTContext &Context = TU->getASTContext();
642
643 // Some builtin types (such as Objective-C's "id", "sel", and
644 // "Class") have associated declarations. Create cursors for those.
645 QualType VisitType;
646 switch (TL.getType()->getAs<BuiltinType>()->getKind()) {
647 case BuiltinType::Void:
648 case BuiltinType::Bool:
649 case BuiltinType::Char_U:
650 case BuiltinType::UChar:
651 case BuiltinType::Char16:
652 case BuiltinType::Char32:
653 case BuiltinType::UShort:
654 case BuiltinType::UInt:
655 case BuiltinType::ULong:
656 case BuiltinType::ULongLong:
657 case BuiltinType::UInt128:
658 case BuiltinType::Char_S:
659 case BuiltinType::SChar:
660 case BuiltinType::WChar:
661 case BuiltinType::Short:
662 case BuiltinType::Int:
663 case BuiltinType::Long:
664 case BuiltinType::LongLong:
665 case BuiltinType::Int128:
666 case BuiltinType::Float:
667 case BuiltinType::Double:
668 case BuiltinType::LongDouble:
669 case BuiltinType::NullPtr:
670 case BuiltinType::Overload:
671 case BuiltinType::Dependent:
672 break;
673
674 case BuiltinType::UndeducedAuto: // FIXME: Deserves a cursor?
675 break;
676
677 case BuiltinType::ObjCId:
678 VisitType = Context.getObjCIdType();
679 break;
680
681 case BuiltinType::ObjCClass:
682 VisitType = Context.getObjCClassType();
683 break;
684
685 case BuiltinType::ObjCSel:
686 VisitType = Context.getObjCSelType();
687 break;
688 }
689
690 if (!VisitType.isNull()) {
691 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
692 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
693 TU));
694 }
695
696 return false;
697}
698
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000699bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
700 return Visit(MakeCursorTypeRef(TL.getTypedefDecl(), TL.getNameLoc(), TU));
701}
702
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000703bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
704 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
705}
706
707bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
708 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
709}
710
711bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
712 if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
713 return true;
714
715 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
716 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
717 TU)))
718 return true;
719 }
720
721 return false;
722}
723
724bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
725 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseTypeLoc()))
726 return true;
727
728 if (TL.hasProtocolsAsWritten()) {
729 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
730 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I),
731 TL.getProtocolLoc(I),
732 TU)))
733 return true;
734 }
735 }
736
737 return false;
738}
739
740bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
741 return Visit(TL.getPointeeLoc());
742}
743
744bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
745 return Visit(TL.getPointeeLoc());
746}
747
748bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
749 return Visit(TL.getPointeeLoc());
750}
751
752bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
753 return Visit(TL.getPointeeLoc());
754}
755
756bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
757 return Visit(TL.getPointeeLoc());
758}
759
760bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
761 if (Visit(TL.getResultLoc()))
762 return true;
763
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000764 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
765 if (Visit(MakeCXCursor(TL.getArg(I), TU)))
766 return true;
767
768 return false;
769}
770
771bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
772 if (Visit(TL.getElementLoc()))
773 return true;
774
775 if (Expr *Size = TL.getSizeExpr())
776 return Visit(MakeCXCursor(Size, StmtParent, TU));
777
778 return false;
779}
780
Douglas Gregor2332c112010-01-21 20:48:56 +0000781bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
782 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
783}
784
785bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
786 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
787 return Visit(TSInfo->getTypeLoc());
788
789 return false;
790}
791
Douglas Gregora59e3902010-01-21 23:27:09 +0000792bool CursorVisitor::VisitStmt(Stmt *S) {
793 for (Stmt::child_iterator Child = S->child_begin(), ChildEnd = S->child_end();
794 Child != ChildEnd; ++Child) {
Daniel Dunbar54d67ca2010-01-25 00:40:30 +0000795 if (*Child && Visit(MakeCXCursor(*Child, StmtParent, TU)))
Douglas Gregora59e3902010-01-21 23:27:09 +0000796 return true;
797 }
798
799 return false;
800}
801
802bool CursorVisitor::VisitDeclStmt(DeclStmt *S) {
803 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
804 D != DEnd; ++D) {
Douglas Gregor263b47b2010-01-25 16:12:32 +0000805 if (*D && Visit(MakeCXCursor(*D, TU)))
Douglas Gregora59e3902010-01-21 23:27:09 +0000806 return true;
807 }
808
809 return false;
810}
811
Douglas Gregorf5bab412010-01-22 01:00:11 +0000812bool CursorVisitor::VisitIfStmt(IfStmt *S) {
813 if (VarDecl *Var = S->getConditionVariable()) {
814 if (Visit(MakeCXCursor(Var, TU)))
815 return true;
Douglas Gregor263b47b2010-01-25 16:12:32 +0000816 }
Douglas Gregorf5bab412010-01-22 01:00:11 +0000817
Douglas Gregor263b47b2010-01-25 16:12:32 +0000818 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
819 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +0000820 if (S->getThen() && Visit(MakeCXCursor(S->getThen(), StmtParent, TU)))
821 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +0000822 if (S->getElse() && Visit(MakeCXCursor(S->getElse(), StmtParent, TU)))
823 return true;
824
825 return false;
826}
827
828bool CursorVisitor::VisitSwitchStmt(SwitchStmt *S) {
829 if (VarDecl *Var = S->getConditionVariable()) {
830 if (Visit(MakeCXCursor(Var, TU)))
831 return true;
Douglas Gregor263b47b2010-01-25 16:12:32 +0000832 }
833
834 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
835 return true;
836 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
837 return true;
838
839 return false;
840}
841
842bool CursorVisitor::VisitWhileStmt(WhileStmt *S) {
843 if (VarDecl *Var = S->getConditionVariable()) {
844 if (Visit(MakeCXCursor(Var, TU)))
845 return true;
846 }
847
848 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
849 return true;
850 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
Douglas Gregorf5bab412010-01-22 01:00:11 +0000851 return true;
852
Douglas Gregor263b47b2010-01-25 16:12:32 +0000853 return false;
854}
855
856bool CursorVisitor::VisitForStmt(ForStmt *S) {
857 if (S->getInit() && Visit(MakeCXCursor(S->getInit(), StmtParent, TU)))
858 return true;
859 if (VarDecl *Var = S->getConditionVariable()) {
860 if (Visit(MakeCXCursor(Var, TU)))
861 return true;
862 }
863
864 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
865 return true;
866 if (S->getInc() && Visit(MakeCXCursor(S->getInc(), StmtParent, TU)))
867 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +0000868 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
869 return true;
870
871 return false;
872}
873
Douglas Gregor336fd812010-01-23 00:40:08 +0000874bool CursorVisitor::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E) {
875 if (E->isArgumentType()) {
876 if (TypeSourceInfo *TSInfo = E->getArgumentTypeInfo())
877 return Visit(TSInfo->getTypeLoc());
878
879 return false;
880 }
881
882 return VisitExpr(E);
883}
884
885bool CursorVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
886 if (TypeSourceInfo *TSInfo = E->getTypeInfoAsWritten())
887 if (Visit(TSInfo->getTypeLoc()))
888 return true;
889
890 return VisitCastExpr(E);
891}
892
893bool CursorVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
894 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
895 if (Visit(TSInfo->getTypeLoc()))
896 return true;
897
898 return VisitExpr(E);
899}
900
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000901extern "C" {
Douglas Gregor936ea3b2010-01-28 00:56:43 +0000902CXIndex clang_createIndex(int excludeDeclarationsFromPCH) {
Douglas Gregora030b7c2010-01-22 20:35:53 +0000903 CIndexer *CIdxr = new CIndexer();
Steve Naroffe56b4ba2009-10-20 14:46:24 +0000904 if (excludeDeclarationsFromPCH)
905 CIdxr->setOnlyLocalDecls();
Steve Naroffe56b4ba2009-10-20 14:46:24 +0000906 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +0000907}
908
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000909void clang_disposeIndex(CXIndex CIdx) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +0000910 if (CIdx)
911 delete static_cast<CIndexer *>(CIdx);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +0000912}
913
Daniel Dunbar8506dde2009-12-03 01:54:28 +0000914void clang_setUseExternalASTGeneration(CXIndex CIdx, int value) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +0000915 if (CIdx) {
916 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
917 CXXIdx->setUseExternalASTGeneration(value);
918 }
Daniel Dunbar8506dde2009-12-03 01:54:28 +0000919}
920
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000921CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
Douglas Gregor5352ac02010-01-28 00:27:43 +0000922 const char *ast_filename,
923 CXDiagnosticCallback diag_callback,
924 CXClientData diag_client_data) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +0000925 if (!CIdx)
926 return 0;
927
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000928 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000929
Douglas Gregor5352ac02010-01-28 00:27:43 +0000930 // Configure the diagnostics.
931 DiagnosticOptions DiagOpts;
932 llvm::OwningPtr<Diagnostic> Diags;
933 Diags.reset(CompilerInstance::createDiagnostics(DiagOpts, 0, 0));
934 CIndexDiagnosticClient DiagClient(diag_callback, diag_client_data);
935 Diags->setClient(&DiagClient);
936
937 return ASTUnit::LoadFromPCHFile(ast_filename, *Diags,
Daniel Dunbarb26d4832010-02-16 01:55:04 +0000938 CXXIdx->getOnlyLocalDecls());
Steve Naroff600866c2009-08-27 19:51:58 +0000939}
940
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000941CXTranslationUnit
942clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
943 const char *source_filename,
944 int num_command_line_args,
Douglas Gregor4db64a42010-01-23 00:14:00 +0000945 const char **command_line_args,
946 unsigned num_unsaved_files,
Douglas Gregor5352ac02010-01-28 00:27:43 +0000947 struct CXUnsavedFile *unsaved_files,
948 CXDiagnosticCallback diag_callback,
949 CXClientData diag_client_data) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +0000950 if (!CIdx)
951 return 0;
952
Steve Naroffe56b4ba2009-10-20 14:46:24 +0000953 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
954
Douglas Gregor5352ac02010-01-28 00:27:43 +0000955 // Configure the diagnostics.
956 DiagnosticOptions DiagOpts;
957 llvm::OwningPtr<Diagnostic> Diags;
958 Diags.reset(CompilerInstance::createDiagnostics(DiagOpts, 0, 0));
959 CIndexDiagnosticClient DiagClient(diag_callback, diag_client_data);
960 Diags->setClient(&DiagClient);
961
Douglas Gregor4db64a42010-01-23 00:14:00 +0000962 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
963 for (unsigned I = 0; I != num_unsaved_files; ++I) {
964 const llvm::MemoryBuffer *Buffer
965 = llvm::MemoryBuffer::getMemBuffer(unsaved_files[I].Contents,
966 unsaved_files[I].Contents + unsaved_files[I].Length,
967 unsaved_files[I].Filename);
968 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
969 Buffer));
970 }
971
Daniel Dunbar8506dde2009-12-03 01:54:28 +0000972 if (!CXXIdx->getUseExternalASTGeneration()) {
973 llvm::SmallVector<const char *, 16> Args;
974
975 // The 'source_filename' argument is optional. If the caller does not
976 // specify it then it is assumed that the source file is specified
977 // in the actual argument list.
978 if (source_filename)
979 Args.push_back(source_filename);
980 Args.insert(Args.end(), command_line_args,
981 command_line_args + num_command_line_args);
982
Douglas Gregor5352ac02010-01-28 00:27:43 +0000983 unsigned NumErrors = Diags->getNumErrors();
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000984
Ted Kremenek29b72842010-01-07 22:49:05 +0000985#ifdef USE_CRASHTRACER
986 ArgsCrashTracerInfo ACTI(Args);
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000987#endif
988
Daniel Dunbar94220972009-12-05 02:17:18 +0000989 llvm::OwningPtr<ASTUnit> Unit(
990 ASTUnit::LoadFromCommandLine(Args.data(), Args.data() + Args.size(),
Douglas Gregor5352ac02010-01-28 00:27:43 +0000991 *Diags,
Daniel Dunbar869824e2009-12-13 03:46:13 +0000992 CXXIdx->getClangResourcesPath(),
Daniel Dunbar94220972009-12-05 02:17:18 +0000993 CXXIdx->getOnlyLocalDecls(),
Douglas Gregor4db64a42010-01-23 00:14:00 +0000994 RemappedFiles.data(),
995 RemappedFiles.size()));
Ted Kremenek29b72842010-01-07 22:49:05 +0000996
Daniel Dunbar94220972009-12-05 02:17:18 +0000997 // FIXME: Until we have broader testing, just drop the entire AST if we
998 // encountered an error.
Douglas Gregor5352ac02010-01-28 00:27:43 +0000999 if (NumErrors != Diags->getNumErrors())
Daniel Dunbar94220972009-12-05 02:17:18 +00001000 return 0;
1001
1002 return Unit.take();
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001003 }
1004
Ted Kremenek139ba862009-10-22 00:03:57 +00001005 // Build up the arguments for invoking 'clang'.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001006 std::vector<const char *> argv;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001007
Ted Kremenek139ba862009-10-22 00:03:57 +00001008 // First add the complete path to the 'clang' executable.
1009 llvm::sys::Path ClangPath = static_cast<CIndexer *>(CIdx)->getClangPath();
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00001010 argv.push_back(ClangPath.c_str());
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001011
Ted Kremenek139ba862009-10-22 00:03:57 +00001012 // Add the '-emit-ast' option as our execution mode for 'clang'.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001013 argv.push_back("-emit-ast");
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001014
Ted Kremenek139ba862009-10-22 00:03:57 +00001015 // The 'source_filename' argument is optional. If the caller does not
1016 // specify it then it is assumed that the source file is specified
1017 // in the actual argument list.
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001018 if (source_filename)
1019 argv.push_back(source_filename);
Ted Kremenek139ba862009-10-22 00:03:57 +00001020
Steve Naroff37b5ac22009-10-15 20:50:09 +00001021 // Generate a temporary name for the AST file.
Ted Kremenek139ba862009-10-22 00:03:57 +00001022 argv.push_back("-o");
Steve Naroff37b5ac22009-10-15 20:50:09 +00001023 char astTmpFile[L_tmpnam];
Ted Kremenek74cd0692009-10-15 23:21:22 +00001024 argv.push_back(tmpnam(astTmpFile));
Ted Kremenek139ba862009-10-22 00:03:57 +00001025
Douglas Gregor4db64a42010-01-23 00:14:00 +00001026 // Remap any unsaved files to temporary files.
1027 std::vector<llvm::sys::Path> TemporaryFiles;
1028 std::vector<std::string> RemapArgs;
1029 if (RemapFiles(num_unsaved_files, unsaved_files, RemapArgs, TemporaryFiles))
1030 return 0;
1031
1032 // The pointers into the elements of RemapArgs are stable because we
1033 // won't be adding anything to RemapArgs after this point.
1034 for (unsigned i = 0, e = RemapArgs.size(); i != e; ++i)
1035 argv.push_back(RemapArgs[i].c_str());
1036
Ted Kremenek139ba862009-10-22 00:03:57 +00001037 // Process the compiler options, stripping off '-o', '-c', '-fsyntax-only'.
1038 for (int i = 0; i < num_command_line_args; ++i)
1039 if (const char *arg = command_line_args[i]) {
1040 if (strcmp(arg, "-o") == 0) {
1041 ++i; // Also skip the matching argument.
1042 continue;
1043 }
1044 if (strcmp(arg, "-emit-ast") == 0 ||
1045 strcmp(arg, "-c") == 0 ||
1046 strcmp(arg, "-fsyntax-only") == 0) {
1047 continue;
1048 }
1049
1050 // Keep the argument.
1051 argv.push_back(arg);
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001052 }
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001053
Douglas Gregord93256e2010-01-28 06:00:51 +00001054 // Generate a temporary name for the diagnostics file.
1055 char tmpFileResults[L_tmpnam];
1056 char *tmpResultsFileName = tmpnam(tmpFileResults);
1057 llvm::sys::Path DiagnosticsFile(tmpResultsFileName);
1058 TemporaryFiles.push_back(DiagnosticsFile);
1059 argv.push_back("-fdiagnostics-binary");
1060
Ted Kremenek139ba862009-10-22 00:03:57 +00001061 // Add the null terminator.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001062 argv.push_back(NULL);
1063
Ted Kremenekfeb15e32009-10-26 22:14:08 +00001064 // Invoke 'clang'.
1065 llvm::sys::Path DevNull; // leave empty, causes redirection to /dev/null
1066 // on Unix or NUL (Windows).
Ted Kremenek379afec2009-10-22 03:24:01 +00001067 std::string ErrMsg;
Douglas Gregord93256e2010-01-28 06:00:51 +00001068 const llvm::sys::Path *Redirects[] = { &DevNull, &DevNull, &DiagnosticsFile,
1069 NULL };
Ted Kremenek379afec2009-10-22 03:24:01 +00001070 llvm::sys::Program::ExecuteAndWait(ClangPath, &argv[0], /* env */ NULL,
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001071 /* redirects */ &Redirects[0],
Ted Kremenek379afec2009-10-22 03:24:01 +00001072 /* secondsToWait */ 0, /* memoryLimits */ 0, &ErrMsg);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001073
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001074 if (!ErrMsg.empty()) {
1075 std::string AllArgs;
Ted Kremenek379afec2009-10-22 03:24:01 +00001076 for (std::vector<const char*>::iterator I = argv.begin(), E = argv.end();
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001077 I != E; ++I) {
1078 AllArgs += ' ';
Ted Kremenek779e5f42009-10-26 22:08:39 +00001079 if (*I)
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001080 AllArgs += *I;
Ted Kremenek779e5f42009-10-26 22:08:39 +00001081 }
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001082
1083 Diags->Report(diag::err_fe_clang) << AllArgs << ErrMsg;
Ted Kremenek379afec2009-10-22 03:24:01 +00001084 }
Benjamin Kramer0829a832009-10-18 11:19:36 +00001085
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001086 // FIXME: Parse the (redirected) standard error to emit diagnostics.
1087
Douglas Gregor5352ac02010-01-28 00:27:43 +00001088 ASTUnit *ATU = ASTUnit::LoadFromPCHFile(astTmpFile, *Diags,
Douglas Gregor4db64a42010-01-23 00:14:00 +00001089 CXXIdx->getOnlyLocalDecls(),
Douglas Gregor4db64a42010-01-23 00:14:00 +00001090 RemappedFiles.data(),
1091 RemappedFiles.size());
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001092 if (ATU)
1093 ATU->unlinkTemporaryFile();
Douglas Gregor4db64a42010-01-23 00:14:00 +00001094
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00001095 // FIXME: Currently we don't report diagnostics on invalid ASTs.
1096 if (ATU)
1097 ReportSerializedDiagnostics(DiagnosticsFile, *Diags,
1098 num_unsaved_files, unsaved_files,
1099 ATU->getASTContext().getLangOptions());
Douglas Gregord93256e2010-01-28 06:00:51 +00001100
Douglas Gregor4db64a42010-01-23 00:14:00 +00001101 for (unsigned i = 0, e = TemporaryFiles.size(); i != e; ++i)
1102 TemporaryFiles[i].eraseFromDisk();
1103
Steve Naroffe19944c2009-10-15 22:23:48 +00001104 return ATU;
Steve Naroff5b7d8e22009-10-15 20:04:39 +00001105}
1106
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001107void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001108 if (CTUnit)
1109 delete static_cast<ASTUnit *>(CTUnit);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00001110}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001111
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001112CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001113 if (!CTUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001114 return createCXString("");
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001115
Steve Naroff77accc12009-09-03 18:19:54 +00001116 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001117 return createCXString(CXXUnit->getOriginalSourceFileName(), true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +00001118}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +00001119
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001120CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001121 CXCursor Result = { CXCursor_TranslationUnit, { 0, 0, TU } };
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001122 return Result;
1123}
1124
Ted Kremenekfb480492010-01-13 21:46:36 +00001125} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +00001126
Ted Kremenekfb480492010-01-13 21:46:36 +00001127//===----------------------------------------------------------------------===//
Douglas Gregor1db19de2010-01-19 21:36:55 +00001128// CXSourceLocation and CXSourceRange Operations.
1129//===----------------------------------------------------------------------===//
1130
Douglas Gregorb9790342010-01-22 21:44:22 +00001131extern "C" {
1132CXSourceLocation clang_getNullLocation() {
Douglas Gregor5352ac02010-01-28 00:27:43 +00001133 CXSourceLocation Result = { { 0, 0 }, 0 };
Douglas Gregorb9790342010-01-22 21:44:22 +00001134 return Result;
1135}
1136
1137unsigned clang_equalLocations(CXSourceLocation loc1, CXSourceLocation loc2) {
Daniel Dunbar90a6b9e2010-01-30 23:58:27 +00001138 return (loc1.ptr_data[0] == loc2.ptr_data[0] &&
1139 loc1.ptr_data[1] == loc2.ptr_data[1] &&
1140 loc1.int_data == loc2.int_data);
Douglas Gregorb9790342010-01-22 21:44:22 +00001141}
1142
1143CXSourceLocation clang_getLocation(CXTranslationUnit tu,
1144 CXFile file,
1145 unsigned line,
1146 unsigned column) {
1147 if (!tu)
1148 return clang_getNullLocation();
1149
1150 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
1151 SourceLocation SLoc
1152 = CXXUnit->getSourceManager().getLocation(
1153 static_cast<const FileEntry *>(file),
1154 line, column);
1155
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00001156 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
Douglas Gregorb9790342010-01-22 21:44:22 +00001157}
1158
Douglas Gregor5352ac02010-01-28 00:27:43 +00001159CXSourceRange clang_getNullRange() {
1160 CXSourceRange Result = { { 0, 0 }, 0, 0 };
1161 return Result;
1162}
Daniel Dunbard52864b2010-02-14 10:02:57 +00001163
Douglas Gregor5352ac02010-01-28 00:27:43 +00001164CXSourceRange clang_getRange(CXSourceLocation begin, CXSourceLocation end) {
1165 if (begin.ptr_data[0] != end.ptr_data[0] ||
1166 begin.ptr_data[1] != end.ptr_data[1])
1167 return clang_getNullRange();
1168
1169 CXSourceRange Result = { { begin.ptr_data[0], begin.ptr_data[1] },
1170 begin.int_data, end.int_data };
Douglas Gregorb9790342010-01-22 21:44:22 +00001171 return Result;
1172}
1173
Douglas Gregor46766dc2010-01-26 19:19:08 +00001174void clang_getInstantiationLocation(CXSourceLocation location,
1175 CXFile *file,
1176 unsigned *line,
1177 unsigned *column,
1178 unsigned *offset) {
Douglas Gregor1db19de2010-01-19 21:36:55 +00001179 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
1180
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00001181 if (!location.ptr_data[0] || Loc.isInvalid()) {
Douglas Gregor46766dc2010-01-26 19:19:08 +00001182 if (file)
1183 *file = 0;
1184 if (line)
1185 *line = 0;
1186 if (column)
1187 *column = 0;
1188 if (offset)
1189 *offset = 0;
1190 return;
1191 }
1192
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00001193 const SourceManager &SM =
1194 *static_cast<const SourceManager*>(location.ptr_data[0]);
Douglas Gregor1db19de2010-01-19 21:36:55 +00001195 SourceLocation InstLoc = SM.getInstantiationLoc(Loc);
Douglas Gregor1db19de2010-01-19 21:36:55 +00001196
1197 if (file)
1198 *file = (void *)SM.getFileEntryForID(SM.getFileID(InstLoc));
1199 if (line)
1200 *line = SM.getInstantiationLineNumber(InstLoc);
1201 if (column)
1202 *column = SM.getInstantiationColumnNumber(InstLoc);
Douglas Gregore69517c2010-01-26 03:07:15 +00001203 if (offset)
Douglas Gregor46766dc2010-01-26 19:19:08 +00001204 *offset = SM.getDecomposedLoc(InstLoc).second;
Douglas Gregore69517c2010-01-26 03:07:15 +00001205}
1206
Douglas Gregor1db19de2010-01-19 21:36:55 +00001207CXSourceLocation clang_getRangeStart(CXSourceRange range) {
Douglas Gregor5352ac02010-01-28 00:27:43 +00001208 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
1209 range.begin_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00001210 return Result;
1211}
1212
1213CXSourceLocation clang_getRangeEnd(CXSourceRange range) {
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00001214 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00001215 range.end_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00001216 return Result;
1217}
1218
Douglas Gregorb9790342010-01-22 21:44:22 +00001219} // end: extern "C"
1220
Douglas Gregor1db19de2010-01-19 21:36:55 +00001221//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00001222// CXFile Operations.
1223//===----------------------------------------------------------------------===//
1224
1225extern "C" {
Ted Kremenek74844072010-02-17 00:41:20 +00001226CXString clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00001227 if (!SFile)
Ted Kremenek74844072010-02-17 00:41:20 +00001228 return createCXString(NULL);
Douglas Gregor98258af2010-01-18 22:46:11 +00001229
Steve Naroff88145032009-10-27 14:35:18 +00001230 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Ted Kremenek74844072010-02-17 00:41:20 +00001231 return createCXString(FEnt->getName());
Steve Naroff88145032009-10-27 14:35:18 +00001232}
1233
1234time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00001235 if (!SFile)
1236 return 0;
1237
Steve Naroff88145032009-10-27 14:35:18 +00001238 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
1239 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +00001240}
Douglas Gregorb9790342010-01-22 21:44:22 +00001241
1242CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
1243 if (!tu)
1244 return 0;
1245
1246 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
1247
1248 FileManager &FMgr = CXXUnit->getFileManager();
1249 const FileEntry *File = FMgr.getFile(file_name, file_name+strlen(file_name));
1250 return const_cast<FileEntry *>(File);
1251}
1252
Ted Kremenekfb480492010-01-13 21:46:36 +00001253} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +00001254
Ted Kremenekfb480492010-01-13 21:46:36 +00001255//===----------------------------------------------------------------------===//
1256// CXCursor Operations.
1257//===----------------------------------------------------------------------===//
1258
Ted Kremenekfb480492010-01-13 21:46:36 +00001259static Decl *getDeclFromExpr(Stmt *E) {
1260 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
1261 return RefExpr->getDecl();
1262 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
1263 return ME->getMemberDecl();
1264 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
1265 return RE->getDecl();
1266
1267 if (CallExpr *CE = dyn_cast<CallExpr>(E))
1268 return getDeclFromExpr(CE->getCallee());
1269 if (CastExpr *CE = dyn_cast<CastExpr>(E))
1270 return getDeclFromExpr(CE->getSubExpr());
1271 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
1272 return OME->getMethodDecl();
1273
1274 return 0;
1275}
1276
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00001277static SourceLocation getLocationFromExpr(Expr *E) {
1278 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
1279 return /*FIXME:*/Msg->getLeftLoc();
1280 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
1281 return DRE->getLocation();
1282 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
1283 return Member->getMemberLoc();
1284 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
1285 return Ivar->getLocation();
1286 return E->getLocStart();
1287}
1288
Ted Kremenekfb480492010-01-13 21:46:36 +00001289extern "C" {
Douglas Gregorb1373d02010-01-20 20:59:29 +00001290
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001291unsigned clang_visitChildren(CXCursor parent,
Douglas Gregorb1373d02010-01-20 20:59:29 +00001292 CXCursorVisitor visitor,
1293 CXClientData client_data) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001294 ASTUnit *CXXUnit = getCursorASTUnit(parent);
Douglas Gregorb1373d02010-01-20 20:59:29 +00001295
1296 unsigned PCHLevel = Decl::MaxPCHLevel;
1297
1298 // Set the PCHLevel to filter out unwanted decls if requested.
1299 if (CXXUnit->getOnlyLocalDecls()) {
1300 PCHLevel = 0;
1301
1302 // If the main input was an AST, bump the level.
1303 if (CXXUnit->isMainFileAST())
1304 ++PCHLevel;
1305 }
1306
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001307 CursorVisitor CursorVis(CXXUnit, visitor, client_data, PCHLevel);
Douglas Gregorb1373d02010-01-20 20:59:29 +00001308 return CursorVis.VisitChildren(parent);
1309}
1310
Douglas Gregor78205d42010-01-20 21:45:58 +00001311static CXString getDeclSpelling(Decl *D) {
1312 NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
1313 if (!ND)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001314 return createCXString("");
Douglas Gregor78205d42010-01-20 21:45:58 +00001315
1316 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001317 return createCXString(OMD->getSelector().getAsString());
Douglas Gregor78205d42010-01-20 21:45:58 +00001318
1319 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
1320 // No, this isn't the same as the code below. getIdentifier() is non-virtual
1321 // and returns different names. NamedDecl returns the class name and
1322 // ObjCCategoryImplDecl returns the category name.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001323 return createCXString(CIMP->getIdentifier()->getNameStart());
Douglas Gregor78205d42010-01-20 21:45:58 +00001324
1325 if (ND->getIdentifier())
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001326 return createCXString(ND->getIdentifier()->getNameStart());
Douglas Gregor78205d42010-01-20 21:45:58 +00001327
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001328 return createCXString("");
Douglas Gregor78205d42010-01-20 21:45:58 +00001329}
1330
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001331CXString clang_getCursorSpelling(CXCursor C) {
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001332 if (clang_isTranslationUnit(C.kind))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001333 return clang_getTranslationUnitSpelling(C.data[2]);
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001334
Steve Narofff334b4e2009-09-02 18:26:48 +00001335 if (clang_isReference(C.kind)) {
1336 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00001337 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +00001338 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001339 return createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00001340 }
1341 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +00001342 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001343 return createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00001344 }
1345 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +00001346 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +00001347 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001348 return createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00001349 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001350 case CXCursor_TypeRef: {
1351 TypeDecl *Type = getCursorTypeRef(C).first;
1352 assert(Type && "Missing type decl");
1353
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001354 return createCXString(getCursorContext(C).getTypeDeclType(Type).
1355 getAsString());
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001356 }
1357
Daniel Dunbaracca7252009-11-30 20:42:49 +00001358 default:
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001359 return createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +00001360 }
1361 }
Douglas Gregor97b98722010-01-19 23:20:36 +00001362
1363 if (clang_isExpression(C.kind)) {
1364 Decl *D = getDeclFromExpr(getCursorExpr(C));
1365 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +00001366 return getDeclSpelling(D);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001367 return createCXString("");
Douglas Gregor97b98722010-01-19 23:20:36 +00001368 }
1369
Douglas Gregor60cbfac2010-01-25 16:56:17 +00001370 if (clang_isDeclaration(C.kind))
1371 return getDeclSpelling(getCursorDecl(C));
1372
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001373 return createCXString("");
Steve Narofff334b4e2009-09-02 18:26:48 +00001374}
1375
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001376const char *clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00001377 switch (Kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00001378 case CXCursor_FunctionDecl: return "FunctionDecl";
1379 case CXCursor_TypedefDecl: return "TypedefDecl";
1380 case CXCursor_EnumDecl: return "EnumDecl";
1381 case CXCursor_EnumConstantDecl: return "EnumConstantDecl";
1382 case CXCursor_StructDecl: return "StructDecl";
1383 case CXCursor_UnionDecl: return "UnionDecl";
1384 case CXCursor_ClassDecl: return "ClassDecl";
1385 case CXCursor_FieldDecl: return "FieldDecl";
1386 case CXCursor_VarDecl: return "VarDecl";
1387 case CXCursor_ParmDecl: return "ParmDecl";
1388 case CXCursor_ObjCInterfaceDecl: return "ObjCInterfaceDecl";
1389 case CXCursor_ObjCCategoryDecl: return "ObjCCategoryDecl";
1390 case CXCursor_ObjCProtocolDecl: return "ObjCProtocolDecl";
1391 case CXCursor_ObjCPropertyDecl: return "ObjCPropertyDecl";
1392 case CXCursor_ObjCIvarDecl: return "ObjCIvarDecl";
1393 case CXCursor_ObjCInstanceMethodDecl: return "ObjCInstanceMethodDecl";
1394 case CXCursor_ObjCClassMethodDecl: return "ObjCClassMethodDecl";
Douglas Gregorb6998662010-01-19 19:34:47 +00001395 case CXCursor_ObjCImplementationDecl: return "ObjCImplementationDecl";
1396 case CXCursor_ObjCCategoryImplDecl: return "ObjCCategoryImplDecl";
Douglas Gregor30122132010-01-19 22:07:56 +00001397 case CXCursor_UnexposedDecl: return "UnexposedDecl";
Daniel Dunbaracca7252009-11-30 20:42:49 +00001398 case CXCursor_ObjCSuperClassRef: return "ObjCSuperClassRef";
1399 case CXCursor_ObjCProtocolRef: return "ObjCProtocolRef";
1400 case CXCursor_ObjCClassRef: return "ObjCClassRef";
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001401 case CXCursor_TypeRef: return "TypeRef";
Douglas Gregor97b98722010-01-19 23:20:36 +00001402 case CXCursor_UnexposedExpr: return "UnexposedExpr";
1403 case CXCursor_DeclRefExpr: return "DeclRefExpr";
1404 case CXCursor_MemberRefExpr: return "MemberRefExpr";
1405 case CXCursor_CallExpr: return "CallExpr";
1406 case CXCursor_ObjCMessageExpr: return "ObjCMessageExpr";
1407 case CXCursor_UnexposedStmt: return "UnexposedStmt";
Daniel Dunbaracca7252009-11-30 20:42:49 +00001408 case CXCursor_InvalidFile: return "InvalidFile";
1409 case CXCursor_NoDeclFound: return "NoDeclFound";
1410 case CXCursor_NotImplemented: return "NotImplemented";
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001411 case CXCursor_TranslationUnit: return "TranslationUnit";
Steve Naroff89922f82009-08-31 00:59:03 +00001412 }
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00001413
1414 llvm_unreachable("Unhandled CXCursorKind");
1415 return NULL;
Steve Naroff600866c2009-08-27 19:51:58 +00001416}
Steve Naroff89922f82009-08-31 00:59:03 +00001417
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001418enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
1419 CXCursor parent,
1420 CXClientData client_data) {
1421 CXCursor *BestCursor = static_cast<CXCursor *>(client_data);
1422 *BestCursor = cursor;
1423 return CXChildVisit_Recurse;
1424}
1425
Douglas Gregorb9790342010-01-22 21:44:22 +00001426CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
1427 if (!TU)
Ted Kremenekf4629892010-01-14 01:51:23 +00001428 return clang_getNullCursor();
Ted Kremenekf4629892010-01-14 01:51:23 +00001429
Douglas Gregorb9790342010-01-22 21:44:22 +00001430 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
1431
Ted Kremeneka297de22010-01-25 22:34:44 +00001432 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001433 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
1434 if (SLoc.isValid()) {
Daniel Dunbard52864b2010-02-14 10:02:57 +00001435 SourceRange RegionOfInterest(SLoc, SLoc.getFileLocWithOffset(1));
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001436
1437 // FIXME: Would be great to have a "hint" cursor, then walk from that
1438 // hint cursor upward until we find a cursor whose source range encloses
1439 // the region of interest, rather than starting from the translation unit.
1440 CXCursor Parent = clang_getTranslationUnitCursor(CXXUnit);
1441 CursorVisitor CursorVis(CXXUnit, GetCursorVisitor, &Result,
1442 Decl::MaxPCHLevel, RegionOfInterest);
1443 CursorVis.VisitChildren(Parent);
Steve Naroff77128dd2009-09-15 20:25:34 +00001444 }
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001445 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00001446}
1447
Ted Kremenek73885552009-11-17 19:28:59 +00001448CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00001449 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00001450}
1451
1452unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00001453 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00001454}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001455
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001456unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00001457 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
1458}
1459
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001460unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +00001461 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
1462}
Steve Naroff2d4d6292009-08-31 14:26:51 +00001463
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001464unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00001465 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
1466}
1467
Douglas Gregor97b98722010-01-19 23:20:36 +00001468unsigned clang_isExpression(enum CXCursorKind K) {
1469 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
1470}
1471
1472unsigned clang_isStatement(enum CXCursorKind K) {
1473 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
1474}
1475
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001476unsigned clang_isTranslationUnit(enum CXCursorKind K) {
1477 return K == CXCursor_TranslationUnit;
1478}
1479
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001480CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00001481 return C.kind;
1482}
1483
Douglas Gregor98258af2010-01-18 22:46:11 +00001484CXSourceLocation clang_getCursorLocation(CXCursor C) {
1485 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00001486 switch (C.kind) {
1487 case CXCursor_ObjCSuperClassRef: {
1488 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1489 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001490 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001491 }
1492
1493 case CXCursor_ObjCProtocolRef: {
1494 std::pair<ObjCProtocolDecl *, SourceLocation> P
1495 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001496 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001497 }
1498
1499 case CXCursor_ObjCClassRef: {
1500 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1501 = getCursorObjCClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001502 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001503 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001504
1505 case CXCursor_TypeRef: {
1506 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001507 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001508 }
Douglas Gregorf46034a2010-01-18 23:41:10 +00001509
Douglas Gregorf46034a2010-01-18 23:41:10 +00001510 default:
1511 // FIXME: Need a way to enumerate all non-reference cases.
1512 llvm_unreachable("Missed a reference kind");
1513 }
Douglas Gregor98258af2010-01-18 22:46:11 +00001514 }
Douglas Gregor97b98722010-01-19 23:20:36 +00001515
1516 if (clang_isExpression(C.kind))
Ted Kremeneka297de22010-01-25 22:34:44 +00001517 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00001518 getLocationFromExpr(getCursorExpr(C)));
1519
Douglas Gregor5352ac02010-01-28 00:27:43 +00001520 if (!getCursorDecl(C))
1521 return clang_getNullLocation();
Douglas Gregor98258af2010-01-18 22:46:11 +00001522
Douglas Gregorf46034a2010-01-18 23:41:10 +00001523 Decl *D = getCursorDecl(C);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001524 SourceLocation Loc = D->getLocation();
1525 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
1526 Loc = Class->getClassLoc();
Ted Kremeneka297de22010-01-25 22:34:44 +00001527 return cxloc::translateSourceLocation(D->getASTContext(), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00001528}
Douglas Gregora7bde202010-01-19 00:34:46 +00001529
1530CXSourceRange clang_getCursorExtent(CXCursor C) {
1531 if (clang_isReference(C.kind)) {
1532 switch (C.kind) {
1533 case CXCursor_ObjCSuperClassRef: {
1534 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1535 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001536 return cxloc::translateSourceRange(P.first->getASTContext(), P.second);
Douglas Gregora7bde202010-01-19 00:34:46 +00001537 }
1538
1539 case CXCursor_ObjCProtocolRef: {
1540 std::pair<ObjCProtocolDecl *, SourceLocation> P
1541 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001542 return cxloc::translateSourceRange(P.first->getASTContext(), P.second);
Douglas Gregora7bde202010-01-19 00:34:46 +00001543 }
1544
1545 case CXCursor_ObjCClassRef: {
1546 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1547 = getCursorObjCClassRef(C);
1548
Ted Kremeneka297de22010-01-25 22:34:44 +00001549 return cxloc::translateSourceRange(P.first->getASTContext(), P.second);
Douglas Gregora7bde202010-01-19 00:34:46 +00001550 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001551
1552 case CXCursor_TypeRef: {
1553 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001554 return cxloc::translateSourceRange(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001555 }
Douglas Gregora7bde202010-01-19 00:34:46 +00001556
Douglas Gregora7bde202010-01-19 00:34:46 +00001557 default:
1558 // FIXME: Need a way to enumerate all non-reference cases.
1559 llvm_unreachable("Missed a reference kind");
1560 }
1561 }
Douglas Gregor97b98722010-01-19 23:20:36 +00001562
1563 if (clang_isExpression(C.kind))
Ted Kremeneka297de22010-01-25 22:34:44 +00001564 return cxloc::translateSourceRange(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00001565 getCursorExpr(C)->getSourceRange());
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001566
1567 if (clang_isStatement(C.kind))
Ted Kremeneka297de22010-01-25 22:34:44 +00001568 return cxloc::translateSourceRange(getCursorContext(C),
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001569 getCursorStmt(C)->getSourceRange());
Douglas Gregora7bde202010-01-19 00:34:46 +00001570
Douglas Gregor5352ac02010-01-28 00:27:43 +00001571 if (!getCursorDecl(C))
1572 return clang_getNullRange();
Douglas Gregora7bde202010-01-19 00:34:46 +00001573
1574 Decl *D = getCursorDecl(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001575 return cxloc::translateSourceRange(D->getASTContext(), D->getSourceRange());
Douglas Gregora7bde202010-01-19 00:34:46 +00001576}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001577
1578CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001579 if (clang_isInvalid(C.kind))
1580 return clang_getNullCursor();
1581
1582 ASTUnit *CXXUnit = getCursorASTUnit(C);
Douglas Gregorb6998662010-01-19 19:34:47 +00001583 if (clang_isDeclaration(C.kind))
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001584 return C;
Douglas Gregor98258af2010-01-18 22:46:11 +00001585
Douglas Gregor97b98722010-01-19 23:20:36 +00001586 if (clang_isExpression(C.kind)) {
1587 Decl *D = getDeclFromExpr(getCursorExpr(C));
1588 if (D)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001589 return MakeCXCursor(D, CXXUnit);
Douglas Gregor97b98722010-01-19 23:20:36 +00001590 return clang_getNullCursor();
1591 }
1592
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001593 if (!clang_isReference(C.kind))
1594 return clang_getNullCursor();
1595
1596 switch (C.kind) {
1597 case CXCursor_ObjCSuperClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001598 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, CXXUnit);
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001599
1600 case CXCursor_ObjCProtocolRef: {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001601 return MakeCXCursor(getCursorObjCProtocolRef(C).first, CXXUnit);
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001602
1603 case CXCursor_ObjCClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001604 return MakeCXCursor(getCursorObjCClassRef(C).first, CXXUnit);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001605
1606 case CXCursor_TypeRef:
1607 return MakeCXCursor(getCursorTypeRef(C).first, CXXUnit);
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001608
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001609 default:
1610 // We would prefer to enumerate all non-reference cursor kinds here.
1611 llvm_unreachable("Unhandled reference cursor kind");
1612 break;
1613 }
1614 }
1615
1616 return clang_getNullCursor();
1617}
1618
Douglas Gregorb6998662010-01-19 19:34:47 +00001619CXCursor clang_getCursorDefinition(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);
1624
Douglas Gregorb6998662010-01-19 19:34:47 +00001625 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00001626 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00001627 C = clang_getCursorReferenced(C);
1628 WasReference = true;
1629 }
1630
1631 if (!clang_isDeclaration(C.kind))
1632 return clang_getNullCursor();
1633
1634 Decl *D = getCursorDecl(C);
1635 if (!D)
1636 return clang_getNullCursor();
1637
1638 switch (D->getKind()) {
1639 // Declaration kinds that don't really separate the notions of
1640 // declaration and definition.
1641 case Decl::Namespace:
1642 case Decl::Typedef:
1643 case Decl::TemplateTypeParm:
1644 case Decl::EnumConstant:
1645 case Decl::Field:
1646 case Decl::ObjCIvar:
1647 case Decl::ObjCAtDefsField:
1648 case Decl::ImplicitParam:
1649 case Decl::ParmVar:
1650 case Decl::NonTypeTemplateParm:
1651 case Decl::TemplateTemplateParm:
1652 case Decl::ObjCCategoryImpl:
1653 case Decl::ObjCImplementation:
1654 case Decl::LinkageSpec:
1655 case Decl::ObjCPropertyImpl:
1656 case Decl::FileScopeAsm:
1657 case Decl::StaticAssert:
1658 case Decl::Block:
1659 return C;
1660
1661 // Declaration kinds that don't make any sense here, but are
1662 // nonetheless harmless.
1663 case Decl::TranslationUnit:
1664 case Decl::Template:
1665 case Decl::ObjCContainer:
1666 break;
1667
1668 // Declaration kinds for which the definition is not resolvable.
1669 case Decl::UnresolvedUsingTypename:
1670 case Decl::UnresolvedUsingValue:
1671 break;
1672
1673 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001674 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
1675 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001676
1677 case Decl::NamespaceAlias:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001678 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001679
1680 case Decl::Enum:
1681 case Decl::Record:
1682 case Decl::CXXRecord:
1683 case Decl::ClassTemplateSpecialization:
1684 case Decl::ClassTemplatePartialSpecialization:
Douglas Gregor952b0172010-02-11 01:04:33 +00001685 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001686 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001687 return clang_getNullCursor();
1688
1689 case Decl::Function:
1690 case Decl::CXXMethod:
1691 case Decl::CXXConstructor:
1692 case Decl::CXXDestructor:
1693 case Decl::CXXConversion: {
1694 const FunctionDecl *Def = 0;
1695 if (cast<FunctionDecl>(D)->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001696 return MakeCXCursor(const_cast<FunctionDecl *>(Def), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001697 return clang_getNullCursor();
1698 }
1699
1700 case Decl::Var: {
Sebastian Redl31310a22010-02-01 20:16:42 +00001701 // Ask the variable if it has a definition.
1702 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
1703 return MakeCXCursor(Def, CXXUnit);
1704 return clang_getNullCursor();
Douglas Gregorb6998662010-01-19 19:34:47 +00001705 }
1706
1707 case Decl::FunctionTemplate: {
1708 const FunctionDecl *Def = 0;
1709 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001710 return MakeCXCursor(Def->getDescribedFunctionTemplate(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001711 return clang_getNullCursor();
1712 }
1713
1714 case Decl::ClassTemplate: {
1715 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
Douglas Gregor952b0172010-02-11 01:04:33 +00001716 ->getDefinition())
Douglas Gregorb6998662010-01-19 19:34:47 +00001717 return MakeCXCursor(
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001718 cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
1719 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001720 return clang_getNullCursor();
1721 }
1722
1723 case Decl::Using: {
1724 UsingDecl *Using = cast<UsingDecl>(D);
1725 CXCursor Def = clang_getNullCursor();
1726 for (UsingDecl::shadow_iterator S = Using->shadow_begin(),
1727 SEnd = Using->shadow_end();
1728 S != SEnd; ++S) {
1729 if (Def != clang_getNullCursor()) {
1730 // FIXME: We have no way to return multiple results.
1731 return clang_getNullCursor();
1732 }
1733
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001734 Def = clang_getCursorDefinition(MakeCXCursor((*S)->getTargetDecl(),
1735 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00001736 }
1737
1738 return Def;
1739 }
1740
1741 case Decl::UsingShadow:
1742 return clang_getCursorDefinition(
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001743 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
1744 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00001745
1746 case Decl::ObjCMethod: {
1747 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
1748 if (Method->isThisDeclarationADefinition())
1749 return C;
1750
1751 // Dig out the method definition in the associated
1752 // @implementation, if we have it.
1753 // FIXME: The ASTs should make finding the definition easier.
1754 if (ObjCInterfaceDecl *Class
1755 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
1756 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
1757 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
1758 Method->isInstanceMethod()))
1759 if (Def->isThisDeclarationADefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001760 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001761
1762 return clang_getNullCursor();
1763 }
1764
1765 case Decl::ObjCCategory:
1766 if (ObjCCategoryImplDecl *Impl
1767 = cast<ObjCCategoryDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001768 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001769 return clang_getNullCursor();
1770
1771 case Decl::ObjCProtocol:
1772 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
1773 return C;
1774 return clang_getNullCursor();
1775
1776 case Decl::ObjCInterface:
1777 // There are two notions of a "definition" for an Objective-C
1778 // class: the interface and its implementation. When we resolved a
1779 // reference to an Objective-C class, produce the @interface as
1780 // the definition; when we were provided with the interface,
1781 // produce the @implementation as the definition.
1782 if (WasReference) {
1783 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
1784 return C;
1785 } else if (ObjCImplementationDecl *Impl
1786 = cast<ObjCInterfaceDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001787 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001788 return clang_getNullCursor();
1789
1790 case Decl::ObjCProperty:
1791 // FIXME: We don't really know where to find the
1792 // ObjCPropertyImplDecls that implement this property.
1793 return clang_getNullCursor();
1794
1795 case Decl::ObjCCompatibleAlias:
1796 if (ObjCInterfaceDecl *Class
1797 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
1798 if (!Class->isForwardDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001799 return MakeCXCursor(Class, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001800
1801 return clang_getNullCursor();
1802
1803 case Decl::ObjCForwardProtocol: {
1804 ObjCForwardProtocolDecl *Forward = cast<ObjCForwardProtocolDecl>(D);
1805 if (Forward->protocol_size() == 1)
1806 return clang_getCursorDefinition(
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001807 MakeCXCursor(*Forward->protocol_begin(),
1808 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00001809
1810 // FIXME: Cannot return multiple definitions.
1811 return clang_getNullCursor();
1812 }
1813
1814 case Decl::ObjCClass: {
1815 ObjCClassDecl *Class = cast<ObjCClassDecl>(D);
1816 if (Class->size() == 1) {
1817 ObjCInterfaceDecl *IFace = Class->begin()->getInterface();
1818 if (!IFace->isForwardDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001819 return MakeCXCursor(IFace, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001820 return clang_getNullCursor();
1821 }
1822
1823 // FIXME: Cannot return multiple definitions.
1824 return clang_getNullCursor();
1825 }
1826
1827 case Decl::Friend:
1828 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001829 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00001830 return clang_getNullCursor();
1831
1832 case Decl::FriendTemplate:
1833 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001834 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00001835 return clang_getNullCursor();
1836 }
1837
1838 return clang_getNullCursor();
1839}
1840
1841unsigned clang_isCursorDefinition(CXCursor C) {
1842 if (!clang_isDeclaration(C.kind))
1843 return 0;
1844
1845 return clang_getCursorDefinition(C) == C;
1846}
1847
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001848void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00001849 const char **startBuf,
1850 const char **endBuf,
1851 unsigned *startLine,
1852 unsigned *startColumn,
1853 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001854 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00001855 assert(getCursorDecl(C) && "CXCursor has null decl");
1856 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00001857 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
1858 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekfb480492010-01-13 21:46:36 +00001859
Steve Naroff4ade6d62009-09-23 17:52:52 +00001860 SourceManager &SM = FD->getASTContext().getSourceManager();
1861 *startBuf = SM.getCharacterData(Body->getLBracLoc());
1862 *endBuf = SM.getCharacterData(Body->getRBracLoc());
1863 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
1864 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
1865 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
1866 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
1867}
Ted Kremenekfb480492010-01-13 21:46:36 +00001868
1869} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00001870
Ted Kremenekfb480492010-01-13 21:46:36 +00001871//===----------------------------------------------------------------------===//
Douglas Gregorfc8ea232010-01-26 17:06:03 +00001872// Token-based Operations.
1873//===----------------------------------------------------------------------===//
1874
1875/* CXToken layout:
1876 * int_data[0]: a CXTokenKind
1877 * int_data[1]: starting token location
1878 * int_data[2]: token length
1879 * int_data[3]: reserved
1880 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
1881 * otherwise unused.
1882 */
1883extern "C" {
1884
1885CXTokenKind clang_getTokenKind(CXToken CXTok) {
1886 return static_cast<CXTokenKind>(CXTok.int_data[0]);
1887}
1888
1889CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
1890 switch (clang_getTokenKind(CXTok)) {
1891 case CXToken_Identifier:
1892 case CXToken_Keyword:
1893 // We know we have an IdentifierInfo*, so use that.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001894 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
1895 ->getNameStart());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00001896
1897 case CXToken_Literal: {
1898 // We have stashed the starting pointer in the ptr_data field. Use it.
1899 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001900 return createCXString(llvm::StringRef(Text, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00001901 }
1902
1903 case CXToken_Punctuation:
1904 case CXToken_Comment:
1905 break;
1906 }
1907
1908 // We have to find the starting buffer pointer the hard way, by
1909 // deconstructing the source location.
1910 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
1911 if (!CXXUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001912 return createCXString("");
Douglas Gregorfc8ea232010-01-26 17:06:03 +00001913
1914 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
1915 std::pair<FileID, unsigned> LocInfo
1916 = CXXUnit->getSourceManager().getDecomposedLoc(Loc);
1917 std::pair<const char *,const char *> Buffer
1918 = CXXUnit->getSourceManager().getBufferData(LocInfo.first);
1919
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001920 return createCXString(llvm::StringRef(Buffer.first+LocInfo.second,
1921 CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00001922}
1923
1924CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
1925 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
1926 if (!CXXUnit)
1927 return clang_getNullLocation();
1928
1929 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
1930 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
1931}
1932
1933CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
1934 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregor5352ac02010-01-28 00:27:43 +00001935 if (!CXXUnit)
1936 return clang_getNullRange();
Douglas Gregorfc8ea232010-01-26 17:06:03 +00001937
1938 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
1939 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
1940}
1941
1942void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
1943 CXToken **Tokens, unsigned *NumTokens) {
1944 if (Tokens)
1945 *Tokens = 0;
1946 if (NumTokens)
1947 *NumTokens = 0;
1948
1949 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
1950 if (!CXXUnit || !Tokens || !NumTokens)
1951 return;
1952
Daniel Dunbar85b988f2010-02-14 08:31:57 +00001953 SourceRange R = cxloc::translateCXSourceRange(Range);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00001954 if (R.isInvalid())
1955 return;
1956
1957 SourceManager &SourceMgr = CXXUnit->getSourceManager();
1958 std::pair<FileID, unsigned> BeginLocInfo
1959 = SourceMgr.getDecomposedLoc(R.getBegin());
1960 std::pair<FileID, unsigned> EndLocInfo
1961 = SourceMgr.getDecomposedLoc(R.getEnd());
1962
1963 // Cannot tokenize across files.
1964 if (BeginLocInfo.first != EndLocInfo.first)
1965 return;
1966
1967 // Create a lexer
1968 std::pair<const char *,const char *> Buffer
1969 = SourceMgr.getBufferData(BeginLocInfo.first);
1970 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
1971 CXXUnit->getASTContext().getLangOptions(),
1972 Buffer.first, Buffer.first + BeginLocInfo.second, Buffer.second);
1973 Lex.SetCommentRetentionState(true);
1974
1975 // Lex tokens until we hit the end of the range.
1976 const char *EffectiveBufferEnd = Buffer.first + EndLocInfo.second;
1977 llvm::SmallVector<CXToken, 32> CXTokens;
1978 Token Tok;
1979 do {
1980 // Lex the next token
1981 Lex.LexFromRawLexer(Tok);
1982 if (Tok.is(tok::eof))
1983 break;
1984
1985 // Initialize the CXToken.
1986 CXToken CXTok;
1987
1988 // - Common fields
1989 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
1990 CXTok.int_data[2] = Tok.getLength();
1991 CXTok.int_data[3] = 0;
1992
1993 // - Kind-specific fields
1994 if (Tok.isLiteral()) {
1995 CXTok.int_data[0] = CXToken_Literal;
1996 CXTok.ptr_data = (void *)Tok.getLiteralData();
1997 } else if (Tok.is(tok::identifier)) {
1998 // Lookup the identifier to determine whether we have a
1999 std::pair<FileID, unsigned> LocInfo
2000 = SourceMgr.getDecomposedLoc(Tok.getLocation());
2001 const char *StartPos
2002 = CXXUnit->getSourceManager().getBufferData(LocInfo.first).first +
2003 LocInfo.second;
2004 IdentifierInfo *II
2005 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok, StartPos);
2006 CXTok.int_data[0] = II->getTokenID() == tok::identifier?
2007 CXToken_Identifier
2008 : CXToken_Keyword;
2009 CXTok.ptr_data = II;
2010 } else if (Tok.is(tok::comment)) {
2011 CXTok.int_data[0] = CXToken_Comment;
2012 CXTok.ptr_data = 0;
2013 } else {
2014 CXTok.int_data[0] = CXToken_Punctuation;
2015 CXTok.ptr_data = 0;
2016 }
2017 CXTokens.push_back(CXTok);
2018 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
2019
2020 if (CXTokens.empty())
2021 return;
2022
2023 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
2024 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
2025 *NumTokens = CXTokens.size();
2026}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002027
2028typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
2029
2030enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
2031 CXCursor parent,
2032 CXClientData client_data) {
2033 AnnotateTokensData *Data = static_cast<AnnotateTokensData *>(client_data);
2034
2035 // We only annotate the locations of declarations, simple
2036 // references, and expressions which directly reference something.
2037 CXCursorKind Kind = clang_getCursorKind(cursor);
2038 if (clang_isDeclaration(Kind) || clang_isReference(Kind)) {
2039 // Okay: We can annotate the location of this declaration with the
2040 // declaration or reference
2041 } else if (clang_isExpression(cursor.kind)) {
2042 if (Kind != CXCursor_DeclRefExpr &&
2043 Kind != CXCursor_MemberRefExpr &&
2044 Kind != CXCursor_ObjCMessageExpr)
2045 return CXChildVisit_Recurse;
2046
2047 CXCursor Referenced = clang_getCursorReferenced(cursor);
2048 if (Referenced == cursor || Referenced == clang_getNullCursor())
2049 return CXChildVisit_Recurse;
2050
2051 // Okay: we can annotate the location of this expression
2052 } else {
2053 // Nothing to annotate
2054 return CXChildVisit_Recurse;
2055 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002056
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002057 CXSourceLocation Loc = clang_getCursorLocation(cursor);
2058 (*Data)[Loc.int_data] = cursor;
2059 return CXChildVisit_Recurse;
2060}
2061
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002062void clang_annotateTokens(CXTranslationUnit TU,
2063 CXToken *Tokens, unsigned NumTokens,
2064 CXCursor *Cursors) {
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002065 if (NumTokens == 0)
2066 return;
2067
2068 // Any token we don't specifically annotate will have a NULL cursor.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002069 for (unsigned I = 0; I != NumTokens; ++I)
2070 Cursors[I] = clang_getNullCursor();
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002071
2072 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2073 if (!CXXUnit || !Tokens)
2074 return;
2075
2076 // Annotate all of the source locations in the region of interest that map
2077 SourceRange RegionOfInterest;
2078 RegionOfInterest.setBegin(
2079 cxloc::translateSourceLocation(clang_getTokenLocation(TU, Tokens[0])));
2080 SourceLocation End
2081 = cxloc::translateSourceLocation(clang_getTokenLocation(TU,
2082 Tokens[NumTokens - 1]));
Daniel Dunbard52864b2010-02-14 10:02:57 +00002083 RegionOfInterest.setEnd(CXXUnit->getPreprocessor().getLocForEndOfToken(End));
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002084 // FIXME: Would be great to have a "hint" cursor, then walk from that
2085 // hint cursor upward until we find a cursor whose source range encloses
2086 // the region of interest, rather than starting from the translation unit.
2087 AnnotateTokensData Annotated;
2088 CXCursor Parent = clang_getTranslationUnitCursor(CXXUnit);
2089 CursorVisitor AnnotateVis(CXXUnit, AnnotateTokensVisitor, &Annotated,
2090 Decl::MaxPCHLevel, RegionOfInterest);
2091 AnnotateVis.VisitChildren(Parent);
2092
2093 for (unsigned I = 0; I != NumTokens; ++I) {
2094 // Determine whether we saw a cursor at this token's location.
2095 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
2096 if (Pos == Annotated.end())
2097 continue;
2098
2099 Cursors[I] = Pos->second;
2100 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002101}
2102
2103void clang_disposeTokens(CXTranslationUnit TU,
2104 CXToken *Tokens, unsigned NumTokens) {
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002105 free(Tokens);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002106}
2107
2108} // end: extern "C"
2109
2110//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00002111// CXString Operations.
2112//===----------------------------------------------------------------------===//
2113
2114extern "C" {
2115const char *clang_getCString(CXString string) {
2116 return string.Spelling;
2117}
2118
2119void clang_disposeString(CXString string) {
2120 if (string.MustFreeString && string.Spelling)
2121 free((void*)string.Spelling);
2122}
Ted Kremenek04bb7162010-01-22 22:44:15 +00002123
Ted Kremenekfb480492010-01-13 21:46:36 +00002124} // end: extern "C"
Ted Kremenek04bb7162010-01-22 22:44:15 +00002125
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002126namespace clang { namespace cxstring {
2127CXString createCXString(const char *String, bool DupString){
2128 CXString Str;
2129 if (DupString) {
2130 Str.Spelling = strdup(String);
2131 Str.MustFreeString = 1;
2132 } else {
2133 Str.Spelling = String;
2134 Str.MustFreeString = 0;
2135 }
2136 return Str;
2137}
2138
2139CXString createCXString(llvm::StringRef String, bool DupString) {
2140 CXString Result;
2141 if (DupString || (!String.empty() && String.data()[String.size()] != 0)) {
2142 char *Spelling = (char *)malloc(String.size() + 1);
2143 memmove(Spelling, String.data(), String.size());
2144 Spelling[String.size()] = 0;
2145 Result.Spelling = Spelling;
2146 Result.MustFreeString = 1;
2147 } else {
2148 Result.Spelling = String.data();
2149 Result.MustFreeString = 0;
2150 }
2151 return Result;
2152}
2153}}
2154
Ted Kremenek04bb7162010-01-22 22:44:15 +00002155//===----------------------------------------------------------------------===//
2156// Misc. utility functions.
2157//===----------------------------------------------------------------------===//
2158
2159extern "C" {
2160
Ted Kremeneka2a9d6e2010-02-12 22:54:40 +00002161CXString clang_getClangVersion() {
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002162 return createCXString(getClangFullVersion());
Ted Kremenek04bb7162010-01-22 22:44:15 +00002163}
2164
2165} // end: extern "C"