blob: db27ffe68a46c162c0741ba6d87b09d251eddf99 [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"
Douglas Gregor0a812cf2010-02-18 23:07:20 +000030#include "llvm/System/Signals.h"
Ted Kremenekfc062212009-10-19 21:44:57 +000031
Benjamin Kramerc2a98162010-03-13 21:22:49 +000032// Needed to define L_TMPNAM on some systems.
33#include <cstdio>
34
Steve Naroff50398192009-08-28 15:28:48 +000035using namespace clang;
Ted Kremenek16c440a2010-01-15 20:35:54 +000036using namespace clang::cxcursor;
Ted Kremenekee4db4f2010-02-17 00:41:08 +000037using namespace clang::cxstring;
Steve Naroff50398192009-08-28 15:28:48 +000038using namespace idx;
39
Ted Kremenek8a8da7d2010-01-06 03:42:32 +000040//===----------------------------------------------------------------------===//
41// Crash Reporting.
42//===----------------------------------------------------------------------===//
43
44#ifdef __APPLE__
Ted Kremenek29b72842010-01-07 22:49:05 +000045#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 Kremenek6b569992010-02-17 21:12:23 +000049#define NUM_CRASH_STRINGS 32
Ted Kremenek29b72842010-01-07 22:49:05 +000050static 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);
Ted Kremenek0baa9522010-03-05 22:43:25 +0000107 Out << "ClangCIndex [" << getClangFullVersion() << "]"
108 << "[createTranslationUnitFromSourceFile]: clang";
Ted Kremenek29b72842010-01-07 22:49:05 +0000109 for (llvm::SmallVectorImpl<const char*>::iterator I=Args.begin(),
110 E=Args.end(); I!=E; ++I)
111 Out << ' ' << *I;
112 }
113 crashtracerSlot = SetCrashTracerInfo(CrashString.c_str(),
114 AggregateString);
115 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000116
Ted Kremenek29b72842010-01-07 22:49:05 +0000117 ~ArgsCrashTracerInfo() {
118 ResetCrashTracerInfo(crashtracerSlot);
119 }
120};
121}
122#endif
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000123
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
Ted Kremenek09dfa372010-02-18 05:46:33 +0000259 bool VisitAttributes(Decl *D);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000260 bool VisitDeclContext(DeclContext *DC);
Ted Kremenek4540c9c2010-02-18 18:47:08 +0000261 bool VisitTranslationUnitDecl(TranslationUnitDecl *D);
262 bool VisitTypedefDecl(TypedefDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000263 bool VisitTagDecl(TagDecl *D);
264 bool VisitEnumConstantDecl(EnumConstantDecl *D);
265 bool VisitDeclaratorDecl(DeclaratorDecl *DD);
266 bool VisitFunctionDecl(FunctionDecl *ND);
267 bool VisitFieldDecl(FieldDecl *D);
Ted Kremenek4540c9c2010-02-18 18:47:08 +0000268 bool VisitVarDecl(VarDecl *);
Ted Kremenek79758f62010-02-18 22:36:18 +0000269 bool VisitObjCMethodDecl(ObjCMethodDecl *ND);
270 bool VisitObjCContainerDecl(ObjCContainerDecl *D);
271 bool VisitObjCCategoryDecl(ObjCCategoryDecl *ND);
272 bool VisitObjCProtocolDecl(ObjCProtocolDecl *PID);
273 bool VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
274 bool VisitObjCImplDecl(ObjCImplDecl *D);
275 bool VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
276 bool VisitObjCImplementationDecl(ObjCImplementationDecl *D);
277 // FIXME: ObjCPropertyDecl requires TypeSourceInfo, getter/setter locations,
278 // etc.
279 // FIXME: ObjCCompatibleAliasDecl requires aliased-class locations.
280 bool VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D);
281 bool VisitObjCClassDecl(ObjCClassDecl *D);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000282
283 // Type visitors
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000284 // FIXME: QualifiedTypeLoc doesn't provide any location information
285 bool VisitBuiltinTypeLoc(BuiltinTypeLoc TL);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000286 bool VisitTypedefTypeLoc(TypedefTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000287 bool VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL);
288 bool VisitTagTypeLoc(TagTypeLoc TL);
289 // FIXME: TemplateTypeParmTypeLoc doesn't provide any location information
290 bool VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL);
291 bool VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL);
292 bool VisitPointerTypeLoc(PointerTypeLoc TL);
293 bool VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL);
294 bool VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL);
295 bool VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL);
296 bool VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL);
297 bool VisitFunctionTypeLoc(FunctionTypeLoc TL);
298 bool VisitArrayTypeLoc(ArrayTypeLoc TL);
Douglas Gregor2332c112010-01-21 20:48:56 +0000299 // FIXME: Implement for TemplateSpecializationTypeLoc
300 // FIXME: Implement visitors here when the unimplemented TypeLocs get
301 // implemented
302 bool VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL);
303 bool VisitTypeOfTypeLoc(TypeOfTypeLoc TL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000304
Douglas Gregora59e3902010-01-21 23:27:09 +0000305 // Statement visitors
306 bool VisitStmt(Stmt *S);
307 bool VisitDeclStmt(DeclStmt *S);
Douglas Gregorf5bab412010-01-22 01:00:11 +0000308 // FIXME: LabelStmt label?
309 bool VisitIfStmt(IfStmt *S);
310 bool VisitSwitchStmt(SwitchStmt *S);
Douglas Gregor263b47b2010-01-25 16:12:32 +0000311 bool VisitWhileStmt(WhileStmt *S);
312 bool VisitForStmt(ForStmt *S);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000313
Douglas Gregor336fd812010-01-23 00:40:08 +0000314 // Expression visitors
315 bool VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E);
316 bool VisitExplicitCastExpr(ExplicitCastExpr *E);
317 bool VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
Douglas Gregorc2350e52010-03-08 16:40:19 +0000318 bool VisitObjCMessageExpr(ObjCMessageExpr *E);
Steve Naroff89922f82009-08-31 00:59:03 +0000319};
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000320
Ted Kremenekab188932010-01-05 19:32:54 +0000321} // end anonymous namespace
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000322
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000323RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000324 return RangeCompare(TU->getSourceManager(), R, RegionOfInterest);
325}
326
Douglas Gregorb1373d02010-01-20 20:59:29 +0000327/// \brief Visit the given cursor and, if requested by the visitor,
328/// its children.
329///
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000330/// \param Cursor the cursor to visit.
331///
332/// \param CheckRegionOfInterest if true, then the caller already checked that
333/// this cursor is within the region of interest.
334///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000335/// \returns true if the visitation should be aborted, false if it
336/// should continue.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000337bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
Douglas Gregorb1373d02010-01-20 20:59:29 +0000338 if (clang_isInvalid(Cursor.kind))
339 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000340
Douglas Gregorb1373d02010-01-20 20:59:29 +0000341 if (clang_isDeclaration(Cursor.kind)) {
342 Decl *D = getCursorDecl(Cursor);
343 assert(D && "Invalid declaration cursor");
344 if (D->getPCHLevel() > MaxPCHLevel)
345 return false;
346
347 if (D->isImplicit())
348 return false;
349 }
350
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000351 // If we have a range of interest, and this cursor doesn't intersect with it,
352 // we're done.
353 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
Daniel Dunbarf408f322010-02-14 08:32:05 +0000354 SourceRange Range =
355 cxloc::translateCXSourceRange(clang_getCursorExtent(Cursor));
356 if (Range.isInvalid() || CompareRegionOfInterest(Range))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000357 return false;
358 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000359
Douglas Gregorb1373d02010-01-20 20:59:29 +0000360 switch (Visitor(Cursor, Parent, ClientData)) {
361 case CXChildVisit_Break:
362 return true;
363
364 case CXChildVisit_Continue:
365 return false;
366
367 case CXChildVisit_Recurse:
368 return VisitChildren(Cursor);
369 }
370
Douglas Gregorfd643772010-01-25 16:45:46 +0000371 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000372}
373
374/// \brief Visit the children of the given cursor.
375///
376/// \returns true if the visitation should be aborted, false if it
377/// should continue.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000378bool CursorVisitor::VisitChildren(CXCursor Cursor) {
Douglas Gregora59e3902010-01-21 23:27:09 +0000379 if (clang_isReference(Cursor.kind)) {
380 // By definition, references have no children.
381 return false;
382 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000383
384 // Set the Parent field to Cursor, then back to its old value once we're
Douglas Gregorb1373d02010-01-20 20:59:29 +0000385 // done.
386 class SetParentRAII {
387 CXCursor &Parent;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000388 Decl *&StmtParent;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000389 CXCursor OldParent;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000390
Douglas Gregorb1373d02010-01-20 20:59:29 +0000391 public:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000392 SetParentRAII(CXCursor &Parent, Decl *&StmtParent, CXCursor NewParent)
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000393 : Parent(Parent), StmtParent(StmtParent), OldParent(Parent)
Douglas Gregorb1373d02010-01-20 20:59:29 +0000394 {
395 Parent = NewParent;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000396 if (clang_isDeclaration(Parent.kind))
397 StmtParent = getCursorDecl(Parent);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000398 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000399
Douglas Gregorb1373d02010-01-20 20:59:29 +0000400 ~SetParentRAII() {
401 Parent = OldParent;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000402 if (clang_isDeclaration(Parent.kind))
403 StmtParent = getCursorDecl(Parent);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000404 }
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000405 } SetParent(Parent, StmtParent, Cursor);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000406
Douglas Gregorb1373d02010-01-20 20:59:29 +0000407 if (clang_isDeclaration(Cursor.kind)) {
408 Decl *D = getCursorDecl(Cursor);
409 assert(D && "Invalid declaration cursor");
Ted Kremenek539311e2010-02-18 18:47:01 +0000410 return VisitAttributes(D) || Visit(D);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000411 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000412
Douglas Gregora59e3902010-01-21 23:27:09 +0000413 if (clang_isStatement(Cursor.kind))
414 return Visit(getCursorStmt(Cursor));
415 if (clang_isExpression(Cursor.kind))
416 return Visit(getCursorExpr(Cursor));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000417
Douglas Gregorb1373d02010-01-20 20:59:29 +0000418 if (clang_isTranslationUnit(Cursor.kind)) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000419 ASTUnit *CXXUnit = getCursorASTUnit(Cursor);
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000420 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
421 RegionOfInterest.isInvalid()) {
Douglas Gregor7b691f332010-01-20 21:13:59 +0000422 const std::vector<Decl*> &TLDs = CXXUnit->getTopLevelDecls();
423 for (std::vector<Decl*>::const_iterator it = TLDs.begin(),
424 ie = TLDs.end(); it != ie; ++it) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000425 if (Visit(MakeCXCursor(*it, CXXUnit), true))
Douglas Gregor7b691f332010-01-20 21:13:59 +0000426 return true;
427 }
428 } else {
429 return VisitDeclContext(
Douglas Gregorb1373d02010-01-20 20:59:29 +0000430 CXXUnit->getASTContext().getTranslationUnitDecl());
Douglas Gregor7b691f332010-01-20 21:13:59 +0000431 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000432
Douglas Gregor7b691f332010-01-20 21:13:59 +0000433 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000434 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000435
Douglas Gregorb1373d02010-01-20 20:59:29 +0000436 // Nothing to visit at the moment.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000437 return false;
438}
439
Douglas Gregorb1373d02010-01-20 20:59:29 +0000440bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000441 for (DeclContext::decl_iterator
Douglas Gregorb1373d02010-01-20 20:59:29 +0000442 I = DC->decls_begin(), E = DC->decls_end(); I != E; ++I) {
Ted Kremenek09dfa372010-02-18 05:46:33 +0000443
Daniel Dunbard52864b2010-02-14 10:02:57 +0000444 CXCursor Cursor = MakeCXCursor(*I, TU);
445
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000446 if (RegionOfInterest.isValid()) {
Daniel Dunbard52864b2010-02-14 10:02:57 +0000447 SourceRange Range =
448 cxloc::translateCXSourceRange(clang_getCursorExtent(Cursor));
449 if (Range.isInvalid())
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000450 continue;
Daniel Dunbard52864b2010-02-14 10:02:57 +0000451
452 switch (CompareRegionOfInterest(Range)) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000453 case RangeBefore:
454 // This declaration comes before the region of interest; skip it.
455 continue;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000456
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000457 case RangeAfter:
458 // This declaration comes after the region of interest; we're done.
459 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000460
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000461 case RangeOverlap:
462 // This declaration overlaps the region of interest; visit it.
463 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000464 }
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000465 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000466
Daniel Dunbard52864b2010-02-14 10:02:57 +0000467 if (Visit(Cursor, true))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000468 return true;
469 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000470
Douglas Gregorb1373d02010-01-20 20:59:29 +0000471 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000472}
473
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000474bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
475 llvm_unreachable("Translation units are visited directly by Visit()");
476 return false;
477}
478
479bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
480 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
481 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000482
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000483 return false;
484}
485
486bool CursorVisitor::VisitTagDecl(TagDecl *D) {
487 return VisitDeclContext(D);
488}
489
490bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
491 if (Expr *Init = D->getInitExpr())
492 return Visit(MakeCXCursor(Init, StmtParent, TU));
493 return false;
494}
495
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000496bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
497 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
498 if (Visit(TSInfo->getTypeLoc()))
499 return true;
500
501 return false;
502}
503
Douglas Gregorb1373d02010-01-20 20:59:29 +0000504bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000505 if (VisitDeclaratorDecl(ND))
506 return true;
507
Douglas Gregora59e3902010-01-21 23:27:09 +0000508 if (ND->isThisDeclarationADefinition() &&
509 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
510 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000511
Douglas Gregorb1373d02010-01-20 20:59:29 +0000512 return false;
513}
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000514
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000515bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
516 if (VisitDeclaratorDecl(D))
517 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000518
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000519 if (Expr *BitWidth = D->getBitWidth())
520 return Visit(MakeCXCursor(BitWidth, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000521
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000522 return false;
523}
524
525bool CursorVisitor::VisitVarDecl(VarDecl *D) {
526 if (VisitDeclaratorDecl(D))
527 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000528
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000529 if (Expr *Init = D->getInit())
530 return Visit(MakeCXCursor(Init, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000531
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000532 return false;
533}
534
535bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
Douglas Gregor4bc1cb62010-03-08 14:59:44 +0000536 if (TypeSourceInfo *TSInfo = ND->getResultTypeSourceInfo())
537 if (Visit(TSInfo->getTypeLoc()))
538 return true;
539
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000540 for (ObjCMethodDecl::param_iterator P = ND->param_begin(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000541 PEnd = ND->param_end();
542 P != PEnd; ++P) {
543 if (Visit(MakeCXCursor(*P, TU)))
544 return true;
545 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000546
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000547 if (ND->isThisDeclarationADefinition() &&
548 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
549 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000550
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000551 return false;
552}
553
Douglas Gregora59e3902010-01-21 23:27:09 +0000554bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
555 return VisitDeclContext(D);
556}
557
Douglas Gregorb1373d02010-01-20 20:59:29 +0000558bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000559 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
560 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000561 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000562
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000563 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
564 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
565 E = ND->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000566 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000567 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000568
Douglas Gregora59e3902010-01-21 23:27:09 +0000569 return VisitObjCContainerDecl(ND);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000570}
571
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000572bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
573 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
574 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
575 E = PID->protocol_end(); I != E; ++I, ++PL)
576 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
577 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000578
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000579 return VisitObjCContainerDecl(PID);
580}
581
Douglas Gregorb1373d02010-01-20 20:59:29 +0000582bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000583 // Issue callbacks for super class.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000584 if (D->getSuperClass() &&
585 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000586 D->getSuperClassLoc(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000587 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000588 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000589
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000590 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
591 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
592 E = D->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000593 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000594 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000595
Douglas Gregora59e3902010-01-21 23:27:09 +0000596 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000597}
598
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000599bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
600 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000601}
602
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000603bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000604 if (Visit(MakeCursorObjCClassRef(D->getCategoryDecl()->getClassInterface(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000605 D->getLocation(), TU)))
606 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000607
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000608 return VisitObjCImplDecl(D);
609}
610
611bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
612#if 0
613 // Issue callbacks for super class.
614 // FIXME: No source location information!
615 if (D->getSuperClass() &&
616 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000617 D->getSuperClassLoc(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000618 TU)))
619 return true;
620#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000621
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000622 return VisitObjCImplDecl(D);
623}
624
625bool CursorVisitor::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D) {
626 ObjCForwardProtocolDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
627 for (ObjCForwardProtocolDecl::protocol_iterator I = D->protocol_begin(),
628 E = D->protocol_end();
629 I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000630 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000631 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000632
633 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000634}
635
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000636bool CursorVisitor::VisitObjCClassDecl(ObjCClassDecl *D) {
637 for (ObjCClassDecl::iterator C = D->begin(), CEnd = D->end(); C != CEnd; ++C)
638 if (Visit(MakeCursorObjCClassRef(C->getInterface(), C->getLocation(), TU)))
639 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000640
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000641 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000642}
643
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000644bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
645 ASTContext &Context = TU->getASTContext();
646
647 // Some builtin types (such as Objective-C's "id", "sel", and
648 // "Class") have associated declarations. Create cursors for those.
649 QualType VisitType;
650 switch (TL.getType()->getAs<BuiltinType>()->getKind()) {
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000651 case BuiltinType::Void:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000652 case BuiltinType::Bool:
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000653 case BuiltinType::Char_U:
654 case BuiltinType::UChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000655 case BuiltinType::Char16:
656 case BuiltinType::Char32:
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000657 case BuiltinType::UShort:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000658 case BuiltinType::UInt:
659 case BuiltinType::ULong:
660 case BuiltinType::ULongLong:
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000661 case BuiltinType::UInt128:
662 case BuiltinType::Char_S:
663 case BuiltinType::SChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000664 case BuiltinType::WChar:
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000665 case BuiltinType::Short:
666 case BuiltinType::Int:
667 case BuiltinType::Long:
668 case BuiltinType::LongLong:
669 case BuiltinType::Int128:
670 case BuiltinType::Float:
671 case BuiltinType::Double:
672 case BuiltinType::LongDouble:
673 case BuiltinType::NullPtr:
674 case BuiltinType::Overload:
675 case BuiltinType::Dependent:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000676 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000677
678 case BuiltinType::UndeducedAuto: // FIXME: Deserves a cursor?
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000679 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000680
Ted Kremenekc4174cc2010-02-18 18:52:18 +0000681 case BuiltinType::ObjCId:
682 VisitType = Context.getObjCIdType();
683 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000684
685 case BuiltinType::ObjCClass:
686 VisitType = Context.getObjCClassType();
687 break;
688
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000689 case BuiltinType::ObjCSel:
690 VisitType = Context.getObjCSelType();
691 break;
692 }
693
694 if (!VisitType.isNull()) {
695 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000696 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000697 TU));
698 }
699
700 return false;
701}
702
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000703bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
704 return Visit(MakeCursorTypeRef(TL.getTypedefDecl(), TL.getNameLoc(), TU));
705}
706
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000707bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
708 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
709}
710
711bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
712 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
713}
714
715bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
716 if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
717 return true;
718
719 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
720 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
721 TU)))
722 return true;
723 }
724
725 return false;
726}
727
728bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
729 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseTypeLoc()))
730 return true;
731
732 if (TL.hasProtocolsAsWritten()) {
733 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000734 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I),
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000735 TL.getProtocolLoc(I),
736 TU)))
737 return true;
738 }
739 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000740
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000741 return false;
742}
743
744bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
745 return Visit(TL.getPointeeLoc());
746}
747
748bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
749 return Visit(TL.getPointeeLoc());
750}
751
752bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
753 return Visit(TL.getPointeeLoc());
754}
755
756bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000757 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000758}
759
760bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000761 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000762}
763
764bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
765 if (Visit(TL.getResultLoc()))
766 return true;
767
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000768 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
769 if (Visit(MakeCXCursor(TL.getArg(I), TU)))
770 return true;
771
772 return false;
773}
774
775bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
776 if (Visit(TL.getElementLoc()))
777 return true;
778
779 if (Expr *Size = TL.getSizeExpr())
780 return Visit(MakeCXCursor(Size, StmtParent, TU));
781
782 return false;
783}
784
Douglas Gregor2332c112010-01-21 20:48:56 +0000785bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
786 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
787}
788
789bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
790 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
791 return Visit(TSInfo->getTypeLoc());
792
793 return false;
794}
795
Douglas Gregora59e3902010-01-21 23:27:09 +0000796bool CursorVisitor::VisitStmt(Stmt *S) {
797 for (Stmt::child_iterator Child = S->child_begin(), ChildEnd = S->child_end();
798 Child != ChildEnd; ++Child) {
Daniel Dunbar54d67ca2010-01-25 00:40:30 +0000799 if (*Child && Visit(MakeCXCursor(*Child, StmtParent, TU)))
Douglas Gregora59e3902010-01-21 23:27:09 +0000800 return true;
801 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000802
Douglas Gregora59e3902010-01-21 23:27:09 +0000803 return false;
804}
805
806bool CursorVisitor::VisitDeclStmt(DeclStmt *S) {
807 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
808 D != DEnd; ++D) {
Douglas Gregor263b47b2010-01-25 16:12:32 +0000809 if (*D && Visit(MakeCXCursor(*D, TU)))
Douglas Gregora59e3902010-01-21 23:27:09 +0000810 return true;
811 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000812
Douglas Gregora59e3902010-01-21 23:27:09 +0000813 return false;
814}
815
Douglas Gregorf5bab412010-01-22 01:00:11 +0000816bool CursorVisitor::VisitIfStmt(IfStmt *S) {
817 if (VarDecl *Var = S->getConditionVariable()) {
818 if (Visit(MakeCXCursor(Var, TU)))
819 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000820 }
821
Douglas Gregor263b47b2010-01-25 16:12:32 +0000822 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
823 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +0000824 if (S->getThen() && Visit(MakeCXCursor(S->getThen(), StmtParent, TU)))
825 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +0000826 if (S->getElse() && Visit(MakeCXCursor(S->getElse(), StmtParent, TU)))
827 return true;
828
829 return false;
830}
831
832bool CursorVisitor::VisitSwitchStmt(SwitchStmt *S) {
833 if (VarDecl *Var = S->getConditionVariable()) {
834 if (Visit(MakeCXCursor(Var, TU)))
835 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000836 }
837
Douglas Gregor263b47b2010-01-25 16:12:32 +0000838 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
839 return true;
840 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
841 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000842
Douglas Gregor263b47b2010-01-25 16:12:32 +0000843 return false;
844}
845
846bool CursorVisitor::VisitWhileStmt(WhileStmt *S) {
847 if (VarDecl *Var = S->getConditionVariable()) {
848 if (Visit(MakeCXCursor(Var, TU)))
849 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000850 }
851
Douglas Gregor263b47b2010-01-25 16:12:32 +0000852 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
853 return true;
854 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
Douglas Gregorf5bab412010-01-22 01:00:11 +0000855 return true;
856
Douglas Gregor263b47b2010-01-25 16:12:32 +0000857 return false;
858}
859
860bool CursorVisitor::VisitForStmt(ForStmt *S) {
861 if (S->getInit() && Visit(MakeCXCursor(S->getInit(), StmtParent, TU)))
862 return true;
863 if (VarDecl *Var = S->getConditionVariable()) {
864 if (Visit(MakeCXCursor(Var, TU)))
865 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000866 }
867
Douglas Gregor263b47b2010-01-25 16:12:32 +0000868 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
869 return true;
870 if (S->getInc() && Visit(MakeCXCursor(S->getInc(), StmtParent, TU)))
871 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +0000872 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
873 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000874
Douglas Gregorf5bab412010-01-22 01:00:11 +0000875 return false;
876}
877
Douglas Gregor336fd812010-01-23 00:40:08 +0000878bool CursorVisitor::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E) {
879 if (E->isArgumentType()) {
880 if (TypeSourceInfo *TSInfo = E->getArgumentTypeInfo())
881 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000882
Douglas Gregor336fd812010-01-23 00:40:08 +0000883 return false;
884 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000885
Douglas Gregor336fd812010-01-23 00:40:08 +0000886 return VisitExpr(E);
887}
888
889bool CursorVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
890 if (TypeSourceInfo *TSInfo = E->getTypeInfoAsWritten())
891 if (Visit(TSInfo->getTypeLoc()))
892 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000893
Douglas Gregor336fd812010-01-23 00:40:08 +0000894 return VisitCastExpr(E);
895}
896
897bool CursorVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
898 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
899 if (Visit(TSInfo->getTypeLoc()))
900 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000901
Douglas Gregor336fd812010-01-23 00:40:08 +0000902 return VisitExpr(E);
903}
904
Douglas Gregorc2350e52010-03-08 16:40:19 +0000905bool CursorVisitor::VisitObjCMessageExpr(ObjCMessageExpr *E) {
906 ObjCMessageExpr::ClassInfo CI = E->getClassInfo();
907 if (CI.Decl && Visit(MakeCursorObjCClassRef(CI.Decl, CI.Loc, TU)))
908 return true;
909
910 return VisitExpr(E);
911}
912
Ted Kremenek09dfa372010-02-18 05:46:33 +0000913bool CursorVisitor::VisitAttributes(Decl *D) {
914 for (const Attr *A = D->getAttrs(); A; A = A->getNext())
915 if (Visit(MakeCXCursor(A, D, TU)))
916 return true;
917
918 return false;
919}
920
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000921extern "C" {
Douglas Gregor0a812cf2010-02-18 23:07:20 +0000922CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
923 int displayDiagnostics) {
Douglas Gregora030b7c2010-01-22 20:35:53 +0000924 CIndexer *CIdxr = new CIndexer();
Steve Naroffe56b4ba2009-10-20 14:46:24 +0000925 if (excludeDeclarationsFromPCH)
926 CIdxr->setOnlyLocalDecls();
Douglas Gregor0a812cf2010-02-18 23:07:20 +0000927 if (displayDiagnostics)
928 CIdxr->setDisplayDiagnostics();
Steve Naroffe56b4ba2009-10-20 14:46:24 +0000929 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +0000930}
931
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000932void clang_disposeIndex(CXIndex CIdx) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +0000933 if (CIdx)
934 delete static_cast<CIndexer *>(CIdx);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +0000935}
936
Daniel Dunbar8506dde2009-12-03 01:54:28 +0000937void clang_setUseExternalASTGeneration(CXIndex CIdx, int value) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +0000938 if (CIdx) {
939 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
940 CXXIdx->setUseExternalASTGeneration(value);
941 }
Daniel Dunbar8506dde2009-12-03 01:54:28 +0000942}
943
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000944CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
Douglas Gregora88084b2010-02-18 18:08:43 +0000945 const char *ast_filename) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +0000946 if (!CIdx)
947 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000948
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000949 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000950
Douglas Gregor5352ac02010-01-28 00:27:43 +0000951 // Configure the diagnostics.
952 DiagnosticOptions DiagOpts;
953 llvm::OwningPtr<Diagnostic> Diags;
954 Diags.reset(CompilerInstance::createDiagnostics(DiagOpts, 0, 0));
Douglas Gregor5352ac02010-01-28 00:27:43 +0000955 return ASTUnit::LoadFromPCHFile(ast_filename, *Diags,
Douglas Gregora88084b2010-02-18 18:08:43 +0000956 CXXIdx->getOnlyLocalDecls(),
957 0, 0, true);
Steve Naroff600866c2009-08-27 19:51:58 +0000958}
959
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000960CXTranslationUnit
961clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
962 const char *source_filename,
963 int num_command_line_args,
Douglas Gregor4db64a42010-01-23 00:14:00 +0000964 const char **command_line_args,
965 unsigned num_unsaved_files,
Douglas Gregora88084b2010-02-18 18:08:43 +0000966 struct CXUnsavedFile *unsaved_files) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +0000967 if (!CIdx)
968 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000969
Steve Naroffe56b4ba2009-10-20 14:46:24 +0000970 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
971
Douglas Gregor5352ac02010-01-28 00:27:43 +0000972 // Configure the diagnostics.
973 DiagnosticOptions DiagOpts;
974 llvm::OwningPtr<Diagnostic> Diags;
975 Diags.reset(CompilerInstance::createDiagnostics(DiagOpts, 0, 0));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000976
Douglas Gregor4db64a42010-01-23 00:14:00 +0000977 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
978 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000979 const llvm::MemoryBuffer *Buffer
Douglas Gregorc8dfe5e2010-02-27 01:32:48 +0000980 = llvm::MemoryBuffer::getMemBufferCopy(unsaved_files[I].Contents,
Douglas Gregor313e26c2010-02-18 23:35:40 +0000981 unsaved_files[I].Contents + unsaved_files[I].Length,
982 unsaved_files[I].Filename);
Douglas Gregor4db64a42010-01-23 00:14:00 +0000983 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
984 Buffer));
985 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000986
Daniel Dunbar8506dde2009-12-03 01:54:28 +0000987 if (!CXXIdx->getUseExternalASTGeneration()) {
988 llvm::SmallVector<const char *, 16> Args;
989
990 // The 'source_filename' argument is optional. If the caller does not
991 // specify it then it is assumed that the source file is specified
992 // in the actual argument list.
993 if (source_filename)
994 Args.push_back(source_filename);
995 Args.insert(Args.end(), command_line_args,
996 command_line_args + num_command_line_args);
997
Douglas Gregor5352ac02010-01-28 00:27:43 +0000998 unsigned NumErrors = Diags->getNumErrors();
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000999
Ted Kremenek29b72842010-01-07 22:49:05 +00001000#ifdef USE_CRASHTRACER
1001 ArgsCrashTracerInfo ACTI(Args);
Ted Kremenek8a8da7d2010-01-06 03:42:32 +00001002#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001003
Daniel Dunbar94220972009-12-05 02:17:18 +00001004 llvm::OwningPtr<ASTUnit> Unit(
1005 ASTUnit::LoadFromCommandLine(Args.data(), Args.data() + Args.size(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001006 *Diags,
Daniel Dunbar869824e2009-12-13 03:46:13 +00001007 CXXIdx->getClangResourcesPath(),
Daniel Dunbar94220972009-12-05 02:17:18 +00001008 CXXIdx->getOnlyLocalDecls(),
Douglas Gregor4db64a42010-01-23 00:14:00 +00001009 RemappedFiles.data(),
Douglas Gregora88084b2010-02-18 18:08:43 +00001010 RemappedFiles.size(),
1011 /*CaptureDiagnostics=*/true));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001012
Daniel Dunbar94220972009-12-05 02:17:18 +00001013 // FIXME: Until we have broader testing, just drop the entire AST if we
1014 // encountered an error.
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001015 if (NumErrors != Diags->getNumErrors()) {
Ted Kremenek34f6a322010-03-05 22:43:29 +00001016 // Make sure to check that 'Unit' is non-NULL.
1017 if (CXXIdx->getDisplayDiagnostics() && Unit.get()) {
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001018 for (ASTUnit::diag_iterator D = Unit->diag_begin(),
1019 DEnd = Unit->diag_end();
1020 D != DEnd; ++D) {
1021 CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOptions());
Douglas Gregor274f1902010-02-22 23:17:23 +00001022 CXString Msg = clang_formatDiagnostic(&Diag,
1023 clang_defaultDiagnosticDisplayOptions());
1024 fprintf(stderr, "%s\n", clang_getCString(Msg));
1025 clang_disposeString(Msg);
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001026 }
Douglas Gregor274f1902010-02-22 23:17:23 +00001027#ifdef LLVM_ON_WIN32
1028 // On Windows, force a flush, since there may be multiple copies of
1029 // stderr and stdout in the file system, all with different buffers
1030 // but writing to the same device.
1031 fflush(stderr);
1032#endif
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001033 }
Daniel Dunbar94220972009-12-05 02:17:18 +00001034 return 0;
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001035 }
Daniel Dunbar94220972009-12-05 02:17:18 +00001036
1037 return Unit.take();
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001038 }
1039
Ted Kremenek139ba862009-10-22 00:03:57 +00001040 // Build up the arguments for invoking 'clang'.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001041 std::vector<const char *> argv;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001042
Ted Kremenek139ba862009-10-22 00:03:57 +00001043 // First add the complete path to the 'clang' executable.
1044 llvm::sys::Path ClangPath = static_cast<CIndexer *>(CIdx)->getClangPath();
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00001045 argv.push_back(ClangPath.c_str());
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001046
Ted Kremenek139ba862009-10-22 00:03:57 +00001047 // Add the '-emit-ast' option as our execution mode for 'clang'.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001048 argv.push_back("-emit-ast");
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001049
Ted Kremenek139ba862009-10-22 00:03:57 +00001050 // The 'source_filename' argument is optional. If the caller does not
1051 // specify it then it is assumed that the source file is specified
1052 // in the actual argument list.
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001053 if (source_filename)
1054 argv.push_back(source_filename);
Ted Kremenek139ba862009-10-22 00:03:57 +00001055
Steve Naroff37b5ac22009-10-15 20:50:09 +00001056 // Generate a temporary name for the AST file.
Ted Kremenek139ba862009-10-22 00:03:57 +00001057 argv.push_back("-o");
Benjamin Kramerc2a98162010-03-13 21:22:49 +00001058 char astTmpFile[L_tmpnam];
1059 argv.push_back(tmpnam(astTmpFile));
Ted Kremenek139ba862009-10-22 00:03:57 +00001060
Douglas Gregor4db64a42010-01-23 00:14:00 +00001061 // Remap any unsaved files to temporary files.
1062 std::vector<llvm::sys::Path> TemporaryFiles;
1063 std::vector<std::string> RemapArgs;
1064 if (RemapFiles(num_unsaved_files, unsaved_files, RemapArgs, TemporaryFiles))
1065 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001066
Douglas Gregor4db64a42010-01-23 00:14:00 +00001067 // The pointers into the elements of RemapArgs are stable because we
1068 // won't be adding anything to RemapArgs after this point.
1069 for (unsigned i = 0, e = RemapArgs.size(); i != e; ++i)
1070 argv.push_back(RemapArgs[i].c_str());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001071
Ted Kremenek139ba862009-10-22 00:03:57 +00001072 // Process the compiler options, stripping off '-o', '-c', '-fsyntax-only'.
1073 for (int i = 0; i < num_command_line_args; ++i)
1074 if (const char *arg = command_line_args[i]) {
1075 if (strcmp(arg, "-o") == 0) {
1076 ++i; // Also skip the matching argument.
1077 continue;
1078 }
1079 if (strcmp(arg, "-emit-ast") == 0 ||
1080 strcmp(arg, "-c") == 0 ||
1081 strcmp(arg, "-fsyntax-only") == 0) {
1082 continue;
1083 }
1084
1085 // Keep the argument.
1086 argv.push_back(arg);
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001087 }
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001088
Douglas Gregord93256e2010-01-28 06:00:51 +00001089 // Generate a temporary name for the diagnostics file.
Benjamin Kramerc2a98162010-03-13 21:22:49 +00001090 char tmpFileResults[L_tmpnam];
1091 char *tmpResultsFileName = tmpnam(tmpFileResults);
1092 llvm::sys::Path DiagnosticsFile(tmpResultsFileName);
Douglas Gregord93256e2010-01-28 06:00:51 +00001093 TemporaryFiles.push_back(DiagnosticsFile);
1094 argv.push_back("-fdiagnostics-binary");
1095
Ted Kremenek139ba862009-10-22 00:03:57 +00001096 // Add the null terminator.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001097 argv.push_back(NULL);
1098
Ted Kremenekfeb15e32009-10-26 22:14:08 +00001099 // Invoke 'clang'.
1100 llvm::sys::Path DevNull; // leave empty, causes redirection to /dev/null
1101 // on Unix or NUL (Windows).
Ted Kremenek379afec2009-10-22 03:24:01 +00001102 std::string ErrMsg;
Douglas Gregord93256e2010-01-28 06:00:51 +00001103 const llvm::sys::Path *Redirects[] = { &DevNull, &DevNull, &DiagnosticsFile,
1104 NULL };
Ted Kremenek379afec2009-10-22 03:24:01 +00001105 llvm::sys::Program::ExecuteAndWait(ClangPath, &argv[0], /* env */ NULL,
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001106 /* redirects */ &Redirects[0],
Ted Kremenek379afec2009-10-22 03:24:01 +00001107 /* secondsToWait */ 0, /* memoryLimits */ 0, &ErrMsg);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001108
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001109 if (!ErrMsg.empty()) {
1110 std::string AllArgs;
Ted Kremenek379afec2009-10-22 03:24:01 +00001111 for (std::vector<const char*>::iterator I = argv.begin(), E = argv.end();
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001112 I != E; ++I) {
1113 AllArgs += ' ';
Ted Kremenek779e5f42009-10-26 22:08:39 +00001114 if (*I)
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001115 AllArgs += *I;
Ted Kremenek779e5f42009-10-26 22:08:39 +00001116 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001117
Daniel Dunbar32141c82010-02-23 20:23:45 +00001118 Diags->Report(diag::err_fe_invoking) << AllArgs << ErrMsg;
Ted Kremenek379afec2009-10-22 03:24:01 +00001119 }
Benjamin Kramer0829a832009-10-18 11:19:36 +00001120
Benjamin Kramerc2a98162010-03-13 21:22:49 +00001121 ASTUnit *ATU = ASTUnit::LoadFromPCHFile(astTmpFile, *Diags,
Douglas Gregor4db64a42010-01-23 00:14:00 +00001122 CXXIdx->getOnlyLocalDecls(),
Douglas Gregor4db64a42010-01-23 00:14:00 +00001123 RemappedFiles.data(),
Douglas Gregora88084b2010-02-18 18:08:43 +00001124 RemappedFiles.size(),
1125 /*CaptureDiagnostics=*/true);
Douglas Gregora88084b2010-02-18 18:08:43 +00001126 if (ATU) {
1127 LoadSerializedDiagnostics(DiagnosticsFile,
1128 num_unsaved_files, unsaved_files,
1129 ATU->getFileManager(),
1130 ATU->getSourceManager(),
1131 ATU->getDiagnostics());
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001132 } else if (CXXIdx->getDisplayDiagnostics()) {
1133 // We failed to load the ASTUnit, but we can still deserialize the
1134 // diagnostics and emit them.
1135 FileManager FileMgr;
Douglas Gregorf715ca12010-03-16 00:06:06 +00001136 Diagnostic Diag;
1137 SourceManager SourceMgr(Diag);
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001138 // FIXME: Faked LangOpts!
1139 LangOptions LangOpts;
1140 llvm::SmallVector<StoredDiagnostic, 4> Diags;
1141 LoadSerializedDiagnostics(DiagnosticsFile,
1142 num_unsaved_files, unsaved_files,
1143 FileMgr, SourceMgr, Diags);
1144 for (llvm::SmallVector<StoredDiagnostic, 4>::iterator D = Diags.begin(),
1145 DEnd = Diags.end();
1146 D != DEnd; ++D) {
1147 CXStoredDiagnostic Diag(*D, LangOpts);
Douglas Gregor274f1902010-02-22 23:17:23 +00001148 CXString Msg = clang_formatDiagnostic(&Diag,
1149 clang_defaultDiagnosticDisplayOptions());
1150 fprintf(stderr, "%s\n", clang_getCString(Msg));
1151 clang_disposeString(Msg);
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001152 }
Douglas Gregor274f1902010-02-22 23:17:23 +00001153
1154#ifdef LLVM_ON_WIN32
1155 // On Windows, force a flush, since there may be multiple copies of
1156 // stderr and stdout in the file system, all with different buffers
1157 // but writing to the same device.
1158 fflush(stderr);
1159#endif
Douglas Gregora88084b2010-02-18 18:08:43 +00001160 }
Douglas Gregord93256e2010-01-28 06:00:51 +00001161
Douglas Gregor313e26c2010-02-18 23:35:40 +00001162 if (ATU) {
1163 // Make the translation unit responsible for destroying all temporary files.
1164 for (unsigned i = 0, e = TemporaryFiles.size(); i != e; ++i)
1165 ATU->addTemporaryFile(TemporaryFiles[i]);
1166 ATU->addTemporaryFile(llvm::sys::Path(ATU->getPCHFileName()));
1167 } else {
1168 // Destroy all of the temporary files now; they can't be referenced any
1169 // longer.
1170 llvm::sys::Path(astTmpFile).eraseFromDisk();
1171 for (unsigned i = 0, e = TemporaryFiles.size(); i != e; ++i)
1172 TemporaryFiles[i].eraseFromDisk();
1173 }
1174
Steve Naroffe19944c2009-10-15 22:23:48 +00001175 return ATU;
Steve Naroff5b7d8e22009-10-15 20:04:39 +00001176}
1177
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001178void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001179 if (CTUnit)
1180 delete static_cast<ASTUnit *>(CTUnit);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00001181}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001182
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001183CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001184 if (!CTUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001185 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001186
Steve Naroff77accc12009-09-03 18:19:54 +00001187 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001188 return createCXString(CXXUnit->getOriginalSourceFileName(), true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +00001189}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +00001190
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001191CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001192 CXCursor Result = { CXCursor_TranslationUnit, { 0, 0, TU } };
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001193 return Result;
1194}
1195
Ted Kremenekfb480492010-01-13 21:46:36 +00001196} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +00001197
Ted Kremenekfb480492010-01-13 21:46:36 +00001198//===----------------------------------------------------------------------===//
Douglas Gregor1db19de2010-01-19 21:36:55 +00001199// CXSourceLocation and CXSourceRange Operations.
1200//===----------------------------------------------------------------------===//
1201
Douglas Gregorb9790342010-01-22 21:44:22 +00001202extern "C" {
1203CXSourceLocation clang_getNullLocation() {
Douglas Gregor5352ac02010-01-28 00:27:43 +00001204 CXSourceLocation Result = { { 0, 0 }, 0 };
Douglas Gregorb9790342010-01-22 21:44:22 +00001205 return Result;
1206}
1207
1208unsigned clang_equalLocations(CXSourceLocation loc1, CXSourceLocation loc2) {
Daniel Dunbar90a6b9e2010-01-30 23:58:27 +00001209 return (loc1.ptr_data[0] == loc2.ptr_data[0] &&
1210 loc1.ptr_data[1] == loc2.ptr_data[1] &&
1211 loc1.int_data == loc2.int_data);
Douglas Gregorb9790342010-01-22 21:44:22 +00001212}
1213
1214CXSourceLocation clang_getLocation(CXTranslationUnit tu,
1215 CXFile file,
1216 unsigned line,
1217 unsigned column) {
1218 if (!tu)
1219 return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001220
Douglas Gregorb9790342010-01-22 21:44:22 +00001221 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
1222 SourceLocation SLoc
1223 = CXXUnit->getSourceManager().getLocation(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001224 static_cast<const FileEntry *>(file),
Douglas Gregorb9790342010-01-22 21:44:22 +00001225 line, column);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001226
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00001227 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
Douglas Gregorb9790342010-01-22 21:44:22 +00001228}
1229
Douglas Gregor5352ac02010-01-28 00:27:43 +00001230CXSourceRange clang_getNullRange() {
1231 CXSourceRange Result = { { 0, 0 }, 0, 0 };
1232 return Result;
1233}
Daniel Dunbard52864b2010-02-14 10:02:57 +00001234
Douglas Gregor5352ac02010-01-28 00:27:43 +00001235CXSourceRange clang_getRange(CXSourceLocation begin, CXSourceLocation end) {
1236 if (begin.ptr_data[0] != end.ptr_data[0] ||
1237 begin.ptr_data[1] != end.ptr_data[1])
1238 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001239
1240 CXSourceRange Result = { { begin.ptr_data[0], begin.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00001241 begin.int_data, end.int_data };
Douglas Gregorb9790342010-01-22 21:44:22 +00001242 return Result;
1243}
1244
Douglas Gregor46766dc2010-01-26 19:19:08 +00001245void clang_getInstantiationLocation(CXSourceLocation location,
1246 CXFile *file,
1247 unsigned *line,
1248 unsigned *column,
1249 unsigned *offset) {
Douglas Gregor1db19de2010-01-19 21:36:55 +00001250 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
1251
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00001252 if (!location.ptr_data[0] || Loc.isInvalid()) {
Douglas Gregor46766dc2010-01-26 19:19:08 +00001253 if (file)
1254 *file = 0;
1255 if (line)
1256 *line = 0;
1257 if (column)
1258 *column = 0;
1259 if (offset)
1260 *offset = 0;
1261 return;
1262 }
1263
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00001264 const SourceManager &SM =
1265 *static_cast<const SourceManager*>(location.ptr_data[0]);
Douglas Gregor1db19de2010-01-19 21:36:55 +00001266 SourceLocation InstLoc = SM.getInstantiationLoc(Loc);
Douglas Gregor1db19de2010-01-19 21:36:55 +00001267
1268 if (file)
1269 *file = (void *)SM.getFileEntryForID(SM.getFileID(InstLoc));
1270 if (line)
1271 *line = SM.getInstantiationLineNumber(InstLoc);
1272 if (column)
1273 *column = SM.getInstantiationColumnNumber(InstLoc);
Douglas Gregore69517c2010-01-26 03:07:15 +00001274 if (offset)
Douglas Gregor46766dc2010-01-26 19:19:08 +00001275 *offset = SM.getDecomposedLoc(InstLoc).second;
Douglas Gregore69517c2010-01-26 03:07:15 +00001276}
1277
Douglas Gregor1db19de2010-01-19 21:36:55 +00001278CXSourceLocation clang_getRangeStart(CXSourceRange range) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001279 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00001280 range.begin_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00001281 return Result;
1282}
1283
1284CXSourceLocation clang_getRangeEnd(CXSourceRange range) {
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00001285 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00001286 range.end_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00001287 return Result;
1288}
1289
Douglas Gregorb9790342010-01-22 21:44:22 +00001290} // end: extern "C"
1291
Douglas Gregor1db19de2010-01-19 21:36:55 +00001292//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00001293// CXFile Operations.
1294//===----------------------------------------------------------------------===//
1295
1296extern "C" {
Ted Kremenek74844072010-02-17 00:41:20 +00001297CXString clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00001298 if (!SFile)
Ted Kremenek74844072010-02-17 00:41:20 +00001299 return createCXString(NULL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001300
Steve Naroff88145032009-10-27 14:35:18 +00001301 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Ted Kremenek74844072010-02-17 00:41:20 +00001302 return createCXString(FEnt->getName());
Steve Naroff88145032009-10-27 14:35:18 +00001303}
1304
1305time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00001306 if (!SFile)
1307 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001308
Steve Naroff88145032009-10-27 14:35:18 +00001309 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
1310 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +00001311}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001312
Douglas Gregorb9790342010-01-22 21:44:22 +00001313CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
1314 if (!tu)
1315 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001316
Douglas Gregorb9790342010-01-22 21:44:22 +00001317 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001318
Douglas Gregorb9790342010-01-22 21:44:22 +00001319 FileManager &FMgr = CXXUnit->getFileManager();
1320 const FileEntry *File = FMgr.getFile(file_name, file_name+strlen(file_name));
1321 return const_cast<FileEntry *>(File);
1322}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001323
Ted Kremenekfb480492010-01-13 21:46:36 +00001324} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +00001325
Ted Kremenekfb480492010-01-13 21:46:36 +00001326//===----------------------------------------------------------------------===//
1327// CXCursor Operations.
1328//===----------------------------------------------------------------------===//
1329
Ted Kremenekfb480492010-01-13 21:46:36 +00001330static Decl *getDeclFromExpr(Stmt *E) {
1331 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
1332 return RefExpr->getDecl();
1333 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
1334 return ME->getMemberDecl();
1335 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
1336 return RE->getDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001337
Ted Kremenekfb480492010-01-13 21:46:36 +00001338 if (CallExpr *CE = dyn_cast<CallExpr>(E))
1339 return getDeclFromExpr(CE->getCallee());
1340 if (CastExpr *CE = dyn_cast<CastExpr>(E))
1341 return getDeclFromExpr(CE->getSubExpr());
1342 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
1343 return OME->getMethodDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001344
Ted Kremenekfb480492010-01-13 21:46:36 +00001345 return 0;
1346}
1347
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00001348static SourceLocation getLocationFromExpr(Expr *E) {
1349 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
1350 return /*FIXME:*/Msg->getLeftLoc();
1351 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
1352 return DRE->getLocation();
1353 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
1354 return Member->getMemberLoc();
1355 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
1356 return Ivar->getLocation();
1357 return E->getLocStart();
1358}
1359
Ted Kremenekfb480492010-01-13 21:46:36 +00001360extern "C" {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001361
1362unsigned clang_visitChildren(CXCursor parent,
Douglas Gregorb1373d02010-01-20 20:59:29 +00001363 CXCursorVisitor visitor,
1364 CXClientData client_data) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001365 ASTUnit *CXXUnit = getCursorASTUnit(parent);
Douglas Gregorb1373d02010-01-20 20:59:29 +00001366
1367 unsigned PCHLevel = Decl::MaxPCHLevel;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001368
Douglas Gregorb1373d02010-01-20 20:59:29 +00001369 // Set the PCHLevel to filter out unwanted decls if requested.
1370 if (CXXUnit->getOnlyLocalDecls()) {
1371 PCHLevel = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001372
Douglas Gregorb1373d02010-01-20 20:59:29 +00001373 // If the main input was an AST, bump the level.
1374 if (CXXUnit->isMainFileAST())
1375 ++PCHLevel;
1376 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001377
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001378 CursorVisitor CursorVis(CXXUnit, visitor, client_data, PCHLevel);
Douglas Gregorb1373d02010-01-20 20:59:29 +00001379 return CursorVis.VisitChildren(parent);
1380}
1381
Douglas Gregor78205d42010-01-20 21:45:58 +00001382static CXString getDeclSpelling(Decl *D) {
1383 NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
1384 if (!ND)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001385 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001386
Douglas Gregor78205d42010-01-20 21:45:58 +00001387 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001388 return createCXString(OMD->getSelector().getAsString());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001389
Douglas Gregor78205d42010-01-20 21:45:58 +00001390 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
1391 // No, this isn't the same as the code below. getIdentifier() is non-virtual
1392 // and returns different names. NamedDecl returns the class name and
1393 // ObjCCategoryImplDecl returns the category name.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001394 return createCXString(CIMP->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001395
Douglas Gregor78205d42010-01-20 21:45:58 +00001396 if (ND->getIdentifier())
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001397 return createCXString(ND->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001398
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001399 return createCXString("");
Douglas Gregor78205d42010-01-20 21:45:58 +00001400}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001401
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001402CXString clang_getCursorSpelling(CXCursor C) {
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001403 if (clang_isTranslationUnit(C.kind))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001404 return clang_getTranslationUnitSpelling(C.data[2]);
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001405
Steve Narofff334b4e2009-09-02 18:26:48 +00001406 if (clang_isReference(C.kind)) {
1407 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00001408 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +00001409 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001410 return createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00001411 }
1412 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +00001413 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001414 return createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00001415 }
1416 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +00001417 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +00001418 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001419 return createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00001420 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001421 case CXCursor_TypeRef: {
1422 TypeDecl *Type = getCursorTypeRef(C).first;
1423 assert(Type && "Missing type decl");
1424
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001425 return createCXString(getCursorContext(C).getTypeDeclType(Type).
1426 getAsString());
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001427 }
1428
Daniel Dunbaracca7252009-11-30 20:42:49 +00001429 default:
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001430 return createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +00001431 }
1432 }
Douglas Gregor97b98722010-01-19 23:20:36 +00001433
1434 if (clang_isExpression(C.kind)) {
1435 Decl *D = getDeclFromExpr(getCursorExpr(C));
1436 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +00001437 return getDeclSpelling(D);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001438 return createCXString("");
Douglas Gregor97b98722010-01-19 23:20:36 +00001439 }
1440
Douglas Gregor60cbfac2010-01-25 16:56:17 +00001441 if (clang_isDeclaration(C.kind))
1442 return getDeclSpelling(getCursorDecl(C));
Ted Kremeneke68fff62010-02-17 00:41:32 +00001443
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001444 return createCXString("");
Steve Narofff334b4e2009-09-02 18:26:48 +00001445}
1446
Ted Kremeneke68fff62010-02-17 00:41:32 +00001447CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00001448 switch (Kind) {
Ted Kremeneke68fff62010-02-17 00:41:32 +00001449 case CXCursor_FunctionDecl:
1450 return createCXString("FunctionDecl");
1451 case CXCursor_TypedefDecl:
1452 return createCXString("TypedefDecl");
1453 case CXCursor_EnumDecl:
1454 return createCXString("EnumDecl");
1455 case CXCursor_EnumConstantDecl:
1456 return createCXString("EnumConstantDecl");
1457 case CXCursor_StructDecl:
1458 return createCXString("StructDecl");
1459 case CXCursor_UnionDecl:
1460 return createCXString("UnionDecl");
1461 case CXCursor_ClassDecl:
1462 return createCXString("ClassDecl");
1463 case CXCursor_FieldDecl:
1464 return createCXString("FieldDecl");
1465 case CXCursor_VarDecl:
1466 return createCXString("VarDecl");
1467 case CXCursor_ParmDecl:
1468 return createCXString("ParmDecl");
1469 case CXCursor_ObjCInterfaceDecl:
1470 return createCXString("ObjCInterfaceDecl");
1471 case CXCursor_ObjCCategoryDecl:
1472 return createCXString("ObjCCategoryDecl");
1473 case CXCursor_ObjCProtocolDecl:
1474 return createCXString("ObjCProtocolDecl");
1475 case CXCursor_ObjCPropertyDecl:
1476 return createCXString("ObjCPropertyDecl");
1477 case CXCursor_ObjCIvarDecl:
1478 return createCXString("ObjCIvarDecl");
1479 case CXCursor_ObjCInstanceMethodDecl:
1480 return createCXString("ObjCInstanceMethodDecl");
1481 case CXCursor_ObjCClassMethodDecl:
1482 return createCXString("ObjCClassMethodDecl");
1483 case CXCursor_ObjCImplementationDecl:
1484 return createCXString("ObjCImplementationDecl");
1485 case CXCursor_ObjCCategoryImplDecl:
1486 return createCXString("ObjCCategoryImplDecl");
1487 case CXCursor_UnexposedDecl:
1488 return createCXString("UnexposedDecl");
1489 case CXCursor_ObjCSuperClassRef:
1490 return createCXString("ObjCSuperClassRef");
1491 case CXCursor_ObjCProtocolRef:
1492 return createCXString("ObjCProtocolRef");
1493 case CXCursor_ObjCClassRef:
1494 return createCXString("ObjCClassRef");
1495 case CXCursor_TypeRef:
1496 return createCXString("TypeRef");
1497 case CXCursor_UnexposedExpr:
1498 return createCXString("UnexposedExpr");
1499 case CXCursor_DeclRefExpr:
1500 return createCXString("DeclRefExpr");
1501 case CXCursor_MemberRefExpr:
1502 return createCXString("MemberRefExpr");
1503 case CXCursor_CallExpr:
1504 return createCXString("CallExpr");
1505 case CXCursor_ObjCMessageExpr:
1506 return createCXString("ObjCMessageExpr");
1507 case CXCursor_UnexposedStmt:
1508 return createCXString("UnexposedStmt");
1509 case CXCursor_InvalidFile:
1510 return createCXString("InvalidFile");
1511 case CXCursor_NoDeclFound:
1512 return createCXString("NoDeclFound");
1513 case CXCursor_NotImplemented:
1514 return createCXString("NotImplemented");
1515 case CXCursor_TranslationUnit:
1516 return createCXString("TranslationUnit");
Ted Kremeneke77f4432010-02-18 03:09:07 +00001517 case CXCursor_UnexposedAttr:
1518 return createCXString("UnexposedAttr");
1519 case CXCursor_IBActionAttr:
1520 return createCXString("attribute(ibaction)");
1521 case CXCursor_IBOutletAttr:
1522 return createCXString("attribute(iboutlet)");
Steve Naroff89922f82009-08-31 00:59:03 +00001523 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00001524
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00001525 llvm_unreachable("Unhandled CXCursorKind");
Ted Kremeneke68fff62010-02-17 00:41:32 +00001526 return createCXString(NULL);
Steve Naroff600866c2009-08-27 19:51:58 +00001527}
Steve Naroff89922f82009-08-31 00:59:03 +00001528
Ted Kremeneke68fff62010-02-17 00:41:32 +00001529enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
1530 CXCursor parent,
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001531 CXClientData client_data) {
1532 CXCursor *BestCursor = static_cast<CXCursor *>(client_data);
1533 *BestCursor = cursor;
1534 return CXChildVisit_Recurse;
1535}
Ted Kremeneke68fff62010-02-17 00:41:32 +00001536
Douglas Gregorb9790342010-01-22 21:44:22 +00001537CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
1538 if (!TU)
Ted Kremenekf4629892010-01-14 01:51:23 +00001539 return clang_getNullCursor();
Ted Kremeneke68fff62010-02-17 00:41:32 +00001540
Douglas Gregorb9790342010-01-22 21:44:22 +00001541 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
1542
Douglas Gregorbdf60622010-03-05 21:16:25 +00001543 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
1544
Ted Kremeneka297de22010-01-25 22:34:44 +00001545 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001546 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
1547 if (SLoc.isValid()) {
Daniel Dunbard52864b2010-02-14 10:02:57 +00001548 SourceRange RegionOfInterest(SLoc, SLoc.getFileLocWithOffset(1));
Ted Kremeneke68fff62010-02-17 00:41:32 +00001549
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001550 // FIXME: Would be great to have a "hint" cursor, then walk from that
1551 // hint cursor upward until we find a cursor whose source range encloses
1552 // the region of interest, rather than starting from the translation unit.
1553 CXCursor Parent = clang_getTranslationUnitCursor(CXXUnit);
Ted Kremeneke68fff62010-02-17 00:41:32 +00001554 CursorVisitor CursorVis(CXXUnit, GetCursorVisitor, &Result,
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001555 Decl::MaxPCHLevel, RegionOfInterest);
1556 CursorVis.VisitChildren(Parent);
Steve Naroff77128dd2009-09-15 20:25:34 +00001557 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00001558 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00001559}
1560
Ted Kremenek73885552009-11-17 19:28:59 +00001561CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00001562 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00001563}
1564
1565unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00001566 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00001567}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001568
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001569unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00001570 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
1571}
1572
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001573unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +00001574 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
1575}
Steve Naroff2d4d6292009-08-31 14:26:51 +00001576
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001577unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00001578 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
1579}
1580
Douglas Gregor97b98722010-01-19 23:20:36 +00001581unsigned clang_isExpression(enum CXCursorKind K) {
1582 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
1583}
1584
1585unsigned clang_isStatement(enum CXCursorKind K) {
1586 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
1587}
1588
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001589unsigned clang_isTranslationUnit(enum CXCursorKind K) {
1590 return K == CXCursor_TranslationUnit;
1591}
1592
Ted Kremenekad6eff62010-03-08 21:17:29 +00001593unsigned clang_isUnexposed(enum CXCursorKind K) {
1594 switch (K) {
1595 case CXCursor_UnexposedDecl:
1596 case CXCursor_UnexposedExpr:
1597 case CXCursor_UnexposedStmt:
1598 case CXCursor_UnexposedAttr:
1599 return true;
1600 default:
1601 return false;
1602 }
1603}
1604
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001605CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00001606 return C.kind;
1607}
1608
Douglas Gregor98258af2010-01-18 22:46:11 +00001609CXSourceLocation clang_getCursorLocation(CXCursor C) {
1610 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00001611 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001612 case CXCursor_ObjCSuperClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00001613 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1614 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001615 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001616 }
1617
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001618 case CXCursor_ObjCProtocolRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00001619 std::pair<ObjCProtocolDecl *, SourceLocation> P
1620 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001621 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001622 }
1623
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001624 case CXCursor_ObjCClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00001625 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1626 = getCursorObjCClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001627 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001628 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001629
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001630 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001631 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001632 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001633 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001634
Douglas Gregorf46034a2010-01-18 23:41:10 +00001635 default:
1636 // FIXME: Need a way to enumerate all non-reference cases.
1637 llvm_unreachable("Missed a reference kind");
1638 }
Douglas Gregor98258af2010-01-18 22:46:11 +00001639 }
Douglas Gregor97b98722010-01-19 23:20:36 +00001640
1641 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001642 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00001643 getLocationFromExpr(getCursorExpr(C)));
1644
Douglas Gregor5352ac02010-01-28 00:27:43 +00001645 if (!getCursorDecl(C))
1646 return clang_getNullLocation();
Douglas Gregor98258af2010-01-18 22:46:11 +00001647
Douglas Gregorf46034a2010-01-18 23:41:10 +00001648 Decl *D = getCursorDecl(C);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001649 SourceLocation Loc = D->getLocation();
1650 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
1651 Loc = Class->getClassLoc();
Ted Kremeneka297de22010-01-25 22:34:44 +00001652 return cxloc::translateSourceLocation(D->getASTContext(), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00001653}
Douglas Gregora7bde202010-01-19 00:34:46 +00001654
1655CXSourceRange clang_getCursorExtent(CXCursor C) {
1656 if (clang_isReference(C.kind)) {
1657 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001658 case CXCursor_ObjCSuperClassRef: {
Douglas Gregora7bde202010-01-19 00:34:46 +00001659 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1660 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001661 return cxloc::translateSourceRange(P.first->getASTContext(), P.second);
Douglas Gregora7bde202010-01-19 00:34:46 +00001662 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001663
1664 case CXCursor_ObjCProtocolRef: {
Douglas Gregora7bde202010-01-19 00:34:46 +00001665 std::pair<ObjCProtocolDecl *, SourceLocation> P
1666 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001667 return cxloc::translateSourceRange(P.first->getASTContext(), P.second);
Douglas Gregora7bde202010-01-19 00:34:46 +00001668 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001669
1670 case CXCursor_ObjCClassRef: {
Douglas Gregora7bde202010-01-19 00:34:46 +00001671 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1672 = getCursorObjCClassRef(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001673
Ted Kremeneka297de22010-01-25 22:34:44 +00001674 return cxloc::translateSourceRange(P.first->getASTContext(), P.second);
Douglas Gregora7bde202010-01-19 00:34:46 +00001675 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001676
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001677 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001678 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001679 return cxloc::translateSourceRange(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001680 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001681
Douglas Gregora7bde202010-01-19 00:34:46 +00001682 default:
1683 // FIXME: Need a way to enumerate all non-reference cases.
1684 llvm_unreachable("Missed a reference kind");
1685 }
1686 }
Douglas Gregor97b98722010-01-19 23:20:36 +00001687
1688 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001689 return cxloc::translateSourceRange(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00001690 getCursorExpr(C)->getSourceRange());
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001691
1692 if (clang_isStatement(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001693 return cxloc::translateSourceRange(getCursorContext(C),
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001694 getCursorStmt(C)->getSourceRange());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001695
Douglas Gregor5352ac02010-01-28 00:27:43 +00001696 if (!getCursorDecl(C))
1697 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001698
Douglas Gregora7bde202010-01-19 00:34:46 +00001699 Decl *D = getCursorDecl(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001700 return cxloc::translateSourceRange(D->getASTContext(), D->getSourceRange());
Douglas Gregora7bde202010-01-19 00:34:46 +00001701}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001702
1703CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001704 if (clang_isInvalid(C.kind))
1705 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001706
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001707 ASTUnit *CXXUnit = getCursorASTUnit(C);
Douglas Gregorb6998662010-01-19 19:34:47 +00001708 if (clang_isDeclaration(C.kind))
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001709 return C;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001710
Douglas Gregor97b98722010-01-19 23:20:36 +00001711 if (clang_isExpression(C.kind)) {
1712 Decl *D = getDeclFromExpr(getCursorExpr(C));
1713 if (D)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001714 return MakeCXCursor(D, CXXUnit);
Douglas Gregor97b98722010-01-19 23:20:36 +00001715 return clang_getNullCursor();
1716 }
1717
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001718 if (!clang_isReference(C.kind))
1719 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001720
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001721 switch (C.kind) {
1722 case CXCursor_ObjCSuperClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001723 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001724
1725 case CXCursor_ObjCProtocolRef: {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001726 return MakeCXCursor(getCursorObjCProtocolRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001727
1728 case CXCursor_ObjCClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001729 return MakeCXCursor(getCursorObjCClassRef(C).first, CXXUnit);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001730
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001731 case CXCursor_TypeRef:
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001732 return MakeCXCursor(getCursorTypeRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001733
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001734 default:
1735 // We would prefer to enumerate all non-reference cursor kinds here.
1736 llvm_unreachable("Unhandled reference cursor kind");
1737 break;
1738 }
1739 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001740
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001741 return clang_getNullCursor();
1742}
1743
Douglas Gregorb6998662010-01-19 19:34:47 +00001744CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001745 if (clang_isInvalid(C.kind))
1746 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001747
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001748 ASTUnit *CXXUnit = getCursorASTUnit(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001749
Douglas Gregorb6998662010-01-19 19:34:47 +00001750 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00001751 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00001752 C = clang_getCursorReferenced(C);
1753 WasReference = true;
1754 }
1755
1756 if (!clang_isDeclaration(C.kind))
1757 return clang_getNullCursor();
1758
1759 Decl *D = getCursorDecl(C);
1760 if (!D)
1761 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001762
Douglas Gregorb6998662010-01-19 19:34:47 +00001763 switch (D->getKind()) {
1764 // Declaration kinds that don't really separate the notions of
1765 // declaration and definition.
1766 case Decl::Namespace:
1767 case Decl::Typedef:
1768 case Decl::TemplateTypeParm:
1769 case Decl::EnumConstant:
1770 case Decl::Field:
1771 case Decl::ObjCIvar:
1772 case Decl::ObjCAtDefsField:
1773 case Decl::ImplicitParam:
1774 case Decl::ParmVar:
1775 case Decl::NonTypeTemplateParm:
1776 case Decl::TemplateTemplateParm:
1777 case Decl::ObjCCategoryImpl:
1778 case Decl::ObjCImplementation:
1779 case Decl::LinkageSpec:
1780 case Decl::ObjCPropertyImpl:
1781 case Decl::FileScopeAsm:
1782 case Decl::StaticAssert:
1783 case Decl::Block:
1784 return C;
1785
1786 // Declaration kinds that don't make any sense here, but are
1787 // nonetheless harmless.
1788 case Decl::TranslationUnit:
1789 case Decl::Template:
1790 case Decl::ObjCContainer:
1791 break;
1792
1793 // Declaration kinds for which the definition is not resolvable.
1794 case Decl::UnresolvedUsingTypename:
1795 case Decl::UnresolvedUsingValue:
1796 break;
1797
1798 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001799 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
1800 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001801
1802 case Decl::NamespaceAlias:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001803 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001804
1805 case Decl::Enum:
1806 case Decl::Record:
1807 case Decl::CXXRecord:
1808 case Decl::ClassTemplateSpecialization:
1809 case Decl::ClassTemplatePartialSpecialization:
Douglas Gregor952b0172010-02-11 01:04:33 +00001810 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001811 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001812 return clang_getNullCursor();
1813
1814 case Decl::Function:
1815 case Decl::CXXMethod:
1816 case Decl::CXXConstructor:
1817 case Decl::CXXDestructor:
1818 case Decl::CXXConversion: {
1819 const FunctionDecl *Def = 0;
1820 if (cast<FunctionDecl>(D)->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001821 return MakeCXCursor(const_cast<FunctionDecl *>(Def), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001822 return clang_getNullCursor();
1823 }
1824
1825 case Decl::Var: {
Sebastian Redl31310a22010-02-01 20:16:42 +00001826 // Ask the variable if it has a definition.
1827 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
1828 return MakeCXCursor(Def, CXXUnit);
1829 return clang_getNullCursor();
Douglas Gregorb6998662010-01-19 19:34:47 +00001830 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001831
Douglas Gregorb6998662010-01-19 19:34:47 +00001832 case Decl::FunctionTemplate: {
1833 const FunctionDecl *Def = 0;
1834 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001835 return MakeCXCursor(Def->getDescribedFunctionTemplate(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001836 return clang_getNullCursor();
1837 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001838
Douglas Gregorb6998662010-01-19 19:34:47 +00001839 case Decl::ClassTemplate: {
1840 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
Douglas Gregor952b0172010-02-11 01:04:33 +00001841 ->getDefinition())
Douglas Gregorb6998662010-01-19 19:34:47 +00001842 return MakeCXCursor(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001843 cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001844 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001845 return clang_getNullCursor();
1846 }
1847
1848 case Decl::Using: {
1849 UsingDecl *Using = cast<UsingDecl>(D);
1850 CXCursor Def = clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001851 for (UsingDecl::shadow_iterator S = Using->shadow_begin(),
1852 SEnd = Using->shadow_end();
Douglas Gregorb6998662010-01-19 19:34:47 +00001853 S != SEnd; ++S) {
1854 if (Def != clang_getNullCursor()) {
1855 // FIXME: We have no way to return multiple results.
1856 return clang_getNullCursor();
1857 }
1858
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001859 Def = clang_getCursorDefinition(MakeCXCursor((*S)->getTargetDecl(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001860 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00001861 }
1862
1863 return Def;
1864 }
1865
1866 case Decl::UsingShadow:
1867 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001868 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001869 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00001870
1871 case Decl::ObjCMethod: {
1872 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
1873 if (Method->isThisDeclarationADefinition())
1874 return C;
1875
1876 // Dig out the method definition in the associated
1877 // @implementation, if we have it.
1878 // FIXME: The ASTs should make finding the definition easier.
1879 if (ObjCInterfaceDecl *Class
1880 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
1881 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
1882 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
1883 Method->isInstanceMethod()))
1884 if (Def->isThisDeclarationADefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001885 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001886
1887 return clang_getNullCursor();
1888 }
1889
1890 case Decl::ObjCCategory:
1891 if (ObjCCategoryImplDecl *Impl
1892 = cast<ObjCCategoryDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001893 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001894 return clang_getNullCursor();
1895
1896 case Decl::ObjCProtocol:
1897 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
1898 return C;
1899 return clang_getNullCursor();
1900
1901 case Decl::ObjCInterface:
1902 // There are two notions of a "definition" for an Objective-C
1903 // class: the interface and its implementation. When we resolved a
1904 // reference to an Objective-C class, produce the @interface as
1905 // the definition; when we were provided with the interface,
1906 // produce the @implementation as the definition.
1907 if (WasReference) {
1908 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
1909 return C;
1910 } else if (ObjCImplementationDecl *Impl
1911 = cast<ObjCInterfaceDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001912 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001913 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001914
Douglas Gregorb6998662010-01-19 19:34:47 +00001915 case Decl::ObjCProperty:
1916 // FIXME: We don't really know where to find the
1917 // ObjCPropertyImplDecls that implement this property.
1918 return clang_getNullCursor();
1919
1920 case Decl::ObjCCompatibleAlias:
1921 if (ObjCInterfaceDecl *Class
1922 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
1923 if (!Class->isForwardDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001924 return MakeCXCursor(Class, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001925
Douglas Gregorb6998662010-01-19 19:34:47 +00001926 return clang_getNullCursor();
1927
1928 case Decl::ObjCForwardProtocol: {
1929 ObjCForwardProtocolDecl *Forward = cast<ObjCForwardProtocolDecl>(D);
1930 if (Forward->protocol_size() == 1)
1931 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001932 MakeCXCursor(*Forward->protocol_begin(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001933 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00001934
1935 // FIXME: Cannot return multiple definitions.
1936 return clang_getNullCursor();
1937 }
1938
1939 case Decl::ObjCClass: {
1940 ObjCClassDecl *Class = cast<ObjCClassDecl>(D);
1941 if (Class->size() == 1) {
1942 ObjCInterfaceDecl *IFace = Class->begin()->getInterface();
1943 if (!IFace->isForwardDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001944 return MakeCXCursor(IFace, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001945 return clang_getNullCursor();
1946 }
1947
1948 // FIXME: Cannot return multiple definitions.
1949 return clang_getNullCursor();
1950 }
1951
1952 case Decl::Friend:
1953 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001954 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00001955 return clang_getNullCursor();
1956
1957 case Decl::FriendTemplate:
1958 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001959 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00001960 return clang_getNullCursor();
1961 }
1962
1963 return clang_getNullCursor();
1964}
1965
1966unsigned clang_isCursorDefinition(CXCursor C) {
1967 if (!clang_isDeclaration(C.kind))
1968 return 0;
1969
1970 return clang_getCursorDefinition(C) == C;
1971}
1972
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001973void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00001974 const char **startBuf,
1975 const char **endBuf,
1976 unsigned *startLine,
1977 unsigned *startColumn,
1978 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001979 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00001980 assert(getCursorDecl(C) && "CXCursor has null decl");
1981 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00001982 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
1983 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001984
Steve Naroff4ade6d62009-09-23 17:52:52 +00001985 SourceManager &SM = FD->getASTContext().getSourceManager();
1986 *startBuf = SM.getCharacterData(Body->getLBracLoc());
1987 *endBuf = SM.getCharacterData(Body->getRBracLoc());
1988 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
1989 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
1990 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
1991 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
1992}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001993
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001994void clang_enableStackTraces(void) {
1995 llvm::sys::PrintStackTraceOnErrorSignal();
1996}
1997
Ted Kremenekfb480492010-01-13 21:46:36 +00001998} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00001999
Ted Kremenekfb480492010-01-13 21:46:36 +00002000//===----------------------------------------------------------------------===//
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002001// Token-based Operations.
2002//===----------------------------------------------------------------------===//
2003
2004/* CXToken layout:
2005 * int_data[0]: a CXTokenKind
2006 * int_data[1]: starting token location
2007 * int_data[2]: token length
2008 * int_data[3]: reserved
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002009 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002010 * otherwise unused.
2011 */
2012extern "C" {
2013
2014CXTokenKind clang_getTokenKind(CXToken CXTok) {
2015 return static_cast<CXTokenKind>(CXTok.int_data[0]);
2016}
2017
2018CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
2019 switch (clang_getTokenKind(CXTok)) {
2020 case CXToken_Identifier:
2021 case CXToken_Keyword:
2022 // We know we have an IdentifierInfo*, so use that.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002023 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
2024 ->getNameStart());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002025
2026 case CXToken_Literal: {
2027 // We have stashed the starting pointer in the ptr_data field. Use it.
2028 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002029 return createCXString(llvm::StringRef(Text, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002030 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002031
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002032 case CXToken_Punctuation:
2033 case CXToken_Comment:
2034 break;
2035 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002036
2037 // We have to find the starting buffer pointer the hard way, by
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002038 // deconstructing the source location.
2039 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2040 if (!CXXUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002041 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002042
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002043 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
2044 std::pair<FileID, unsigned> LocInfo
2045 = CXXUnit->getSourceManager().getDecomposedLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +00002046 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002047 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00002048 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
2049 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00002050 return createCXString("");
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002051
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002052 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002053}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002054
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002055CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
2056 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2057 if (!CXXUnit)
2058 return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002059
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002060 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
2061 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
2062}
2063
2064CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
2065 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregor5352ac02010-01-28 00:27:43 +00002066 if (!CXXUnit)
2067 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002068
2069 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002070 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
2071}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002072
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002073void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
2074 CXToken **Tokens, unsigned *NumTokens) {
2075 if (Tokens)
2076 *Tokens = 0;
2077 if (NumTokens)
2078 *NumTokens = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002079
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002080 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2081 if (!CXXUnit || !Tokens || !NumTokens)
2082 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002083
Douglas Gregorbdf60622010-03-05 21:16:25 +00002084 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
2085
Daniel Dunbar85b988f2010-02-14 08:31:57 +00002086 SourceRange R = cxloc::translateCXSourceRange(Range);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002087 if (R.isInvalid())
2088 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002089
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002090 SourceManager &SourceMgr = CXXUnit->getSourceManager();
2091 std::pair<FileID, unsigned> BeginLocInfo
2092 = SourceMgr.getDecomposedLoc(R.getBegin());
2093 std::pair<FileID, unsigned> EndLocInfo
2094 = SourceMgr.getDecomposedLoc(R.getEnd());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002095
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002096 // Cannot tokenize across files.
2097 if (BeginLocInfo.first != EndLocInfo.first)
2098 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002099
2100 // Create a lexer
Douglas Gregorf715ca12010-03-16 00:06:06 +00002101 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002102 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00002103 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
Douglas Gregor47a3fcd2010-03-16 20:26:15 +00002104 if (Invalid)
2105 return;
Douglas Gregoraea67db2010-03-15 22:54:52 +00002106
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002107 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
2108 CXXUnit->getASTContext().getLangOptions(),
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002109 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002110 Lex.SetCommentRetentionState(true);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002111
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002112 // Lex tokens until we hit the end of the range.
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002113 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002114 llvm::SmallVector<CXToken, 32> CXTokens;
2115 Token Tok;
2116 do {
2117 // Lex the next token
2118 Lex.LexFromRawLexer(Tok);
2119 if (Tok.is(tok::eof))
2120 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002121
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002122 // Initialize the CXToken.
2123 CXToken CXTok;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002124
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002125 // - Common fields
2126 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
2127 CXTok.int_data[2] = Tok.getLength();
2128 CXTok.int_data[3] = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002129
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002130 // - Kind-specific fields
2131 if (Tok.isLiteral()) {
2132 CXTok.int_data[0] = CXToken_Literal;
2133 CXTok.ptr_data = (void *)Tok.getLiteralData();
2134 } else if (Tok.is(tok::identifier)) {
Douglas Gregoraea67db2010-03-15 22:54:52 +00002135 // Lookup the identifier to determine whether we have a keyword.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002136 std::pair<FileID, unsigned> LocInfo
2137 = SourceMgr.getDecomposedLoc(Tok.getLocation());
Douglas Gregorf715ca12010-03-16 00:06:06 +00002138 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002139 llvm::StringRef Buf
Douglas Gregorf715ca12010-03-16 00:06:06 +00002140 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
2141 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00002142 return;
2143
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002144 const char *StartPos = Buf.data() + LocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002145 IdentifierInfo *II
2146 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok, StartPos);
2147 CXTok.int_data[0] = II->getTokenID() == tok::identifier?
2148 CXToken_Identifier
2149 : CXToken_Keyword;
2150 CXTok.ptr_data = II;
2151 } else if (Tok.is(tok::comment)) {
2152 CXTok.int_data[0] = CXToken_Comment;
2153 CXTok.ptr_data = 0;
2154 } else {
2155 CXTok.int_data[0] = CXToken_Punctuation;
2156 CXTok.ptr_data = 0;
2157 }
2158 CXTokens.push_back(CXTok);
2159 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002160
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002161 if (CXTokens.empty())
2162 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002163
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002164 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
2165 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
2166 *NumTokens = CXTokens.size();
2167}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002168
2169typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
2170
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002171enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
2172 CXCursor parent,
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002173 CXClientData client_data) {
2174 AnnotateTokensData *Data = static_cast<AnnotateTokensData *>(client_data);
2175
2176 // We only annotate the locations of declarations, simple
2177 // references, and expressions which directly reference something.
2178 CXCursorKind Kind = clang_getCursorKind(cursor);
2179 if (clang_isDeclaration(Kind) || clang_isReference(Kind)) {
2180 // Okay: We can annotate the location of this declaration with the
2181 // declaration or reference
2182 } else if (clang_isExpression(cursor.kind)) {
2183 if (Kind != CXCursor_DeclRefExpr &&
2184 Kind != CXCursor_MemberRefExpr &&
2185 Kind != CXCursor_ObjCMessageExpr)
2186 return CXChildVisit_Recurse;
2187
2188 CXCursor Referenced = clang_getCursorReferenced(cursor);
2189 if (Referenced == cursor || Referenced == clang_getNullCursor())
2190 return CXChildVisit_Recurse;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002191
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002192 // Okay: we can annotate the location of this expression
2193 } else {
2194 // Nothing to annotate
2195 return CXChildVisit_Recurse;
2196 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002197
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002198 CXSourceLocation Loc = clang_getCursorLocation(cursor);
2199 (*Data)[Loc.int_data] = cursor;
2200 return CXChildVisit_Recurse;
2201}
2202
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002203void clang_annotateTokens(CXTranslationUnit TU,
2204 CXToken *Tokens, unsigned NumTokens,
2205 CXCursor *Cursors) {
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002206 if (NumTokens == 0)
2207 return;
2208
2209 // Any token we don't specifically annotate will have a NULL cursor.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002210 for (unsigned I = 0; I != NumTokens; ++I)
2211 Cursors[I] = clang_getNullCursor();
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002212
2213 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2214 if (!CXXUnit || !Tokens)
2215 return;
2216
Douglas Gregorbdf60622010-03-05 21:16:25 +00002217 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
2218
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002219 // Annotate all of the source locations in the region of interest that map
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002220 SourceRange RegionOfInterest;
2221 RegionOfInterest.setBegin(
2222 cxloc::translateSourceLocation(clang_getTokenLocation(TU, Tokens[0])));
2223 SourceLocation End
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002224 = cxloc::translateSourceLocation(clang_getTokenLocation(TU,
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002225 Tokens[NumTokens - 1]));
Daniel Dunbard52864b2010-02-14 10:02:57 +00002226 RegionOfInterest.setEnd(CXXUnit->getPreprocessor().getLocForEndOfToken(End));
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002227 // FIXME: Would be great to have a "hint" cursor, then walk from that
2228 // hint cursor upward until we find a cursor whose source range encloses
2229 // the region of interest, rather than starting from the translation unit.
2230 AnnotateTokensData Annotated;
2231 CXCursor Parent = clang_getTranslationUnitCursor(CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002232 CursorVisitor AnnotateVis(CXXUnit, AnnotateTokensVisitor, &Annotated,
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002233 Decl::MaxPCHLevel, RegionOfInterest);
2234 AnnotateVis.VisitChildren(Parent);
2235
2236 for (unsigned I = 0; I != NumTokens; ++I) {
2237 // Determine whether we saw a cursor at this token's location.
2238 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
2239 if (Pos == Annotated.end())
2240 continue;
2241
2242 Cursors[I] = Pos->second;
2243 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002244}
2245
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002246void clang_disposeTokens(CXTranslationUnit TU,
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002247 CXToken *Tokens, unsigned NumTokens) {
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002248 free(Tokens);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002249}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002250
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002251} // end: extern "C"
2252
2253//===----------------------------------------------------------------------===//
Ted Kremenek16b42592010-03-03 06:36:57 +00002254// Operations for querying linkage of a cursor.
2255//===----------------------------------------------------------------------===//
2256
2257extern "C" {
2258CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
2259 Decl *D = cxcursor::getCursorDecl(cursor);
2260 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
2261 switch (ND->getLinkage()) {
2262 case NoLinkage: return CXLinkage_NoLinkage;
2263 case InternalLinkage: return CXLinkage_Internal;
2264 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
2265 case ExternalLinkage: return CXLinkage_External;
2266 };
2267
2268 return CXLinkage_Invalid;
2269}
2270} // end: extern "C"
2271
2272//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00002273// CXString Operations.
2274//===----------------------------------------------------------------------===//
2275
2276extern "C" {
2277const char *clang_getCString(CXString string) {
2278 return string.Spelling;
2279}
2280
2281void clang_disposeString(CXString string) {
2282 if (string.MustFreeString && string.Spelling)
2283 free((void*)string.Spelling);
2284}
Ted Kremenek04bb7162010-01-22 22:44:15 +00002285
Ted Kremenekfb480492010-01-13 21:46:36 +00002286} // end: extern "C"
Ted Kremenek04bb7162010-01-22 22:44:15 +00002287
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002288namespace clang { namespace cxstring {
2289CXString createCXString(const char *String, bool DupString){
2290 CXString Str;
2291 if (DupString) {
2292 Str.Spelling = strdup(String);
2293 Str.MustFreeString = 1;
2294 } else {
2295 Str.Spelling = String;
2296 Str.MustFreeString = 0;
2297 }
2298 return Str;
2299}
2300
2301CXString createCXString(llvm::StringRef String, bool DupString) {
2302 CXString Result;
2303 if (DupString || (!String.empty() && String.data()[String.size()] != 0)) {
2304 char *Spelling = (char *)malloc(String.size() + 1);
2305 memmove(Spelling, String.data(), String.size());
2306 Spelling[String.size()] = 0;
2307 Result.Spelling = Spelling;
2308 Result.MustFreeString = 1;
2309 } else {
2310 Result.Spelling = String.data();
2311 Result.MustFreeString = 0;
2312 }
2313 return Result;
2314}
2315}}
2316
Ted Kremenek04bb7162010-01-22 22:44:15 +00002317//===----------------------------------------------------------------------===//
2318// Misc. utility functions.
2319//===----------------------------------------------------------------------===//
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002320
Ted Kremenek04bb7162010-01-22 22:44:15 +00002321extern "C" {
2322
Ted Kremeneka2a9d6e2010-02-12 22:54:40 +00002323CXString clang_getClangVersion() {
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002324 return createCXString(getClangFullVersion());
Ted Kremenek04bb7162010-01-22 22:44:15 +00002325}
2326
2327} // end: extern "C"