blob: d24bcf64dffe71861aaad70d7a95520a26ad5513 [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) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +000057
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 {
Ted Kremenekf0e23e82010-02-17 00:41:40 +000072 llvm::raw_svector_ostream Out(AggStr);
Ted Kremenek29b72842010-01-07 22:49:05 +000073 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;
Ted Kremenekf0e23e82010-02-17 00:41:40 +000083
Ted Kremenek254ba7c2010-01-07 23:13:53 +000084 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 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000115
Ted Kremenek29b72842010-01-07 22:49:05 +0000116 ~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,
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000128
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000129 /// \brief The first range ends before the second range starts.
130 RangeBefore,
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000131
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000132 /// \brief The first range starts after the second range ends.
133 RangeAfter
134};
135
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000136/// \brief Compare two source ranges to determine their relative position in
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000137/// the translation unit.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000138static RangeComparisonResult RangeCompare(SourceManager &SM,
139 SourceRange R1,
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000140 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.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000158CXSourceRange cxloc::translateSourceRange(const SourceManager &SM,
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000159 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 Kremenekf0e23e82010-02-17 00:41:40 +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;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000208
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000209 /// \brief The parent cursor whose children we are traversing.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000210 CXCursor Parent;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000211
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000212 /// \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;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000215
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000216 /// \brief The visitor function.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000217 CXCursorVisitor Visitor;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000218
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000219 /// \brief The opaque client data, to be passed along to the visitor.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000220 CXClientData ClientData;
Ted Kremenekf0e23e82010-02-17 00:41:40 +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;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000230
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;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000234
235 /// \brief Determine whether this particular source range comes before, comes
236 /// after, or overlaps the region of interest.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000237 ///
Daniel Dunbard52864b2010-02-14 10:02:57 +0000238 /// \param R a half-open source range retrieved from the abstract syntax tree.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000239 RangeComparisonResult CompareRegionOfInterest(SourceRange R);
240
Steve Naroff89922f82009-08-31 00:59:03 +0000241public:
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000242 CursorVisitor(ASTUnit *TU, CXCursorVisitor Visitor, CXClientData ClientData,
243 unsigned MaxPCHLevel,
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000244 SourceRange RegionOfInterest = SourceRange())
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000245 : TU(TU), Visitor(Visitor), ClientData(ClientData),
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000246 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 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000254
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);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000257
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);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000303
Douglas Gregora59e3902010-01-21 23:27:09 +0000304 // 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);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000312
Douglas Gregor336fd812010-01-23 00:40:08 +0000313 // 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};
Ted Kremenekf0e23e82010-02-17 00:41:40 +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;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000338
Douglas Gregorb1373d02010-01-20 20:59:29 +0000339 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 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000357
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.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000376bool 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 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000381
382 // Set the Parent field to Cursor, then back to its old value once we're
Douglas Gregorb1373d02010-01-20 20:59:29 +0000383 // 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)
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000391 : 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 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000397
Douglas Gregorb1373d02010-01-20 20:59:29 +0000398 ~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);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000404
Douglas Gregorb1373d02010-01-20 20:59:29 +0000405 if (clang_isDeclaration(Cursor.kind)) {
406 Decl *D = getCursorDecl(Cursor);
407 assert(D && "Invalid declaration cursor");
408 return Visit(D);
409 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000410
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));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000415
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 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000430
Douglas Gregor7b691f332010-01-20 21:13:59 +0000431 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000432 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +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;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000453
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000454 case RangeAfter:
455 // This declaration comes after the region of interest; we're done.
456 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000457
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000458 case RangeOverlap:
459 // This declaration overlaps the region of interest; visit it.
460 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000461 }
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000462 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000463
Daniel Dunbard52864b2010-02-14 10:02:57 +0000464 if (Visit(Cursor, true))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000465 return true;
466 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000467
Douglas Gregorb1373d02010-01-20 20:59:29 +0000468 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());
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000479
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000480 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;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000508
Douglas Gregorb1373d02010-01-20 20:59:29 +0000509 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;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000515
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000516 if (Expr *BitWidth = D->getBitWidth())
517 return Visit(MakeCXCursor(BitWidth, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000518
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000519 return false;
520}
521
522bool CursorVisitor::VisitVarDecl(VarDecl *D) {
523 if (VisitDeclaratorDecl(D))
524 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000525
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000526 if (Expr *Init = D->getInit())
527 return Visit(MakeCXCursor(Init, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000528
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000529 return false;
530}
531
532bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
533 // FIXME: We really need a TypeLoc covering Objective-C method declarations.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000534 // At the moment, we don't have information about locations in the return
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000535 // type.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000536 for (ObjCMethodDecl::param_iterator P = ND->param_begin(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000537 PEnd = ND->param_end();
538 P != PEnd; ++P) {
539 if (Visit(MakeCXCursor(*P, TU)))
540 return true;
541 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000542
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000543 if (ND->isThisDeclarationADefinition() &&
544 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
545 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000546
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000547 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;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000558
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;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000564
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;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000574
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000575 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(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000582 D->getSuperClassLoc(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000583 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000584 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +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;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000591
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) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000600 if (Visit(MakeCursorObjCClassRef(D->getCategoryDecl()->getClassInterface(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000601 D->getLocation(), TU)))
602 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000603
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000604 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(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000613 D->getSuperClassLoc(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000614 TU)))
615 return true;
616#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000617
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000618 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 Kremenekf0e23e82010-02-17 00:41:40 +0000628
629 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;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000636
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000637 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:
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000666 case BuiltinType::Float:
667 case BuiltinType::Double:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000668 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>())
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000692 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000693 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) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000730 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I),
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000731 TL.getProtocolLoc(I),
732 TU)))
733 return true;
734 }
735 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000736
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000737 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) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000753 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000754}
755
756bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000757 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000758}
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 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000798
Douglas Gregora59e3902010-01-21 23:27:09 +0000799 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 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000808
Douglas Gregora59e3902010-01-21 23:27:09 +0000809 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;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000816 }
817
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;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000832 }
833
Douglas Gregor263b47b2010-01-25 16:12:32 +0000834 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;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000838
Douglas Gregor263b47b2010-01-25 16:12:32 +0000839 return false;
840}
841
842bool CursorVisitor::VisitWhileStmt(WhileStmt *S) {
843 if (VarDecl *Var = S->getConditionVariable()) {
844 if (Visit(MakeCXCursor(Var, TU)))
845 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000846 }
847
Douglas Gregor263b47b2010-01-25 16:12:32 +0000848 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;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000862 }
863
Douglas Gregor263b47b2010-01-25 16:12:32 +0000864 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;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000870
Douglas Gregorf5bab412010-01-22 01:00:11 +0000871 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());
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000878
Douglas Gregor336fd812010-01-23 00:40:08 +0000879 return false;
880 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000881
Douglas Gregor336fd812010-01-23 00:40:08 +0000882 return VisitExpr(E);
883}
884
885bool CursorVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
886 if (TypeSourceInfo *TSInfo = E->getTypeInfoAsWritten())
887 if (Visit(TSInfo->getTypeLoc()))
888 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000889
Douglas Gregor336fd812010-01-23 00:40:08 +0000890 return VisitCastExpr(E);
891}
892
893bool CursorVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
894 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
895 if (Visit(TSInfo->getTypeLoc()))
896 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000897
Douglas Gregor336fd812010-01-23 00:40:08 +0000898 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;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000927
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);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000936
Douglas Gregor5352ac02010-01-28 00:27:43 +0000937 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;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000952
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);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000961
Douglas Gregor4db64a42010-01-23 00:14:00 +0000962 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
963 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000964 const llvm::MemoryBuffer *Buffer
Douglas Gregor4db64a42010-01-23 00:14:00 +0000965 = 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 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000971
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 Kremenekf0e23e82010-02-17 00:41:40 +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
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000988
Daniel Dunbar94220972009-12-05 02:17:18 +0000989 llvm::OwningPtr<ASTUnit> Unit(
990 ASTUnit::LoadFromCommandLine(Args.data(), Args.data() + Args.size(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +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 Kremenekf0e23e82010-02-17 00:41:40 +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;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001031
Douglas Gregor4db64a42010-01-23 00:14:00 +00001032 // 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());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001036
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 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001082
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001083 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();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001094
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00001095 // FIXME: Currently we don't report diagnostics on invalid ASTs.
1096 if (ATU)
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001097 ReportSerializedDiagnostics(DiagnosticsFile, *Diags,
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00001098 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();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001103
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("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +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();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001149
Douglas Gregorb9790342010-01-22 21:44:22 +00001150 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
1151 SourceLocation SLoc
1152 = CXXUnit->getSourceManager().getLocation(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001153 static_cast<const FileEntry *>(file),
Douglas Gregorb9790342010-01-22 21:44:22 +00001154 line, column);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001155
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();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001168
1169 CXSourceRange Result = { { begin.ptr_data[0], begin.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00001170 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) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001208 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00001209 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);
Ted Kremenekf0e23e82010-02-17 00:41:40 +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;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001237
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}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001241
Douglas Gregorb9790342010-01-22 21:44:22 +00001242CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
1243 if (!tu)
1244 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001245
Douglas Gregorb9790342010-01-22 21:44:22 +00001246 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001247
Douglas Gregorb9790342010-01-22 21:44:22 +00001248 FileManager &FMgr = CXXUnit->getFileManager();
1249 const FileEntry *File = FMgr.getFile(file_name, file_name+strlen(file_name));
1250 return const_cast<FileEntry *>(File);
1251}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001252
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();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001266
Ted Kremenekfb480492010-01-13 21:46:36 +00001267 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();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001273
Ted Kremenekfb480492010-01-13 21:46:36 +00001274 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" {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001290
1291unsigned 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;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001297
Douglas Gregorb1373d02010-01-20 20:59:29 +00001298 // Set the PCHLevel to filter out unwanted decls if requested.
1299 if (CXXUnit->getOnlyLocalDecls()) {
1300 PCHLevel = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001301
Douglas Gregorb1373d02010-01-20 20:59:29 +00001302 // If the main input was an AST, bump the level.
1303 if (CXXUnit->isMainFileAST())
1304 ++PCHLevel;
1305 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001306
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("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001315
Douglas Gregor78205d42010-01-20 21:45:58 +00001316 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001317 return createCXString(OMD->getSelector().getAsString());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001318
Douglas Gregor78205d42010-01-20 21:45:58 +00001319 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());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001324
Douglas Gregor78205d42010-01-20 21:45:58 +00001325 if (ND->getIdentifier())
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001326 return createCXString(ND->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001327
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001328 return createCXString("");
Douglas Gregor78205d42010-01-20 21:45:58 +00001329}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001330
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));
Ted Kremeneke68fff62010-02-17 00:41:32 +00001372
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001373 return createCXString("");
Steve Narofff334b4e2009-09-02 18:26:48 +00001374}
1375
Ted Kremeneke68fff62010-02-17 00:41:32 +00001376CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00001377 switch (Kind) {
Ted Kremeneke68fff62010-02-17 00:41:32 +00001378 case CXCursor_FunctionDecl:
1379 return createCXString("FunctionDecl");
1380 case CXCursor_TypedefDecl:
1381 return createCXString("TypedefDecl");
1382 case CXCursor_EnumDecl:
1383 return createCXString("EnumDecl");
1384 case CXCursor_EnumConstantDecl:
1385 return createCXString("EnumConstantDecl");
1386 case CXCursor_StructDecl:
1387 return createCXString("StructDecl");
1388 case CXCursor_UnionDecl:
1389 return createCXString("UnionDecl");
1390 case CXCursor_ClassDecl:
1391 return createCXString("ClassDecl");
1392 case CXCursor_FieldDecl:
1393 return createCXString("FieldDecl");
1394 case CXCursor_VarDecl:
1395 return createCXString("VarDecl");
1396 case CXCursor_ParmDecl:
1397 return createCXString("ParmDecl");
1398 case CXCursor_ObjCInterfaceDecl:
1399 return createCXString("ObjCInterfaceDecl");
1400 case CXCursor_ObjCCategoryDecl:
1401 return createCXString("ObjCCategoryDecl");
1402 case CXCursor_ObjCProtocolDecl:
1403 return createCXString("ObjCProtocolDecl");
1404 case CXCursor_ObjCPropertyDecl:
1405 return createCXString("ObjCPropertyDecl");
1406 case CXCursor_ObjCIvarDecl:
1407 return createCXString("ObjCIvarDecl");
1408 case CXCursor_ObjCInstanceMethodDecl:
1409 return createCXString("ObjCInstanceMethodDecl");
1410 case CXCursor_ObjCClassMethodDecl:
1411 return createCXString("ObjCClassMethodDecl");
1412 case CXCursor_ObjCImplementationDecl:
1413 return createCXString("ObjCImplementationDecl");
1414 case CXCursor_ObjCCategoryImplDecl:
1415 return createCXString("ObjCCategoryImplDecl");
1416 case CXCursor_UnexposedDecl:
1417 return createCXString("UnexposedDecl");
1418 case CXCursor_ObjCSuperClassRef:
1419 return createCXString("ObjCSuperClassRef");
1420 case CXCursor_ObjCProtocolRef:
1421 return createCXString("ObjCProtocolRef");
1422 case CXCursor_ObjCClassRef:
1423 return createCXString("ObjCClassRef");
1424 case CXCursor_TypeRef:
1425 return createCXString("TypeRef");
1426 case CXCursor_UnexposedExpr:
1427 return createCXString("UnexposedExpr");
1428 case CXCursor_DeclRefExpr:
1429 return createCXString("DeclRefExpr");
1430 case CXCursor_MemberRefExpr:
1431 return createCXString("MemberRefExpr");
1432 case CXCursor_CallExpr:
1433 return createCXString("CallExpr");
1434 case CXCursor_ObjCMessageExpr:
1435 return createCXString("ObjCMessageExpr");
1436 case CXCursor_UnexposedStmt:
1437 return createCXString("UnexposedStmt");
1438 case CXCursor_InvalidFile:
1439 return createCXString("InvalidFile");
1440 case CXCursor_NoDeclFound:
1441 return createCXString("NoDeclFound");
1442 case CXCursor_NotImplemented:
1443 return createCXString("NotImplemented");
1444 case CXCursor_TranslationUnit:
1445 return createCXString("TranslationUnit");
Steve Naroff89922f82009-08-31 00:59:03 +00001446 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00001447
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00001448 llvm_unreachable("Unhandled CXCursorKind");
Ted Kremeneke68fff62010-02-17 00:41:32 +00001449 return createCXString(NULL);
Steve Naroff600866c2009-08-27 19:51:58 +00001450}
Steve Naroff89922f82009-08-31 00:59:03 +00001451
Ted Kremeneke68fff62010-02-17 00:41:32 +00001452enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
1453 CXCursor parent,
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001454 CXClientData client_data) {
1455 CXCursor *BestCursor = static_cast<CXCursor *>(client_data);
1456 *BestCursor = cursor;
1457 return CXChildVisit_Recurse;
1458}
Ted Kremeneke68fff62010-02-17 00:41:32 +00001459
Douglas Gregorb9790342010-01-22 21:44:22 +00001460CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
1461 if (!TU)
Ted Kremenekf4629892010-01-14 01:51:23 +00001462 return clang_getNullCursor();
Ted Kremeneke68fff62010-02-17 00:41:32 +00001463
Douglas Gregorb9790342010-01-22 21:44:22 +00001464 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
1465
Ted Kremeneka297de22010-01-25 22:34:44 +00001466 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001467 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
1468 if (SLoc.isValid()) {
Daniel Dunbard52864b2010-02-14 10:02:57 +00001469 SourceRange RegionOfInterest(SLoc, SLoc.getFileLocWithOffset(1));
Ted Kremeneke68fff62010-02-17 00:41:32 +00001470
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001471 // FIXME: Would be great to have a "hint" cursor, then walk from that
1472 // hint cursor upward until we find a cursor whose source range encloses
1473 // the region of interest, rather than starting from the translation unit.
1474 CXCursor Parent = clang_getTranslationUnitCursor(CXXUnit);
Ted Kremeneke68fff62010-02-17 00:41:32 +00001475 CursorVisitor CursorVis(CXXUnit, GetCursorVisitor, &Result,
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001476 Decl::MaxPCHLevel, RegionOfInterest);
1477 CursorVis.VisitChildren(Parent);
Steve Naroff77128dd2009-09-15 20:25:34 +00001478 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00001479 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00001480}
1481
Ted Kremenek73885552009-11-17 19:28:59 +00001482CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00001483 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00001484}
1485
1486unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00001487 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00001488}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001489
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001490unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00001491 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
1492}
1493
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001494unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +00001495 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
1496}
Steve Naroff2d4d6292009-08-31 14:26:51 +00001497
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001498unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00001499 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
1500}
1501
Douglas Gregor97b98722010-01-19 23:20:36 +00001502unsigned clang_isExpression(enum CXCursorKind K) {
1503 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
1504}
1505
1506unsigned clang_isStatement(enum CXCursorKind K) {
1507 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
1508}
1509
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001510unsigned clang_isTranslationUnit(enum CXCursorKind K) {
1511 return K == CXCursor_TranslationUnit;
1512}
1513
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001514CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00001515 return C.kind;
1516}
1517
Douglas Gregor98258af2010-01-18 22:46:11 +00001518CXSourceLocation clang_getCursorLocation(CXCursor C) {
1519 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00001520 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001521 case CXCursor_ObjCSuperClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00001522 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1523 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001524 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001525 }
1526
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001527 case CXCursor_ObjCProtocolRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00001528 std::pair<ObjCProtocolDecl *, SourceLocation> P
1529 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001530 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001531 }
1532
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001533 case CXCursor_ObjCClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00001534 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1535 = getCursorObjCClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001536 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001537 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001538
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001539 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001540 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001541 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001542 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001543
Douglas Gregorf46034a2010-01-18 23:41:10 +00001544 default:
1545 // FIXME: Need a way to enumerate all non-reference cases.
1546 llvm_unreachable("Missed a reference kind");
1547 }
Douglas Gregor98258af2010-01-18 22:46:11 +00001548 }
Douglas Gregor97b98722010-01-19 23:20:36 +00001549
1550 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001551 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00001552 getLocationFromExpr(getCursorExpr(C)));
1553
Douglas Gregor5352ac02010-01-28 00:27:43 +00001554 if (!getCursorDecl(C))
1555 return clang_getNullLocation();
Douglas Gregor98258af2010-01-18 22:46:11 +00001556
Douglas Gregorf46034a2010-01-18 23:41:10 +00001557 Decl *D = getCursorDecl(C);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001558 SourceLocation Loc = D->getLocation();
1559 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
1560 Loc = Class->getClassLoc();
Ted Kremeneka297de22010-01-25 22:34:44 +00001561 return cxloc::translateSourceLocation(D->getASTContext(), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00001562}
Douglas Gregora7bde202010-01-19 00:34:46 +00001563
1564CXSourceRange clang_getCursorExtent(CXCursor C) {
1565 if (clang_isReference(C.kind)) {
1566 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001567 case CXCursor_ObjCSuperClassRef: {
Douglas Gregora7bde202010-01-19 00:34:46 +00001568 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1569 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001570 return cxloc::translateSourceRange(P.first->getASTContext(), P.second);
Douglas Gregora7bde202010-01-19 00:34:46 +00001571 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001572
1573 case CXCursor_ObjCProtocolRef: {
Douglas Gregora7bde202010-01-19 00:34:46 +00001574 std::pair<ObjCProtocolDecl *, SourceLocation> P
1575 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001576 return cxloc::translateSourceRange(P.first->getASTContext(), P.second);
Douglas Gregora7bde202010-01-19 00:34:46 +00001577 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001578
1579 case CXCursor_ObjCClassRef: {
Douglas Gregora7bde202010-01-19 00:34:46 +00001580 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1581 = getCursorObjCClassRef(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001582
Ted Kremeneka297de22010-01-25 22:34:44 +00001583 return cxloc::translateSourceRange(P.first->getASTContext(), P.second);
Douglas Gregora7bde202010-01-19 00:34:46 +00001584 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001585
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001586 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001587 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001588 return cxloc::translateSourceRange(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001589 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001590
Douglas Gregora7bde202010-01-19 00:34:46 +00001591 default:
1592 // FIXME: Need a way to enumerate all non-reference cases.
1593 llvm_unreachable("Missed a reference kind");
1594 }
1595 }
Douglas Gregor97b98722010-01-19 23:20:36 +00001596
1597 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001598 return cxloc::translateSourceRange(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00001599 getCursorExpr(C)->getSourceRange());
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001600
1601 if (clang_isStatement(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001602 return cxloc::translateSourceRange(getCursorContext(C),
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001603 getCursorStmt(C)->getSourceRange());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001604
Douglas Gregor5352ac02010-01-28 00:27:43 +00001605 if (!getCursorDecl(C))
1606 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001607
Douglas Gregora7bde202010-01-19 00:34:46 +00001608 Decl *D = getCursorDecl(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001609 return cxloc::translateSourceRange(D->getASTContext(), D->getSourceRange());
Douglas Gregora7bde202010-01-19 00:34:46 +00001610}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001611
1612CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001613 if (clang_isInvalid(C.kind))
1614 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001615
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001616 ASTUnit *CXXUnit = getCursorASTUnit(C);
Douglas Gregorb6998662010-01-19 19:34:47 +00001617 if (clang_isDeclaration(C.kind))
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001618 return C;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001619
Douglas Gregor97b98722010-01-19 23:20:36 +00001620 if (clang_isExpression(C.kind)) {
1621 Decl *D = getDeclFromExpr(getCursorExpr(C));
1622 if (D)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001623 return MakeCXCursor(D, CXXUnit);
Douglas Gregor97b98722010-01-19 23:20:36 +00001624 return clang_getNullCursor();
1625 }
1626
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001627 if (!clang_isReference(C.kind))
1628 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001629
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001630 switch (C.kind) {
1631 case CXCursor_ObjCSuperClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001632 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001633
1634 case CXCursor_ObjCProtocolRef: {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001635 return MakeCXCursor(getCursorObjCProtocolRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001636
1637 case CXCursor_ObjCClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001638 return MakeCXCursor(getCursorObjCClassRef(C).first, CXXUnit);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001639
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001640 case CXCursor_TypeRef:
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001641 return MakeCXCursor(getCursorTypeRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001642
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001643 default:
1644 // We would prefer to enumerate all non-reference cursor kinds here.
1645 llvm_unreachable("Unhandled reference cursor kind");
1646 break;
1647 }
1648 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001649
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001650 return clang_getNullCursor();
1651}
1652
Douglas Gregorb6998662010-01-19 19:34:47 +00001653CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001654 if (clang_isInvalid(C.kind))
1655 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001656
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001657 ASTUnit *CXXUnit = getCursorASTUnit(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001658
Douglas Gregorb6998662010-01-19 19:34:47 +00001659 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00001660 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00001661 C = clang_getCursorReferenced(C);
1662 WasReference = true;
1663 }
1664
1665 if (!clang_isDeclaration(C.kind))
1666 return clang_getNullCursor();
1667
1668 Decl *D = getCursorDecl(C);
1669 if (!D)
1670 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001671
Douglas Gregorb6998662010-01-19 19:34:47 +00001672 switch (D->getKind()) {
1673 // Declaration kinds that don't really separate the notions of
1674 // declaration and definition.
1675 case Decl::Namespace:
1676 case Decl::Typedef:
1677 case Decl::TemplateTypeParm:
1678 case Decl::EnumConstant:
1679 case Decl::Field:
1680 case Decl::ObjCIvar:
1681 case Decl::ObjCAtDefsField:
1682 case Decl::ImplicitParam:
1683 case Decl::ParmVar:
1684 case Decl::NonTypeTemplateParm:
1685 case Decl::TemplateTemplateParm:
1686 case Decl::ObjCCategoryImpl:
1687 case Decl::ObjCImplementation:
1688 case Decl::LinkageSpec:
1689 case Decl::ObjCPropertyImpl:
1690 case Decl::FileScopeAsm:
1691 case Decl::StaticAssert:
1692 case Decl::Block:
1693 return C;
1694
1695 // Declaration kinds that don't make any sense here, but are
1696 // nonetheless harmless.
1697 case Decl::TranslationUnit:
1698 case Decl::Template:
1699 case Decl::ObjCContainer:
1700 break;
1701
1702 // Declaration kinds for which the definition is not resolvable.
1703 case Decl::UnresolvedUsingTypename:
1704 case Decl::UnresolvedUsingValue:
1705 break;
1706
1707 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001708 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
1709 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001710
1711 case Decl::NamespaceAlias:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001712 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001713
1714 case Decl::Enum:
1715 case Decl::Record:
1716 case Decl::CXXRecord:
1717 case Decl::ClassTemplateSpecialization:
1718 case Decl::ClassTemplatePartialSpecialization:
Douglas Gregor952b0172010-02-11 01:04:33 +00001719 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001720 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001721 return clang_getNullCursor();
1722
1723 case Decl::Function:
1724 case Decl::CXXMethod:
1725 case Decl::CXXConstructor:
1726 case Decl::CXXDestructor:
1727 case Decl::CXXConversion: {
1728 const FunctionDecl *Def = 0;
1729 if (cast<FunctionDecl>(D)->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001730 return MakeCXCursor(const_cast<FunctionDecl *>(Def), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001731 return clang_getNullCursor();
1732 }
1733
1734 case Decl::Var: {
Sebastian Redl31310a22010-02-01 20:16:42 +00001735 // Ask the variable if it has a definition.
1736 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
1737 return MakeCXCursor(Def, CXXUnit);
1738 return clang_getNullCursor();
Douglas Gregorb6998662010-01-19 19:34:47 +00001739 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001740
Douglas Gregorb6998662010-01-19 19:34:47 +00001741 case Decl::FunctionTemplate: {
1742 const FunctionDecl *Def = 0;
1743 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001744 return MakeCXCursor(Def->getDescribedFunctionTemplate(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001745 return clang_getNullCursor();
1746 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001747
Douglas Gregorb6998662010-01-19 19:34:47 +00001748 case Decl::ClassTemplate: {
1749 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
Douglas Gregor952b0172010-02-11 01:04:33 +00001750 ->getDefinition())
Douglas Gregorb6998662010-01-19 19:34:47 +00001751 return MakeCXCursor(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001752 cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001753 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001754 return clang_getNullCursor();
1755 }
1756
1757 case Decl::Using: {
1758 UsingDecl *Using = cast<UsingDecl>(D);
1759 CXCursor Def = clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001760 for (UsingDecl::shadow_iterator S = Using->shadow_begin(),
1761 SEnd = Using->shadow_end();
Douglas Gregorb6998662010-01-19 19:34:47 +00001762 S != SEnd; ++S) {
1763 if (Def != clang_getNullCursor()) {
1764 // FIXME: We have no way to return multiple results.
1765 return clang_getNullCursor();
1766 }
1767
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001768 Def = clang_getCursorDefinition(MakeCXCursor((*S)->getTargetDecl(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001769 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00001770 }
1771
1772 return Def;
1773 }
1774
1775 case Decl::UsingShadow:
1776 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001777 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001778 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00001779
1780 case Decl::ObjCMethod: {
1781 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
1782 if (Method->isThisDeclarationADefinition())
1783 return C;
1784
1785 // Dig out the method definition in the associated
1786 // @implementation, if we have it.
1787 // FIXME: The ASTs should make finding the definition easier.
1788 if (ObjCInterfaceDecl *Class
1789 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
1790 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
1791 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
1792 Method->isInstanceMethod()))
1793 if (Def->isThisDeclarationADefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001794 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001795
1796 return clang_getNullCursor();
1797 }
1798
1799 case Decl::ObjCCategory:
1800 if (ObjCCategoryImplDecl *Impl
1801 = cast<ObjCCategoryDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001802 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001803 return clang_getNullCursor();
1804
1805 case Decl::ObjCProtocol:
1806 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
1807 return C;
1808 return clang_getNullCursor();
1809
1810 case Decl::ObjCInterface:
1811 // There are two notions of a "definition" for an Objective-C
1812 // class: the interface and its implementation. When we resolved a
1813 // reference to an Objective-C class, produce the @interface as
1814 // the definition; when we were provided with the interface,
1815 // produce the @implementation as the definition.
1816 if (WasReference) {
1817 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
1818 return C;
1819 } else if (ObjCImplementationDecl *Impl
1820 = cast<ObjCInterfaceDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001821 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001822 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001823
Douglas Gregorb6998662010-01-19 19:34:47 +00001824 case Decl::ObjCProperty:
1825 // FIXME: We don't really know where to find the
1826 // ObjCPropertyImplDecls that implement this property.
1827 return clang_getNullCursor();
1828
1829 case Decl::ObjCCompatibleAlias:
1830 if (ObjCInterfaceDecl *Class
1831 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
1832 if (!Class->isForwardDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001833 return MakeCXCursor(Class, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001834
Douglas Gregorb6998662010-01-19 19:34:47 +00001835 return clang_getNullCursor();
1836
1837 case Decl::ObjCForwardProtocol: {
1838 ObjCForwardProtocolDecl *Forward = cast<ObjCForwardProtocolDecl>(D);
1839 if (Forward->protocol_size() == 1)
1840 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001841 MakeCXCursor(*Forward->protocol_begin(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001842 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00001843
1844 // FIXME: Cannot return multiple definitions.
1845 return clang_getNullCursor();
1846 }
1847
1848 case Decl::ObjCClass: {
1849 ObjCClassDecl *Class = cast<ObjCClassDecl>(D);
1850 if (Class->size() == 1) {
1851 ObjCInterfaceDecl *IFace = Class->begin()->getInterface();
1852 if (!IFace->isForwardDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001853 return MakeCXCursor(IFace, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001854 return clang_getNullCursor();
1855 }
1856
1857 // FIXME: Cannot return multiple definitions.
1858 return clang_getNullCursor();
1859 }
1860
1861 case Decl::Friend:
1862 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001863 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00001864 return clang_getNullCursor();
1865
1866 case Decl::FriendTemplate:
1867 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001868 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00001869 return clang_getNullCursor();
1870 }
1871
1872 return clang_getNullCursor();
1873}
1874
1875unsigned clang_isCursorDefinition(CXCursor C) {
1876 if (!clang_isDeclaration(C.kind))
1877 return 0;
1878
1879 return clang_getCursorDefinition(C) == C;
1880}
1881
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001882void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00001883 const char **startBuf,
1884 const char **endBuf,
1885 unsigned *startLine,
1886 unsigned *startColumn,
1887 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001888 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00001889 assert(getCursorDecl(C) && "CXCursor has null decl");
1890 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00001891 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
1892 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001893
Steve Naroff4ade6d62009-09-23 17:52:52 +00001894 SourceManager &SM = FD->getASTContext().getSourceManager();
1895 *startBuf = SM.getCharacterData(Body->getLBracLoc());
1896 *endBuf = SM.getCharacterData(Body->getRBracLoc());
1897 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
1898 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
1899 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
1900 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
1901}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001902
Ted Kremenekfb480492010-01-13 21:46:36 +00001903} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00001904
Ted Kremenekfb480492010-01-13 21:46:36 +00001905//===----------------------------------------------------------------------===//
Douglas Gregorfc8ea232010-01-26 17:06:03 +00001906// Token-based Operations.
1907//===----------------------------------------------------------------------===//
1908
1909/* CXToken layout:
1910 * int_data[0]: a CXTokenKind
1911 * int_data[1]: starting token location
1912 * int_data[2]: token length
1913 * int_data[3]: reserved
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001914 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00001915 * otherwise unused.
1916 */
1917extern "C" {
1918
1919CXTokenKind clang_getTokenKind(CXToken CXTok) {
1920 return static_cast<CXTokenKind>(CXTok.int_data[0]);
1921}
1922
1923CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
1924 switch (clang_getTokenKind(CXTok)) {
1925 case CXToken_Identifier:
1926 case CXToken_Keyword:
1927 // We know we have an IdentifierInfo*, so use that.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001928 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
1929 ->getNameStart());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00001930
1931 case CXToken_Literal: {
1932 // We have stashed the starting pointer in the ptr_data field. Use it.
1933 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001934 return createCXString(llvm::StringRef(Text, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00001935 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001936
Douglas Gregorfc8ea232010-01-26 17:06:03 +00001937 case CXToken_Punctuation:
1938 case CXToken_Comment:
1939 break;
1940 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001941
1942 // We have to find the starting buffer pointer the hard way, by
Douglas Gregorfc8ea232010-01-26 17:06:03 +00001943 // deconstructing the source location.
1944 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
1945 if (!CXXUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001946 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001947
Douglas Gregorfc8ea232010-01-26 17:06:03 +00001948 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
1949 std::pair<FileID, unsigned> LocInfo
1950 = CXXUnit->getSourceManager().getDecomposedLoc(Loc);
1951 std::pair<const char *,const char *> Buffer
1952 = CXXUnit->getSourceManager().getBufferData(LocInfo.first);
1953
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001954 return createCXString(llvm::StringRef(Buffer.first+LocInfo.second,
1955 CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00001956}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001957
Douglas Gregorfc8ea232010-01-26 17:06:03 +00001958CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
1959 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
1960 if (!CXXUnit)
1961 return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001962
Douglas Gregorfc8ea232010-01-26 17:06:03 +00001963 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
1964 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
1965}
1966
1967CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
1968 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregor5352ac02010-01-28 00:27:43 +00001969 if (!CXXUnit)
1970 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001971
1972 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
Douglas Gregorfc8ea232010-01-26 17:06:03 +00001973 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
1974}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001975
Douglas Gregorfc8ea232010-01-26 17:06:03 +00001976void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
1977 CXToken **Tokens, unsigned *NumTokens) {
1978 if (Tokens)
1979 *Tokens = 0;
1980 if (NumTokens)
1981 *NumTokens = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001982
Douglas Gregorfc8ea232010-01-26 17:06:03 +00001983 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
1984 if (!CXXUnit || !Tokens || !NumTokens)
1985 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001986
Daniel Dunbar85b988f2010-02-14 08:31:57 +00001987 SourceRange R = cxloc::translateCXSourceRange(Range);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00001988 if (R.isInvalid())
1989 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001990
Douglas Gregorfc8ea232010-01-26 17:06:03 +00001991 SourceManager &SourceMgr = CXXUnit->getSourceManager();
1992 std::pair<FileID, unsigned> BeginLocInfo
1993 = SourceMgr.getDecomposedLoc(R.getBegin());
1994 std::pair<FileID, unsigned> EndLocInfo
1995 = SourceMgr.getDecomposedLoc(R.getEnd());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001996
Douglas Gregorfc8ea232010-01-26 17:06:03 +00001997 // Cannot tokenize across files.
1998 if (BeginLocInfo.first != EndLocInfo.first)
1999 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002000
2001 // Create a lexer
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002002 std::pair<const char *,const char *> Buffer
2003 = SourceMgr.getBufferData(BeginLocInfo.first);
2004 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
2005 CXXUnit->getASTContext().getLangOptions(),
2006 Buffer.first, Buffer.first + BeginLocInfo.second, Buffer.second);
2007 Lex.SetCommentRetentionState(true);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002008
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002009 // Lex tokens until we hit the end of the range.
2010 const char *EffectiveBufferEnd = Buffer.first + EndLocInfo.second;
2011 llvm::SmallVector<CXToken, 32> CXTokens;
2012 Token Tok;
2013 do {
2014 // Lex the next token
2015 Lex.LexFromRawLexer(Tok);
2016 if (Tok.is(tok::eof))
2017 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002018
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002019 // Initialize the CXToken.
2020 CXToken CXTok;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002021
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002022 // - Common fields
2023 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
2024 CXTok.int_data[2] = Tok.getLength();
2025 CXTok.int_data[3] = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002026
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002027 // - Kind-specific fields
2028 if (Tok.isLiteral()) {
2029 CXTok.int_data[0] = CXToken_Literal;
2030 CXTok.ptr_data = (void *)Tok.getLiteralData();
2031 } else if (Tok.is(tok::identifier)) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002032 // Lookup the identifier to determine whether we have a
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002033 std::pair<FileID, unsigned> LocInfo
2034 = SourceMgr.getDecomposedLoc(Tok.getLocation());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002035 const char *StartPos
2036 = CXXUnit->getSourceManager().getBufferData(LocInfo.first).first +
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002037 LocInfo.second;
2038 IdentifierInfo *II
2039 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok, StartPos);
2040 CXTok.int_data[0] = II->getTokenID() == tok::identifier?
2041 CXToken_Identifier
2042 : CXToken_Keyword;
2043 CXTok.ptr_data = II;
2044 } else if (Tok.is(tok::comment)) {
2045 CXTok.int_data[0] = CXToken_Comment;
2046 CXTok.ptr_data = 0;
2047 } else {
2048 CXTok.int_data[0] = CXToken_Punctuation;
2049 CXTok.ptr_data = 0;
2050 }
2051 CXTokens.push_back(CXTok);
2052 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002053
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002054 if (CXTokens.empty())
2055 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002056
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002057 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
2058 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
2059 *NumTokens = CXTokens.size();
2060}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002061
2062typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
2063
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002064enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
2065 CXCursor parent,
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002066 CXClientData client_data) {
2067 AnnotateTokensData *Data = static_cast<AnnotateTokensData *>(client_data);
2068
2069 // We only annotate the locations of declarations, simple
2070 // references, and expressions which directly reference something.
2071 CXCursorKind Kind = clang_getCursorKind(cursor);
2072 if (clang_isDeclaration(Kind) || clang_isReference(Kind)) {
2073 // Okay: We can annotate the location of this declaration with the
2074 // declaration or reference
2075 } else if (clang_isExpression(cursor.kind)) {
2076 if (Kind != CXCursor_DeclRefExpr &&
2077 Kind != CXCursor_MemberRefExpr &&
2078 Kind != CXCursor_ObjCMessageExpr)
2079 return CXChildVisit_Recurse;
2080
2081 CXCursor Referenced = clang_getCursorReferenced(cursor);
2082 if (Referenced == cursor || Referenced == clang_getNullCursor())
2083 return CXChildVisit_Recurse;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002084
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002085 // Okay: we can annotate the location of this expression
2086 } else {
2087 // Nothing to annotate
2088 return CXChildVisit_Recurse;
2089 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002090
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002091 CXSourceLocation Loc = clang_getCursorLocation(cursor);
2092 (*Data)[Loc.int_data] = cursor;
2093 return CXChildVisit_Recurse;
2094}
2095
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002096void clang_annotateTokens(CXTranslationUnit TU,
2097 CXToken *Tokens, unsigned NumTokens,
2098 CXCursor *Cursors) {
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002099 if (NumTokens == 0)
2100 return;
2101
2102 // Any token we don't specifically annotate will have a NULL cursor.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002103 for (unsigned I = 0; I != NumTokens; ++I)
2104 Cursors[I] = clang_getNullCursor();
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002105
2106 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2107 if (!CXXUnit || !Tokens)
2108 return;
2109
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002110 // Annotate all of the source locations in the region of interest that map
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002111 SourceRange RegionOfInterest;
2112 RegionOfInterest.setBegin(
2113 cxloc::translateSourceLocation(clang_getTokenLocation(TU, Tokens[0])));
2114 SourceLocation End
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002115 = cxloc::translateSourceLocation(clang_getTokenLocation(TU,
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002116 Tokens[NumTokens - 1]));
Daniel Dunbard52864b2010-02-14 10:02:57 +00002117 RegionOfInterest.setEnd(CXXUnit->getPreprocessor().getLocForEndOfToken(End));
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002118 // FIXME: Would be great to have a "hint" cursor, then walk from that
2119 // hint cursor upward until we find a cursor whose source range encloses
2120 // the region of interest, rather than starting from the translation unit.
2121 AnnotateTokensData Annotated;
2122 CXCursor Parent = clang_getTranslationUnitCursor(CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002123 CursorVisitor AnnotateVis(CXXUnit, AnnotateTokensVisitor, &Annotated,
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002124 Decl::MaxPCHLevel, RegionOfInterest);
2125 AnnotateVis.VisitChildren(Parent);
2126
2127 for (unsigned I = 0; I != NumTokens; ++I) {
2128 // Determine whether we saw a cursor at this token's location.
2129 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
2130 if (Pos == Annotated.end())
2131 continue;
2132
2133 Cursors[I] = Pos->second;
2134 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002135}
2136
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002137void clang_disposeTokens(CXTranslationUnit TU,
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002138 CXToken *Tokens, unsigned NumTokens) {
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002139 free(Tokens);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002140}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002141
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002142} // end: extern "C"
2143
2144//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00002145// CXString Operations.
2146//===----------------------------------------------------------------------===//
2147
2148extern "C" {
2149const char *clang_getCString(CXString string) {
2150 return string.Spelling;
2151}
2152
2153void clang_disposeString(CXString string) {
2154 if (string.MustFreeString && string.Spelling)
2155 free((void*)string.Spelling);
2156}
Ted Kremenek04bb7162010-01-22 22:44:15 +00002157
Ted Kremenekfb480492010-01-13 21:46:36 +00002158} // end: extern "C"
Ted Kremenek04bb7162010-01-22 22:44:15 +00002159
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002160namespace clang { namespace cxstring {
2161CXString createCXString(const char *String, bool DupString){
2162 CXString Str;
2163 if (DupString) {
2164 Str.Spelling = strdup(String);
2165 Str.MustFreeString = 1;
2166 } else {
2167 Str.Spelling = String;
2168 Str.MustFreeString = 0;
2169 }
2170 return Str;
2171}
2172
2173CXString createCXString(llvm::StringRef String, bool DupString) {
2174 CXString Result;
2175 if (DupString || (!String.empty() && String.data()[String.size()] != 0)) {
2176 char *Spelling = (char *)malloc(String.size() + 1);
2177 memmove(Spelling, String.data(), String.size());
2178 Spelling[String.size()] = 0;
2179 Result.Spelling = Spelling;
2180 Result.MustFreeString = 1;
2181 } else {
2182 Result.Spelling = String.data();
2183 Result.MustFreeString = 0;
2184 }
2185 return Result;
2186}
2187}}
2188
Ted Kremenek04bb7162010-01-22 22:44:15 +00002189//===----------------------------------------------------------------------===//
2190// Misc. utility functions.
2191//===----------------------------------------------------------------------===//
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002192
Ted Kremenek04bb7162010-01-22 22:44:15 +00002193extern "C" {
2194
Ted Kremeneka2a9d6e2010-02-12 22:54:40 +00002195CXString clang_getClangVersion() {
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002196 return createCXString(getClangFullVersion());
Ted Kremenek04bb7162010-01-22 22:44:15 +00002197}
2198
2199} // end: extern "C"